1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.cts.verifier.security; 18 19 import android.content.Context; 20 import android.content.ContentResolver; 21 import android.content.ContentValues; 22 import android.content.res.AssetManager; 23 import android.net.Uri; 24 import android.provider.MediaStore; 25 26 import android.util.Log; 27 28 import java.io.File; 29 import java.io.FileOutputStream; 30 import java.io.OutputStream; 31 import java.io.IOException; 32 import java.io.InputStream; 33 34 public class CACertWriter { 35 static final String TAG = CACertWriter.class.getSimpleName(); 36 37 private static final String CERT_ASSET_NAME = "myCA.cer"; 38 extractCertToDownloads( Context applicationContext, AssetManager assetManager)39 public static boolean extractCertToDownloads( 40 Context applicationContext, AssetManager assetManager) { 41 // Use MediaStore API to write the CA cert to the Download folder 42 final ContentValues downloadValues = new ContentValues(); 43 downloadValues.put(MediaStore.MediaColumns.DISPLAY_NAME, CERT_ASSET_NAME); 44 45 Uri targetCollection = MediaStore.Downloads.EXTERNAL_CONTENT_URI; 46 ContentResolver resolver = applicationContext.getContentResolver(); 47 Uri toOpen = resolver.insert(targetCollection, downloadValues); 48 Log.i(TAG, String.format("Writing CA cert to %s", toOpen)); 49 50 InputStream is = null; 51 OutputStream os = null; 52 try { 53 try { 54 is = assetManager.open(CERT_ASSET_NAME); 55 os = resolver.openOutputStream(toOpen); 56 byte[] buffer = new byte[1024]; 57 int length; 58 while ((length = is.read(buffer)) > 0) { 59 os.write(buffer, 0, length); 60 } 61 } finally { 62 if (is != null) is.close(); 63 if (os != null) os.close(); 64 } 65 } catch (IOException ioe) { 66 Log.w(TAG, String.format("Problem moving cert file to %s", toOpen), ioe); 67 return false; 68 } 69 return true; 70 } 71 } 72