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

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

Introduction

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

Prototype

ASN1ObjectIdentifier AuthorityKeyIdentifier

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

Click Source Link

Document

Authority Key Identifier

Usage

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

License:Open Source License

/**
 * Generates a new, self-signed X509 V3 certificate for a KeyPair.
 * /*w  w w. jav  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 {/*w  w w. j a va 2 s . c  o  m*/
            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 w ww. j av  a2 s  . c  om*/
        } 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 Authority Key Identifier (RFC3280 4.2.1.1)
 * /*from ww  w . j  a  v  a  2  s  .com*/
 * @throws InvalidKeyException
 * @throws CertificateParsingException
 */
protected final void setAKID() throws InvalidKeyException, CertificateParsingException {
    if (issuer != null) {
        // signed certificates
        AuthorityKeyIdentifierStructure akis = new AuthorityKeyIdentifierStructure(issuer);
        generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, akis);
    } else {
        // self-signed certificates since we already require subjectDN =
        // issuerDN
        GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, issuerDN));
        AuthorityKeyIdentifier akis = new AuthorityKeyIdentifierStructure(pubkey);
        akis = new AuthorityKeyIdentifier(akis.getKeyIdentifier(), issuerName, serialNumber);
        generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, akis);
    }
}

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

License:Open Source License

/**
 * @param gen//from  w  ww.java2 s .c  o m
 * @param pubKey
 *
 * @throws IOException
 */
private static void addAuthorityKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey)
        throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            gen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        } 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);//  w  w w.  j  ava2  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.Generator.java

License:Open Source License

public static void main(String[] args) {
    File newCertsDir = new File(NEW_CERTS_DIR_NAME);
    newCertsDir.mkdirs();// w w  w  .  j  a v a 2s .  c o  m

    // Create a new, blank KeyStore Manager
    KeyStoreManager mgr = new KeyStoreManager(newCertsDir, "blank_crl.pem");

    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();
    X509Certificate caCrlCert = null;
    try {
        caCrlCert = mgr.getSigningCert();
        PrivateKey caCrlPrivateKey = mgr.getSigningPrivateKey();

        crlGen.setIssuerDN(mgr.getSigningCert().getSubjectX500Principal());
        crlGen.setThisUpdate(now);
        crlGen.setNextUpdate(mgr.getSigningCert().getNotAfter());
        crlGen.setSignatureAlgorithm(mgr.getSigningCert().getSigAlgName());

        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCrlCert));
        crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.ONE));

        X509CRL crl = crlGen.generate(caCrlPrivateKey);

        // You have to manually convert this file to it's PEM equivalent using OpenSSL:
        // > openssl crl -inform der -in blank_crl.dec -out blank_crl.pem

        // Save the Certificate in Binary (DEC) format
        File certRevoc = new File(newCertsDir, "blank_crl.dec");
        FileOutputStream cerOut = new FileOutputStream(certRevoc);
        byte[] buf = crl.getEncoded();
        cerOut.write(buf);
        cerOut.flush();
        cerOut.close();

        // Convert the generated DEC to PEM using OpenSSL
        Process p = Runtime.getRuntime().exec(OPENSSL_CMD_DEC_TO_PEM);
        p.waitFor();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (CRLException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkSignatures() {
    // 1.6.1 - Inputs

    // d)/*from   w ww.  j a v  a  2 s . c  o  m*/

    TrustAnchor trust = null;
    X500Principal trustPrincipal = null;

    // validation date
    {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certPathValidDate",
                new Object[] { new TrustedInput(validDate), new TrustedInput(new Date()) });
        addNotification(msg);
    }

    // find trust anchors
    try {
        X509Certificate cert = (X509Certificate) certs.get(certs.size() - 1);
        Collection trustColl = getTrustAnchors(cert, pkixParams.getTrustAnchors());
        if (trustColl.size() > 1) {
            // conflicting trust anchors                
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.conflictingTrustAnchors",
                    new Object[] { new Integer(trustColl.size()),
                            new UntrustedInput(cert.getIssuerX500Principal()) });
            addError(msg);
        } else if (trustColl.isEmpty()) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noTrustAnchorFound",
                    new Object[] { new UntrustedInput(cert.getIssuerX500Principal()),
                            new Integer(pkixParams.getTrustAnchors().size()) });
            addError(msg);
        } else {
            PublicKey trustPublicKey;
            trust = (TrustAnchor) trustColl.iterator().next();
            if (trust.getTrustedCert() != null) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trustPublicKey = trust.getCAPublicKey();
            }
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, trustPublicKey,
                        pkixParams.getSigProvider());
            } catch (SignatureException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustButInvalidCert");
                addError(msg);
            } catch (Exception e) {
                // do nothing, error occurs again later
            }
        }
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage());
    } catch (Throwable t) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.unknown",
                new Object[] { new UntrustedInput(t.getMessage()), new UntrustedInput(t) });
        addError(msg);
    }

    if (trust != null) {
        // get the name of the trustAnchor
        X509Certificate sign = trust.getTrustedCert();
        try {
            if (sign != null) {
                trustPrincipal = getSubjectPrincipal(sign);
            } else {
                trustPrincipal = new X500Principal(trust.getCAName());
            }
        } catch (IllegalArgumentException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustDNInvalid",
                    new Object[] { new UntrustedInput(trust.getCAName()) });
            addError(msg);
        }

        // test key usages of the trust anchor
        if (sign != null) {
            boolean[] ku = sign.getKeyUsage();
            if (ku != null && !ku[5]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustKeyUsage");
                addNotification(msg);
            }
        }
    }

    // 1.6.2 - Initialization

    PublicKey workingPublicKey = null;
    X500Principal workingIssuerName = trustPrincipal;

    X509Certificate sign = null;

    if (trust != null) {
        sign = trust.getTrustedCert();

        if (sign != null) {
            workingPublicKey = sign.getPublicKey();
        } else {
            workingPublicKey = trust.getCAPublicKey();
        }

        try {
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustPubKeyError");
            addError(msg);
        }

    }

    // Basic cert checks

    X509Certificate cert = null;
    int i;

    for (int index = certs.size() - 1; index >= 0; index--) {
        //
        // i as defined in the algorithm description
        //
        i = n - index;

        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialied the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);

        // verify signature
        if (workingPublicKey != null) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey,
                        pkixParams.getSigProvider());
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else if (isSelfIssued(cert)) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, cert.getPublicKey(),
                        pkixParams.getSigProvider());
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                        "CertPathReviewer.rootKeyIsValidButNotATrustAnchor");
                addError(msg, index);
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.NoIssuerPublicKey");
            // if there is an authority key extension add the serial and issuer of the missing certificate
            byte[] akiBytes = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (akiBytes != null) {
                try {
                    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier
                            .getInstance(X509ExtensionUtil.fromExtensionValue(akiBytes));
                    GeneralNames issuerNames = aki.getAuthorityCertIssuer();
                    if (issuerNames != null) {
                        GeneralName name = issuerNames.getNames()[0];
                        BigInteger serial = aki.getAuthorityCertSerialNumber();
                        if (serial != null) {
                            Object[] extraArgs = { new LocaleString(RESOURCE_NAME, "missingIssuer"), " \"",
                                    name, "\" ", new LocaleString(RESOURCE_NAME, "missingSerial"), " ",
                                    serial };
                            msg.setExtraArguments(extraArgs);
                        }
                    }
                } catch (IOException e) {
                    // ignore
                }
            }
            addError(msg, index);
        }

        // certificate valid?
        try {
            cert.checkValidity(validDate);
        } catch (CertificateNotYetValidException cnve) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateNotYetValid",
                    new Object[] { new TrustedInput(cert.getNotBefore()) });
            addError(msg, index);
        } catch (CertificateExpiredException cee) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateExpired",
                    new Object[] { new TrustedInput(cert.getNotAfter()) });
            addError(msg, index);
        }

        // certificate revoked?
        if (pkixParams.isRevocationEnabled()) {
            try {
                checkRevocation(pkixParams, cert, validDate, sign, workingPublicKey);
            } catch (SimpleValidationErrorException e) {
                addError(e, index);
            }
        }

        // certificate issuer correct
        if (workingIssuerName != null && !cert.getIssuerX500Principal().equals(workingIssuerName)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certWrongIssuer",
                    new Object[] { workingIssuerName.getName(), cert.getIssuerX500Principal().getName() });
            addError(msg, index);
        }

        //
        // prepare for next certificate
        //
        if (i != n) {

            if (cert != null && cert.getVersion() == 1) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                addError(msg, index);
            }

            // k)

            BasicConstraints bc;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
                if (bc != null) {
                    if (!bc.isCA()) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                        addError(msg, index);
                    }
                } else {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBasicConstraints");
                    addError(msg, index);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.errorProcesingBC");
                addError(msg, index);
            }

            // n)

            boolean[] _usage = cert.getKeyUsage();

            if ((_usage != null) && !_usage[KEY_CERT_SIGN]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCertSign");
                addError(msg, index);
            }

        } // if

        // set signing certificate for next round
        sign = cert;

        // c)

        workingIssuerName = cert.getSubjectX500Principal();

        // d) e) f)

        try {
            workingPublicKey = getNextWorkingKey(certs, index);
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pubKeyError");
            addError(msg, index);
        }

    } // for

    trustAnchor = trust;
    subjectPublicKey = workingPublicKey;
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

License:Open Source License

private X509V3CertificateGenerator buildX509V3CertificateGenerator(PublicKey publicKey, X509Certificate caCert,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays)
        throws CertificateEncodingException, CertificateParsingException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // Calculate Expiration Date
    Calendar notBeforeCal = Calendar.getInstance();
    Date notBeforeDate = notBeforeCal.getTime();
    Calendar notAfterCal = Calendar.getInstance();
    notAfterCal.add(Calendar.DAY_OF_YEAR, validDays);
    Date notAfterDate = notAfterCal.getTime();

    ///*from  www .j  av a  2  s  .  c om*/
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(BigInteger.valueOf(serialNumber));
    v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    v3CertGen.setNotBefore(notBeforeDate);
    v3CertGen.setNotAfter(notAfterDate);
    v3CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName)));
    v3CertGen.setPublicKey(publicKey);
    v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //
    // extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(publicKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));

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

    return v3CertGen;
}

From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java

License:Apache License

public static X509Certificate[] buildChain() throws Exception {
    // create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);/*w  w w.j  a  v  a  2  s.  c  om*/
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    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));

    // extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}