Example usage for org.bouncycastle.x509 X509V3CertificateGenerator setNotAfter

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

Introduction

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

Prototype

public void setNotAfter(Date date) 

Source Link

Usage

From source file:at.ac.tuwien.ifs.tita.business.security.TiTASecurity.java

License:Apache License

/**
 * Generates a fresh Certificate for a Users KeyPair.
 * //from   w ww .ja v  a  2 s. c om
 * @param pair the KeyPair to create a Certificate for.
 * @param userName the Issuer of the Certificate
 * @return a 10 Year valid Certificate for the User.
 * @throws TiTASecurityException If an error occurs during the generation Process.
 */
private static X509Certificate generateV3Certificate(KeyPair pair, String userName)
        throws TiTASecurityException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE));
    certGen.setSubjectDN(new X500Principal("CN=" + userName + " 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));

    X509Certificate targetCertificate = null;
    try {
        targetCertificate = certGen.generate(pair.getPrivate(), "BC");
    } catch (NoSuchProviderException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Specified provider was not found.\n" + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Specified algorithm was not found.\n" + e.getMessage());
    } catch (SignatureException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Signature is not valid.\n" + e.getMessage());
    } catch (CertificateEncodingException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Wrong encoding for Signature.\n" + e.getMessage());
    } catch (InvalidKeyException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". The Key is not valid.\n" + e.getMessage());
    }

    return targetCertificate;
}

From source file:at.tugraz.ist.akm.keystore.ApplicationKeyStore.java

License:Apache License

private void createNewCertificate() throws InvalidKeyException, SecurityException, SignatureException,
        NoSuchAlgorithmException, CertificateEncodingException, IllegalStateException, NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());
    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.setSerialNumber(BigInteger.valueOf(Math.abs(mRandom.nextInt() + 1)));
    certGenerator.setIssuerDN(new X500Principal(CertificateDefaultAttributes.ISSUER));
    certGenerator.setSubjectDN(new X500Principal(CertificateDefaultAttributes.SUBJECT));
    certGenerator.setNotBefore(new Date(
            System.currentTimeMillis() - CertificateDefaultAttributes.VALID_DURATION_BEFORE_NOW_MILLISECONDS));
    certGenerator.setNotAfter(new Date(
            System.currentTimeMillis() + CertificateDefaultAttributes.VALID_DURATION_FROM_NOW_MILLISECONDS));

    KeyPairGenerator keyGenerator = KeyPairGenerator
            .getInstance(CertificateDefaultAttributes.KEYPAIR_GENERATOR);
    keyGenerator.initialize(CertificateDefaultAttributes.KEYPAIR_LENGTH_BITS);
    KeyPair newKeyPair = keyGenerator.generateKeyPair();

    certGenerator.setPublicKey(newKeyPair.getPublic());
    certGenerator.setSignatureAlgorithm(CertificateDefaultAttributes.ENCRYPTION_ALGORITHM);
    X509Certificate newCertificate = certGenerator.generate(newKeyPair.getPrivate());

    mCertificate = newCertificate;/*w w  w . ja v  a 2  s . c  o m*/
    mKeyPair = newKeyPair;
}

From source file:brooklyn.util.crypto.FluentKeySigner.java

License:Apache License

public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) {
    try {//w w w .  jav a  2  s .c  om
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(serialNumber != null ? serialNumber :
        // must be positive
                BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE));
        v3CertGen.setIssuerDN(issuerPrincipal);
        v3CertGen.setNotBefore(validityStartDate);
        v3CertGen.setNotAfter(validityEndDate);
        v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

        v3CertGen.setSubjectDN(subject);
        v3CertGen.setPublicKey(keyToCertify);

        v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keyToCertify));

        if (authorityKeyIdentifier != null)
            v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

        X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC");
        return pkCertificate;

    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

From source file:ca.nrc.cadc.cred.CertUtil.java

License:Open Source License

/**
 * Method that generates an X509 proxy certificate
 * //ww  w.  j av  a2 s  .co  m
 * @param csr CSR for the certificate
 * @param lifetime lifetime of the certificate in SECONDS
 * @param chain certificate used to sign the proxy certificate
 * @return generated proxy certificate
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CertificateParsingException
 * @throws CertificateEncodingException
 * @throws SignatureException
 * @throws CertificateNotYetValidException
 * @throws CertificateExpiredException
 */
public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime,
        X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException,
        CertificateExpiredException, CertificateNotYetValidException {
    X509Certificate issuerCert = chain.getChain()[0];
    PrivateKey issuerKey = chain.getPrivateKey();

    Security.addProvider(new BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(issuerCert.getSubjectX500Principal());

    // generate the proxy DN as the issuerDN + CN=random number
    Random rand = new Random();
    String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    String delegDN = String.valueOf(Math.abs(rand.nextInt()));
    String proxyDn = "CN=" + delegDN + "," + issuerDN;
    certGen.setSubjectDN(new X500Principal(proxyDn));

    // set validity
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // Start date. Allow for a sixty five minute clock skew here.
    date.add(Calendar.MINUTE, -65);
    Date beforeDate = date.getTime();
    for (X509Certificate currentCert : chain.getChain()) {
        if (beforeDate.before(currentCert.getNotBefore())) {
            beforeDate = currentCert.getNotBefore();
        }
    }
    certGen.setNotBefore(beforeDate);

    // End date.
    // If hours = 0, then cert lifetime is set to that of user cert
    if (lifetime <= 0) {
        // set the validity of certificates as the minimum
        // of the certificates in the chain
        Date afterDate = issuerCert.getNotAfter();
        for (X509Certificate currentCert : chain.getChain()) {
            if (afterDate.after(currentCert.getNotAfter())) {
                afterDate = currentCert.getNotAfter();
            }
        }
        certGen.setNotAfter(afterDate);
    } else {
        // check the validity of the signing certificate
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        for (X509Certificate currentCert : chain.getChain()) {
            currentCert.checkValidity(date.getTime());
        }

        certGen.setNotAfter(date.getTime());
    }

    certGen.setPublicKey(csr.getPublicKey());
    // TODO: should be able to get signature algorithm from the csr, but... obtuse
    certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM);

    // extensions
    // add ProxyCertInfo extension to the new cert

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

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

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

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

    // add the Proxy Certificate Information
    // I expect this code to be removed once support to proxy
    // certificates is provided in Bouncy Castle.

    // create a proxy policy
    // types of proxy certificate policies - see RFC3820
    // impersonates the user
    final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1");
    // independent
    // final DERObjectIdentifier INDEPENDENT = new
    // DERObjectIdentifier(
    // "1.3.6.1.5.5.7.21.2");
    // defined by a policy language
    // final DERObjectIdentifier LIMITED = new DERObjectIdentifier(
    // "1.3.6.1.4.1.3536.1.1.1.9");

    ASN1EncodableVector policy = new ASN1EncodableVector();
    policy.add(IMPERSONATION);

    // pathLengthConstr (RFC3820)
    // The pCPathLenConstraint field, if present, specifies the
    // maximum
    // depth of the path of Proxy Certificates that can be signed by
    // this
    // Proxy Certificate. A pCPathLenConstraint of 0 means that this
    // certificate MUST NOT be used to sign a Proxy Certificate. If
    // the
    // pCPathLenConstraint field is not present then the maximum proxy
    // path
    // length is unlimited. End entity certificates have unlimited
    // maximum
    // proxy path lengths.
    // DERInteger pathLengthConstr = new DERInteger(100);

    // create the proxy certificate information
    ASN1EncodableVector vec = new ASN1EncodableVector();
    // policy.add(pathLengthConstr);
    vec.add(new DERSequence(policy));

    // OID
    final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14");
    certGen.addExtension(OID, true, new DERSequence(vec));

    return certGen.generate(issuerKey, "BC");
}

From source file:chapter6.PKCS10CertCreateExample.java

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") == false) {
        System.out.println("Request failed to verify!!");
        System.exit(1);/* w  ww. j a v  a2s  .  com*/
    }

    // 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(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded()));
    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 };
}

From source file:chapter6.X509V3CreateExample.java

public static X509Certificate generateV3Certificate(KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

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

    // Extension ::= SEQUENCE {
    //  extnID      OBJECT IDENTIFIER,
    //  critical    BOOLEAN DEFAULT FALSE
    //  extnValue   OCTET STRING }
    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(), CryptoDefs.Provider.BC.getName());
}

From source file:chapter7.Utils.java

/**
 * Generate a sample V3 certificate to use as an intermediate CA certificate.
 * @param intKey/* w  ww  .  j  av  a2s  .c o m*/
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509Certificate generateIntermediateCert(final PublicKey intKey, final PrivateKey caKey,
        final X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.ONE);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD));
    certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate"));
    certGen.setPublicKey(intKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    return certGen.generateX509Certificate(caKey, CryptoDefs.Provider.BC.getName());
}

From source file:chapter7.Utils.java

/**
 * Generate a sample V3 certificate to use as an end entity certificate.
 * @param entityKey/* ww w.  j  a v a 2 s.c  o m*/
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509Certificate generateEndEntityCert(final PublicKey entityKey, final PrivateKey caKey,
        final X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.ONE);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD));
    certGen.setSubjectDN(new X500Principal("CN=Test End Certificate"));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    return certGen.generateX509Certificate(caKey, CryptoDefs.Provider.BC.getName());
}

From source file:com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest.java

License:Open Source License

private void addEntry(final String alias) throws GeneralSecurityException {
    final KeyPair pair = KG.generateKeyPair();
    // build a certificate generator
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    final X500Principal dnName = new X500Principal("cn=" + alias);

    certGen.setSerialNumber(new BigInteger(256, RND));
    certGen.setSubjectDN(new X509Name("dc=" + alias));
    certGen.setIssuerDN(dnName); // use the same
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSA");
    final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC");

    ks.setEntry(alias, new KeyStore.PrivateKeyEntry(pair.getPrivate(), new X509Certificate[] { cert }), PP);
}

From source file:com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest.java

License:Open Source License

private void addPublicEntry(final String alias) throws GeneralSecurityException {
    final KeyPair pair = KG.generateKeyPair();
    // build a certificate generator
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    final X500Principal dnName = new X500Principal("cn=" + alias);

    certGen.setSerialNumber(new BigInteger(256, RND));
    certGen.setSubjectDN(new X509Name("dc=" + alias));
    certGen.setIssuerDN(dnName); // use the same
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSA");
    final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC");

    ks.setEntry(alias, new KeyStore.TrustedCertificateEntry(cert), null);
}