Example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier.

Prototype

ASN1ObjectIdentifier SubjectKeyIdentifier

To view the source code for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier.

Click Source Link

Document

Subject Key Identifier

Usage

From source file:com.eucalyptus.auth.crypto.DefaultCryptoProvider.java

License:Open Source License

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey) {//from  w  w w .ja  va2  s.c o  m
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

License:Open Source License

@Override
public X509Certificate generateCertificate(PublicKey key, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    if (signingKey == null) {
        LOG.error("No signing key is provided");
        return null;
    }/* www .  j  ava2  s.  c o  m*/
    if (signer == null) {
        LOG.error("No signiner principal is specified");
        return null;
    }
    if (subjectDn == null) {
        LOG.error("No subject principal is specified");
        return null;
    }
    if (key == null) {
        LOG.error("No requesting key is specified");
        return null;
    }

    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(key));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(key);
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

License:Open Source License

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);/*from   w w w  .j a v a  2  s. co  m*/
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:com.example.androidtest.SslUtil.java

License:Open Source License

/**
 * Generates a new, self-signed X509 V3 certificate for a KeyPair.
 * //from  w  w w . j  av  a2s .  c  o m
 * @param  pair                      the {@link KeyPair} to be used
 * @param  name                      X.500 distinguished name
 * @param  notBefore                 not valid before this date
 * @param  notAfter                  not valid after this date
 * @param  serialNumber              serial number
 * @return                           the new certificate
 * @throws GeneralSecurityException  on error generating the certificate
 */
@SuppressWarnings("deprecation")
public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore,
        Date notAfter, BigInteger serialNumber) throws GeneralSecurityException {
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Name dnName = new X509Name(name);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // For self-signed certificates, OpenSSL 0.9.6 has specific requirements
    // about certificate and extension content.  Quoting the `man verify`:
    //
    //   In OpenSSL 0.9.6 and later all certificates whose subject name matches
    //   the issuer name of the current certificate are subject to further
    //   tests. The relevant authority key identifier components of the current
    //   certificate (if present) must match the subject key identifier (if
    //   present) and issuer and serial number of the candidate issuer, in
    //   addition the keyUsage extension of the candidate issuer (if present)
    //   must permit certificate signing.
    //
    // In the code that follows,
    //   - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign);
    //   - the Authority Key Identifier extension is added, matching the
    //     subject key identifier, and using the issuer, and serial number.

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(pair.getPublic(), dnName,
            serialNumber);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true, authIdentifier);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "googletv@test.test")));

    // This method is deprecated, but Android Eclair does not provide the 
    // generate() methods.
    X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), "BC");
    return cert;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java

License:Open Source License

private X509Certificate generateCertificateToEntity(EntityAuthentication entity, DataMoverSessionID sessionID)
        throws SSLPeerUnverifiedException, CertificateParsingException, CertificateEncodingException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException,
        KeyStoreException, UnrecoverableKeyException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=" + entity.getEntityID().toString());

    certGen.setSerialNumber(sessionID.toBigInteger());
    X509Certificate rootCertificate = null;
    for (X509Certificate checkCertificate : trustedServerCertificates.values()) {
        try {//w w  w  .j a  v  a 2 s  . c om
            entity.getCertificate().verify(checkCertificate.getPublicKey(), "BC");
            rootCertificate = checkCertificate;
            break;
        } catch (GeneralSecurityException e) {
            Logger.getLogger(getClass()).debug(new ErrorLogMessage("Skipping certificate {0}",
                    (Serializable) checkCertificate.getSubjectDN().getName()));
        }
    }
    if (rootCertificate == null)
        throw new SSLPeerUnverifiedException("No certificates authenticated");
    certGen.setIssuerDN(rootCertificate.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 60L * 60L * 1000L));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + (365L * 24L * 60L * 1000L)));
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(entity.getCertificate().getPublicKey());
    certGen.setSignatureAlgorithm(EntityAuthenticationServer.kCertificateSignatureAlg);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCertificate));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entity.getCertificate().getPublicKey()));
    byte[] sessionIDBytes = new byte[DataMoverSessionID.kTotalBytes];
    sessionID.getBytes(sessionIDBytes, 0);
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, sessionIDBytes);
    byte[] issuerIDBytes = new byte[EntityID.kTotalBytes];
    clientIdentity.getBytes(issuerIDBytes, 0);
    certGen.addExtension(X509Extensions.IssuerAlternativeName, false, issuerIDBytes);

    X509Certificate cert = certGen.generate((PrivateKey) persistentKeyStore
            .getKey(kPrivateKeyAliasPrefix + id.toString(), kDefaultKeyStorePassword.toCharArray()), "BC");
    return cert;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationServerCore.java

License:Open Source License

public EntityAuthentication authenticateServer(EntityID serverID, byte[] encodedCertReq)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, UnrecoverableKeyException,
        KeyStoreException, IOException, CertificateParsingException, ServerNotRegisteredException,
        AuthenticationFailureException {
    Date startDate = new Date(System.currentTimeMillis() - (60L * 60L * 1000L)); // time from which certificate is valid
    Date expiryDate = new Date(startDate.getTime() + (30L * 24L * 60L * 60L * 1000L)); // time after which certificate is not valid
    BigInteger serialNumber = serverID.toBigInteger(); // serial number for certificate

    EntityAuthentication returnAuthentication = null;

    Certificate registeredCertificate = keyStore.getCertificate(serverID.toString());
    if (registeredCertificate != null) {
        PublicKey checkKey = registeredCertificate.getPublicKey();
        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest(encodedCertReq);
        if (checkKey != null) {
            byte[] encodedCheckKey = checkKey.getEncoded();
            byte[] encodedCertKey = certReq.getPublicKey().getEncoded();
            if (Arrays.equals(encodedCheckKey, encodedCertKey)) {
                X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
                X500Principal dnName = new X500Principal(
                        EntityAuthenticationClient.kEntityIDCNPrefix + serverID.toString());

                certGen.setSerialNumber(serialNumber);
                certGen.setIssuerDN(rootCertificate.getSubjectX500Principal());
                certGen.setNotBefore(startDate);
                certGen.setNotAfter(expiryDate);
                certGen.setSubjectDN(dnName); // note: same as issuer
                certGen.setPublicKey(certReq.getPublicKey());
                certGen.setSignatureAlgorithm(kCertificateSignatureAlg);

                certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                        new AuthorityKeyIdentifierStructure(rootCertificate));
                certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                        new SubjectKeyIdentifierStructure(certReq.getPublicKey()));

                X509Certificate cert = certGen.generate(signingKey, "BC");
                returnAuthentication = new EntityAuthentication(cert);
            } else {
                logger.error(new ErrorLogMessage(
                        "Server {0} requesting authentication, but registered key does not match", serverID));
                throw new AuthenticationFailureException();
            }//w ww . jav  a  2s . c o  m
        } else {
            logger.error(new ErrorLogMessage(
                    "Server {0} requesting authentication, no check key found in registered certificate",
                    serverID));
            throw new AuthenticationFailureException();
        }
    } else {
        logger.error(new ErrorLogMessage("Server {0} requesting authentication, but not registered", serverID));
        throw new ServerNotRegisteredException();
    }
    return returnAuthentication;
}

From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java

License:Apache License

/**
 * Set Subject Key Identifier (RFC3280 4.2.1.2). The RFC says that final
 * certs should not include SKIDs but it doesn't prohibit them and they make
 * it a lot easier to locate those certificates in a database.
 * /*from ww  w  .  java  2 s  .co m*/
 * @throws InvalidKeyException
 */
protected final void setSKID() throws InvalidKeyException {
    SubjectKeyIdentifierStructure skis = new SubjectKeyIdentifierStructure(pubkey);
    generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, skis);
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

License:Open Source License

/**
 * @param gen/*from   ww  w  .j  av a 2s.c  o m*/
 * @param pubKey
 *
 * @throws IOException
 */
private static void addSubjectKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);
            gen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.streamreduce.util.CAGenerator.java

License:Apache License

public static X509Certificate generateCACert(KeyPair keyPair) throws Exception {
    Date startDate = new Date(System.currentTimeMillis()); // time from which certificate is valid
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 1000 * 365);
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis())); // serial number for certificate

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=Nodeable Client");

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);/*ww w  . j a v  a 2  s .  c  o  m*/
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("MD5withRSA");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    return certGen.generate(keyPair.getPrivate()); // note: private key of CA
}

From source file:cybervillains.ca.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * //from   www .  ja  v a  2 s  . co m
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    // Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen
            .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    // Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DERSequence typicalCAExtendedKeyUsages = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth),
                    new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning),
                    new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown) });

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, typicalCAExtendedKeyUsages);

    X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}