1 /* 2 * Copyright (C) 2021 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 android.net.vcn.persistablebundleutils; 18 19 import java.io.ByteArrayInputStream; 20 import java.io.InputStream; 21 import java.security.KeyFactory; 22 import java.security.NoSuchAlgorithmException; 23 import java.security.cert.CertificateException; 24 import java.security.cert.CertificateFactory; 25 import java.security.cert.X509Certificate; 26 import java.security.interfaces.RSAPrivateKey; 27 import java.security.spec.InvalidKeySpecException; 28 import java.security.spec.PKCS8EncodedKeySpec; 29 import java.util.Objects; 30 31 /** 32 * CertUtils provides utility methods for constructing Certificate and PrivateKey. 33 * 34 * @hide 35 */ 36 public class CertUtils { 37 private static final String CERT_TYPE_X509 = "X.509"; 38 private static final String PRIVATE_KEY_TYPE_RSA = "RSA"; 39 40 /** Decodes an ASN.1 DER encoded Certificate */ certificateFromByteArray(byte[] derEncoded)41 public static X509Certificate certificateFromByteArray(byte[] derEncoded) { 42 Objects.requireNonNull(derEncoded, "derEncoded is null"); 43 44 try { 45 CertificateFactory certFactory = CertificateFactory.getInstance(CERT_TYPE_X509); 46 InputStream in = new ByteArrayInputStream(derEncoded); 47 return (X509Certificate) certFactory.generateCertificate(in); 48 } catch (CertificateException e) { 49 throw new IllegalArgumentException("Fail to decode certificate", e); 50 } 51 } 52 53 /** Decodes a PKCS#8 encoded RSA private key */ privateKeyFromByteArray(byte[] pkcs8Encoded)54 public static RSAPrivateKey privateKeyFromByteArray(byte[] pkcs8Encoded) { 55 Objects.requireNonNull(pkcs8Encoded, "pkcs8Encoded was null"); 56 PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8Encoded); 57 58 try { 59 KeyFactory keyFactory = KeyFactory.getInstance(PRIVATE_KEY_TYPE_RSA); 60 61 return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec); 62 } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 63 throw new IllegalArgumentException("Fail to decode PrivateKey", e); 64 } 65 } 66 } 67