Example usage for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber

List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber

Introduction

In this page you can find the example usage for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber.

Prototype

public void setSerialNumber(BigInteger serialNumber) 

Source Link

Document

set the serial number for the certificate.

Usage

From source file:com.axelor.apps.account.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns an <code>X509Certificate</code> from a given
 * <code>KeyPair</code> and limit dates validations
 * @param keypair the given key pair// www .jav  a  2 s.co  m
 * @param issuer the certificate issuer
 * @param notBefore the begin validity date
 * @param notAfter the end validity date
 * @param keyusage the certificate key usage
 * @return the X509 certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage)
        throws GeneralSecurityException, IOException {
    X509V3CertificateGenerator generator;
    BigInteger serial;
    X509Certificate certificate;
    ASN1EncodableVector vector;

    serial = BigInteger.valueOf(generateSerial());
    generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serial);
    generator.setIssuerDN(new X509Principal(issuer));
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setSubjectDN(new X509Principal(issuer));
    generator.setPublicKey(keypair.getPublic());
    generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
    //generator.addExtension(X509Extensions.BasicConstraints,
    //                   false,
    //                   new BasicConstraints(true));
    /* generator.addExtension(X509Extensions.SubjectKeyIdentifier,
            false,
            getSubjectKeyIdentifier(keypair.getPublic()));
     generator.addExtension(X509Extensions.AuthorityKeyIdentifier,
              false,
              getAuthorityKeyIdentifier(keypair.
                                        getPublic(),
                                        issuer,
                                        serial));*/
    vector = new ASN1EncodableVector();
    vector.add(KeyPurposeId.id_kp_emailProtection);

    //generator.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new DERSequence(vector)));
    /*
        switch (keyusage) {
        case X509Constants.SIGNATURE_KEY_USAGE:
          generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
          break;
        case X509Constants.AUTHENTICATION_KEY_USAGE:
          generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
          break;
        case X509Constants.ENCRYPTION_KEY_USAGE:
          generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
          break;
        default:
          generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
          break;
        }*/

    certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
    certificate.checkValidity(new Date());
    certificate.verify(keypair.getPublic());

    return certificate;
}

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  ww .j  av  a  2  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.auth.util.KeyTool.java

License:Open Source License

public X509Certificate getCertificate(KeyPair keyPair, String certDn) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal dnName = new X500Principal(certDn);

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(dnName);//from  ww w .  j av a2 s . c  om
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(this.keySigningAlgorithm);
    try {
        X509Certificate cert = certGen.generate(keyPair.getPrivate(), PROVIDER);
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        System.exit(-3);
        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;
    }//from   w w  w .  j  av  a2 s .  co  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 .ja  v  a2  s . c om
    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  ww w.j  av a  2  s  .  co  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 {/*from   w w w. ja 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();
            }/*from ww  w  .  ja  va 2s  .  com*/
        } 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.integralblue.httpresponsecache.compat.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<GeneralName> subjectAltNames, Vector<GeneralSubtree> permittedNameConstraints,
        Vector<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;/*from   w  w w  .  j a  va 2s . com*/
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false,
                new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true,
                new NameConstraints(permittedNameConstraints, excludedNameConstraints));
    }

    if (privateKey instanceof ECPrivateKey) {
        /*
         * bouncycastle needs its own ECPrivateKey implementation
         */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:com.intirix.cloudpasswordmanager.services.ssl.CertPinningServiceImplUnitSpec.java

License:Apache License

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

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

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

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}