Search in sources :

Example 11 with X509V3CertificateGenerator

use of com.android.org.bouncycastle.x509.X509V3CertificateGenerator in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreTest method generateCertificate.

@SuppressWarnings("deprecation")
private static X509Certificate generateCertificate(android.security.KeyStore keyStore, String alias, BigInteger serialNumber, X500Principal subjectDN, Date notBefore, Date notAfter) throws Exception {
    final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + alias;
    KeyPair keyPair = AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(keyStore, privateKeyAlias, KeyStore.UID_SELF);
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSerialNumber(serialNumber);
    certGen.setSubjectDN(subjectDN);
    certGen.setIssuerDN(subjectDN);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSignatureAlgorithm("sha1WithRSA");
    final X509Certificate cert = certGen.generate(keyPair.getPrivate());
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) X509Certificate(java.security.cert.X509Certificate)

Example 12 with X509V3CertificateGenerator

use of com.android.org.bouncycastle.x509.X509V3CertificateGenerator in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyPairGenerator method generateKeyPair.

/**
     * Generate a KeyPair which is backed by the Android keystore service. You
     * must call {@link KeyPairGenerator#initialize(AlgorithmParameterSpec)}
     * with an {@link KeyPairGeneratorSpec} as the {@code params}
     * argument before calling this otherwise an {@code IllegalStateException}
     * will be thrown.
     * <p>
     * This will create an entry in the Android keystore service with a
     * self-signed certificate using the {@code params} specified in the
     * {@code initialize(params)} call.
     *
     * @throws IllegalStateException when called before calling
     *             {@link KeyPairGenerator#initialize(AlgorithmParameterSpec)}
     * @see java.security.KeyPairGeneratorSpi#generateKeyPair()
     */
@Override
public KeyPair generateKeyPair() {
    if (mKeyStore == null || mSpec == null) {
        throw new IllegalStateException("Must call initialize with an android.security.KeyPairGeneratorSpec first");
    }
    if (((mSpec.getFlags() & KeyStore.FLAG_ENCRYPTED) != 0) && (mKeyStore.state() != KeyStore.State.UNLOCKED)) {
        throw new IllegalStateException("Android keystore must be in initialized and unlocked state " + "if encryption is required");
    }
    final String alias = mSpec.getKeystoreAlias();
    Credentials.deleteAllTypesForAlias(mKeyStore, alias);
    final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + alias;
    if (!mKeyStore.generate(privateKeyAlias, KeyStore.UID_SELF, mSpec.getFlags())) {
        throw new IllegalStateException("could not generate key in keystore");
    }
    final PrivateKey privKey;
    final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
    try {
        privKey = engine.getPrivateKeyById(privateKeyAlias);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Can't get key", e);
    }
    final byte[] pubKeyBytes = mKeyStore.getPubkey(privateKeyAlias);
    final PublicKey pubKey;
    try {
        final KeyFactory keyFact = KeyFactory.getInstance("RSA");
        pubKey = keyFact.generatePublic(new X509EncodedKeySpec(pubKeyBytes));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Can't instantiate RSA key generator", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException("keystore returned invalid key encoding", e);
    }
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setPublicKey(pubKey);
    certGen.setSerialNumber(mSpec.getSerialNumber());
    certGen.setSubjectDN(mSpec.getSubjectDN());
    certGen.setIssuerDN(mSpec.getSubjectDN());
    certGen.setNotBefore(mSpec.getStartDate());
    certGen.setNotAfter(mSpec.getEndDate());
    certGen.setSignatureAlgorithm("sha1WithRSA");
    final X509Certificate cert;
    try {
        cert = certGen.generate(privKey);
    } catch (Exception e) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new IllegalStateException("Can't generate certificate", e);
    }
    byte[] certBytes;
    try {
        certBytes = cert.getEncoded();
    } catch (CertificateEncodingException e) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new IllegalStateException("Can't get encoding of certificate", e);
    }
    if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, certBytes, KeyStore.UID_SELF, mSpec.getFlags())) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new IllegalStateException("Can't store certificate in AndroidKeyStore");
    }
    return new KeyPair(pubKey, privKey);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OpenSSLEngine(org.apache.harmony.xnet.provider.jsse.OpenSSLEngine) KeyFactory(java.security.KeyFactory)

Example 13 with X509V3CertificateGenerator

use of com.android.org.bouncycastle.x509.X509V3CertificateGenerator in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method generateCertificate.

@SuppressWarnings("deprecation")
private static X509Certificate generateCertificate(android.security.KeyStore keyStore, String alias, BigInteger serialNumber, X500Principal subjectDN, Date notBefore, Date notAfter) throws Exception {
    final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + alias;
    final PrivateKey privKey;
    final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
    try {
        privKey = engine.getPrivateKeyById(privateKeyAlias);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Can't get key", e);
    }
    final byte[] pubKeyBytes = keyStore.getPubkey(privateKeyAlias);
    final PublicKey pubKey;
    try {
        final KeyFactory keyFact = KeyFactory.getInstance("RSA");
        pubKey = keyFact.generatePublic(new X509EncodedKeySpec(pubKeyBytes));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Can't instantiate RSA key generator", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException("keystore returned invalid key encoding", e);
    }
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setPublicKey(pubKey);
    certGen.setSerialNumber(serialNumber);
    certGen.setSubjectDN(subjectDN);
    certGen.setIssuerDN(subjectDN);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSignatureAlgorithm("sha1WithRSA");
    final X509Certificate cert = certGen.generate(privKey);
    return cert;
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OpenSSLEngine(org.apache.harmony.xnet.provider.jsse.OpenSSLEngine) KeyFactory(java.security.KeyFactory)

Example 14 with X509V3CertificateGenerator

use of com.android.org.bouncycastle.x509.X509V3CertificateGenerator in project robovm by robovm.

the class CertificateFactoryTest method generateCertificate.

@SuppressWarnings("deprecation")
private static KeyHolder generateCertificate(boolean isCa, KeyHolder issuer) throws Exception {
    Date startDate = new Date();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    // Jan 1, 2100 UTC
    cal.set(2100, 0, 1, 0, 0, 0);
    Date expiryDate = cal.getTime();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();
    BigInteger serial;
    X500Principal issuerPrincipal;
    X500Principal subjectPrincipal;
    PrivateKey caKey;
    if (issuer != null) {
        serial = issuer.certificate.getSerialNumber().add(BigInteger.ONE);
        subjectPrincipal = new X500Principal("CN=Test Certificate Serial #" + serial.toString());
        issuerPrincipal = issuer.certificate.getSubjectX500Principal();
        caKey = issuer.privateKey;
    } else {
        serial = BigInteger.ONE;
        subjectPrincipal = new X500Principal("CN=Test CA, O=Tests, C=US");
        issuerPrincipal = subjectPrincipal;
        caKey = keyPair.getPrivate();
    }
    BasicConstraints basicConstraints;
    if (isCa) {
        basicConstraints = new BasicConstraints(10 - serial.intValue());
    } else {
        basicConstraints = new BasicConstraints(false);
    }
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(serial);
    certGen.setIssuerDN(issuerPrincipal);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA1withRSA");
    if (issuer != null) {
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuer.certificate));
    } else {
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    }
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
    certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints);
    X509Certificate cert = certGen.generate(caKey);
    KeyHolder holder = new KeyHolder();
    holder.certificate = cert;
    holder.privateKey = keyPair.getPrivate();
    return holder;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) SubjectKeyIdentifierStructure(com.android.org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) GregorianCalendar(java.util.GregorianCalendar) KeyPairGenerator(java.security.KeyPairGenerator) AuthorityKeyIdentifierStructure(com.android.org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints)

Example 15 with X509V3CertificateGenerator

use of com.android.org.bouncycastle.x509.X509V3CertificateGenerator in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithValidSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithValidSignature(PrivateKey privateKey, PublicKey publicKey, String signatureAlgorithm) throws Exception {
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setPublicKey(publicKey);
    certGen.setSerialNumber(mSpec.getCertificateSerialNumber());
    certGen.setSubjectDN(mSpec.getCertificateSubject());
    certGen.setIssuerDN(mSpec.getCertificateSubject());
    certGen.setNotBefore(mSpec.getCertificateNotBefore());
    certGen.setNotAfter(mSpec.getCertificateNotAfter());
    certGen.setSignatureAlgorithm(signatureAlgorithm);
    return certGen.generate(privateKey);
}
Also used : X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator)

Aggregations

X509Certificate (java.security.cert.X509Certificate)16 X509V3CertificateGenerator (com.android.org.bouncycastle.x509.X509V3CertificateGenerator)14 KeyPair (java.security.KeyPair)9 X509V3CertificateGenerator (org.bouncycastle.x509.X509V3CertificateGenerator)8 X509Principal (org.bouncycastle.jce.X509Principal)7 Calendar (java.util.Calendar)6 BigInteger (java.math.BigInteger)4 KeyFactory (java.security.KeyFactory)3 KeyPairGenerator (java.security.KeyPairGenerator)3 PrivateKey (java.security.PrivateKey)3 Date (java.util.Date)3 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)3 BasicConstraints (com.android.org.bouncycastle.asn1.x509.BasicConstraints)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PublicKey (java.security.PublicKey)2 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)2 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)2 X500Principal (javax.security.auth.x500.X500Principal)2