1 /* 2 * Copyright (C) 2019 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.internal.net.ipsec.ike.testutils; 18 19 import android.content.Context; 20 21 import androidx.test.InstrumentationRegistry; 22 23 import com.android.org.bouncycastle.util.io.pem.PemObject; 24 import com.android.org.bouncycastle.util.io.pem.PemReader; 25 26 import java.io.InputStream; 27 import java.io.InputStreamReader; 28 import java.security.KeyFactory; 29 import java.security.cert.CertificateFactory; 30 import java.security.cert.X509Certificate; 31 import java.security.interfaces.RSAPrivateKey; 32 import java.security.spec.PKCS8EncodedKeySpec; 33 34 /** CertUtils provides utility methods for creating X509 certificate and private key. */ 35 public final class CertUtils { 36 private static final String PEM_FOLDER_NAME = "pem"; 37 private static final String KEY_FOLDER_NAME = "key"; 38 39 /** Creates an X509Certificate with a pem file */ createCertFromPemFile(String fileName)40 public static X509Certificate createCertFromPemFile(String fileName) throws Exception { 41 Context context = InstrumentationRegistry.getContext(); 42 InputStream inputStream = 43 context.getResources().getAssets().open(PEM_FOLDER_NAME + "/" + fileName); 44 45 CertificateFactory factory = CertificateFactory.getInstance("X.509"); 46 return (X509Certificate) factory.generateCertificate(inputStream); 47 } 48 49 /** Creates an private key from a PKCS8 format key file */ createRsaPrivateKeyFromKeyFile(String fileName)50 public static RSAPrivateKey createRsaPrivateKeyFromKeyFile(String fileName) throws Exception { 51 Context context = InstrumentationRegistry.getContext(); 52 InputStream inputStream = 53 context.getResources().getAssets().open(KEY_FOLDER_NAME + "/" + fileName); 54 55 PemObject pemObject = new PemReader(new InputStreamReader(inputStream)).readPemObject(); 56 57 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 58 return (RSAPrivateKey) 59 keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pemObject.getContent())); 60 } 61 } 62