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:org.krakenapps.ca.util.CertificateBuilder.java

License:Apache License

public static X509Certificate createCertificate(CertificateRequest req) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    X509Principal subject = parseDn(req.getSubjectDn());
    X509Principal issuer = parseDn(req.getIssuerDn());

    certGen.setSerialNumber(req.getSerial());
    certGen.setIssuerDN(issuer);/*from w w  w  .j a v a  2  s  . c  o  m*/
    certGen.setSubjectDN(subject);
    certGen.setNotBefore(req.getNotBefore());
    certGen.setNotAfter(req.getNotAfter());
    certGen.setPublicKey(req.getKeyPair().getPublic());
    certGen.setSignatureAlgorithm(req.getSignatureAlgorithm());

    if (req.getCrlUrl() != null) {
        GeneralName gn = new GeneralName(6, new DERIA5String(req.getCrlUrl().toString()));

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);

        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);

        List<DistributionPoint> l = new ArrayList<DistributionPoint>();
        l.add(new DistributionPoint(dpn, null, null));

        CRLDistPoint crlDp = new CRLDistPoint(l.toArray(new DistributionPoint[0]));

        certGen.addExtension(new DERObjectIdentifier("2.5.29.31"), false, crlDp);
    }

    return certGen.generate(req.getIssuerKey(), "BC");
}

From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

License:Educational Community License

protected Certificate generateCertificate(KeyPair keyPair, String alias) throws GeneralSecurityException {

    //test that Bouncy Castle provider is present and add it if it's not
    if (Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }//from  w  w  w . ja v  a  2 s .  co  m
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    //      X509Name nameInfo = new X509Name(false,"CN=" + alias);
    certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
    certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
    X509Principal nameInfo = new X509Principal("CN=" + alias);
    certificateGenerator.setIssuerDN(nameInfo);
    certificateGenerator.setSubjectDN(nameInfo); // note: same as issuer for self signed
    certificateGenerator.setNotBefore(new Date());
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
    certificateGenerator.setNotAfter(c.getTime());
    certificateGenerator.setPublicKey(keyPair.getPublic());
    return certificateGenerator.generate(keyPair.getPrivate(),
            org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

public static void setSerialNumberAndValidityPeriod(X509V3CertificateGenerator certGen, boolean isRootCA,
        long validityPeriod) {
    if (isRootCA)
        certGen.setSerialNumber(BigInteger.ONE);
    else//from   w w w . j  ava  2  s. c  om
        certGen.setSerialNumber(BigInteger.valueOf(++serial));

    long time = System.currentTimeMillis();
    time -= time % 86400000L;
    certGen.setNotBefore(new Date(time));
    certGen.setNotAfter(new Date(time + validityPeriod));
}

From source file:org.mitre.jwt.JwtTest.java

License:Apache License

/**
 * Creates a certificate.//  w w w .ja  va2  s .  c o  m
 * 
 * @param commonName
 * @param daysNotValidBefore
 * @param daysNotValidAfter
 * @return
 */
public static X509V3CertificateGenerator createCertificate(String commonName, int daysNotValidBefore,
        int daysNotValidAfter) {
    // BC sez X509V3CertificateGenerator is deprecated and the docs say to
    // use another, but it seemingly isn't included jar...
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    v3CertGen.setIssuerDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None"));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * daysNotValidBefore)));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * daysNotValidAfter)));
    v3CertGen.setSubjectDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None"));
    return v3CertGen;
}

From source file:org.neo4j.server.security.ssl.SslCertificateFactory.java

License:Open Source License

public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) {
    FileOutputStream fos = null;/*from w  w  w.  ja  va  2  s  . c om*/
    try {

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ENCRYPTION);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator certGenertor = new X509V3CertificateGenerator();

        certGenertor.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        certGenertor.setIssuerDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None"));
        certGenertor.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        certGenertor.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        certGenertor.setSubjectDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None"));

        certGenertor.setPublicKey(keyPair.getPublic());
        certGenertor.setSignatureAlgorithm("MD5WithRSAEncryption");

        Certificate certificate = certGenertor.generate(keyPair.getPrivate(), "BC");

        ensureFolderExists(certificatePath.getParentFile());
        ensureFolderExists(privateKeyPath.getParentFile());

        fos = new FileOutputStream(certificatePath);
        fos.write(certificate.getEncoded());
        fos.close();

        fos = new FileOutputStream(privateKeyPath);
        fos.write(keyPair.getPrivate().getEncoded());
        fos.close();

    } catch (Exception e) {
        throw new RuntimeException("Unable to create self signed SSL certificate, please see nested exception.",
                e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java

License:Apache License

public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey,
        X509Certificate caCert) throws Exception {

    installBouncyCastleProviderIfNecessary();

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    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);//from w w  w.jav a2  s.c  o m
    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.generate(caKey, BC_PROVIDER);
}

From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java

License:Apache License

public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey,
        X509Certificate caCert) throws Exception {

    installBouncyCastleProviderIfNecessary();

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    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);/*w  w  w  . j a v  a  2  s  .  c o m*/
    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.generate(caKey, BC_PROVIDER);
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

License:Open Source License

protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException {
    X509Certificate cert;//from  w ww  .java  2 s. c o m
    try {
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal());
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setNotBefore(getCertStartDate());
        certGen.setNotAfter(getCertEndDate());
        certGen.setPublicKey(csr.getPublicKey("BC"));
        certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM);
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(getRootCertificate()));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

        ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
        for (int i = 0; i != attributes.size(); i++) {
            Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
            if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                @SuppressWarnings("rawtypes")
                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());
                }
            }
        }

        KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(),
                rootService.getRootCertificateAlias(), rootService.getRootKeyPassword());
        cert = certGen.generate(rootKeyPair.getPrivate(), "BC");
    } catch (CertificateParsingException e) {
        throw new CertException(e);
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    }
    LOG.debug("Certificate generated for subject: " + cert.getSubjectDN());
    return cert;
}

From source file:org.obiba.opal.core.unit.UnitKeyStore.java

License:Open Source License

public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey, PublicKey subjectPublicKey,
        String certificateInfo, String signatureAlgorithm)
        throws SignatureException, InvalidKeyException, CertificateEncodingException, NoSuchAlgorithmException {
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    X509Name issuerDN = new X509Name(certificateInfo);
    X509Name subjectDN = new X509Name(certificateInfo);
    int daysTillExpiry = 30 * 365;

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, daysTillExpiry);

    certificateGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(subjectDN);
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setNotBefore(new Date());
    certificateGenerator.setNotAfter(expiry.getTime());
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);

    return certificateGenerator.generate(issuerPrivateKey);
}

From source file:org.obiba.security.KeyStoreManager.java

License:Open Source License

public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey, PublicKey subjectPublicKey,
        String certificateInfo, String signatureAlgorithm)
        throws SignatureException, InvalidKeyException, CertificateEncodingException, NoSuchAlgorithmException {
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    X509Name issuerDN = new X509Name(certificateInfo);
    X509Name subjectDN = new X509Name(certificateInfo);
    int daysTillExpiry = 30 * 365;

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, daysTillExpiry);

    certificateGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(subjectDN);
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setNotBefore(new Date());
    certificateGenerator.setNotAfter(expiry.getTime());
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    return certificateGenerator.generate(issuerPrivateKey);
}