| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 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 |
|
| 33 |
|
| 34 |
|
| 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 |
|
| 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 |
|
| 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 |
} |