• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.internal.net.ipsec.ike.utils;
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 /** IkeCertUtils provides utility methods for decoding byte array of Certificate and PrivateKey */
32 public class IkeCertUtils {
33     private static final String CERT_TYPE_X509 = "X.509";
34     private static final String PRIVATE_KEY_TYPE_RSA = "RSA";
35 
36     /** Decodes an ASN.1 DER encoded Certificate */
certificateFromByteArray(byte[] derEncoded)37     public static X509Certificate certificateFromByteArray(byte[] derEncoded) {
38         Objects.requireNonNull(derEncoded, "derEncoded is null");
39 
40         try {
41             CertificateFactory certFactory = CertificateFactory.getInstance(CERT_TYPE_X509);
42             InputStream in = new ByteArrayInputStream(derEncoded);
43             return (X509Certificate) certFactory.generateCertificate(in);
44         } catch (CertificateException e) {
45             throw new IllegalArgumentException("Fail to decode certificate", e);
46         }
47     }
48 
49     /** Decodes a PKCS#8 encoded RSA private key */
privateKeyFromByteArray(byte[] pkcs8Encoded)50     public static RSAPrivateKey privateKeyFromByteArray(byte[] pkcs8Encoded) {
51         Objects.requireNonNull(pkcs8Encoded, "pkcs8Encoded is null");
52         PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8Encoded);
53 
54         try {
55             KeyFactory keyFactory = KeyFactory.getInstance(PRIVATE_KEY_TYPE_RSA);
56 
57             return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
58         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
59             throw new IllegalArgumentException("Fail to decode PrivateKey", e);
60         }
61     }
62 }
63