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.test.ike.testutils; 18 19 import android.content.Context; 20 21 import androidx.test.InstrumentationRegistry; 22 23 import com.android.internal.net.ipsec.test.ike.utils.IkeCertUtils; 24 25 import java.io.BufferedReader; 26 import java.io.InputStream; 27 import java.io.InputStreamReader; 28 import java.nio.charset.StandardCharsets; 29 import java.security.cert.CertificateFactory; 30 import java.security.cert.X509Certificate; 31 import java.security.interfaces.RSAPrivateKey; 32 import java.util.Base64; 33 import java.util.stream.Collectors; 34 35 /** CertUtils provides utility methods for creating X509 certificate and private key. */ 36 public final class CertUtils { 37 private static final String PEM_FOLDER_NAME = "pem"; 38 private static final String KEY_FOLDER_NAME = "key"; 39 private static final String NEW_LINE_CHAR = "\n"; 40 private static final String PEM_TYPE_PRIVATE_KEY = "-----(BEGIN|END) PRIVATE KEY-----"; 41 42 /** Creates an X509Certificate with a pem file */ createCertFromPemFile(String fileName)43 public static X509Certificate createCertFromPemFile(String fileName) throws Exception { 44 Context context = InstrumentationRegistry.getContext(); 45 InputStream inputStream = 46 context.getResources().getAssets().open(PEM_FOLDER_NAME + "/" + fileName); 47 48 CertificateFactory factory = CertificateFactory.getInstance("X.509"); 49 return (X509Certificate) factory.generateCertificate(inputStream); 50 } 51 52 /** Creates an private key from a PKCS8 format key file */ createRsaPrivateKeyFromKeyFile(String fileName)53 public static RSAPrivateKey createRsaPrivateKeyFromKeyFile(String fileName) throws Exception { 54 Context context = InstrumentationRegistry.getContext(); 55 InputStream inputStream = 56 context.getResources().getAssets().open(KEY_FOLDER_NAME + "/" + fileName); 57 58 String pemText = 59 new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) 60 .lines() 61 .collect(Collectors.joining(NEW_LINE_CHAR)); 62 63 byte[] certificateBytes = 64 Base64.getDecoder() 65 .decode( 66 pemText.replaceAll(PEM_TYPE_PRIVATE_KEY, "") 67 .replaceAll(NEW_LINE_CHAR, "") 68 .getBytes(StandardCharsets.UTF_8)); 69 return (RSAPrivateKey) IkeCertUtils.privateKeyFromByteArray(certificateBytes); 70 } 71 } 72