Search in sources :

Example 6 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project koronavilkku-backend by THLfi.

the class FederationGatewaySigningDev method generateDevCertificate.

public X509Certificate generateDevCertificate(KeyPair keyPair, KeyPair trustAnchorKeyPair, X509Certificate trustAnchorCert) throws OperatorCreationException, IOException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    X500Name subject = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.C, "FI").addRDN(BCStyle.CN, "koronavilkku-dev").addRDN(BCStyle.O, "koronavilkku dev").build();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
    JcaContentSignerBuilder csrBuilder = new JcaContentSignerBuilder(DIGEST_ALGORITHM + "RSA").setProvider("BC");
    ContentSigner csrContentSigner = csrBuilder.build(trustAnchorKeyPair.getPrivate());
    PKCS10CertificationRequest csr = p10Builder.build(csrContentSigner);
    X509v3CertificateBuilder issuedCertBuilder = new X509v3CertificateBuilder(new X500Name("CN=" + DEV_TRUST_ANCHOR_ISSUER), new BigInteger(Long.toString(new SecureRandom().nextLong())), Date.from(Instant.now()), Date.from(Instant.now().plus(Duration.ofDays(100))), csr.getSubject(), csr.getSubjectPublicKeyInfo());
    JcaX509ExtensionUtils issuedCertExtUtils = new JcaX509ExtensionUtils();
    issuedCertBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
    issuedCertBuilder.addExtension(Extension.authorityKeyIdentifier, false, issuedCertExtUtils.createAuthorityKeyIdentifier(trustAnchorCert));
    issuedCertBuilder.addExtension(Extension.subjectKeyIdentifier, false, issuedCertExtUtils.createSubjectKeyIdentifier(csr.getSubjectPublicKeyInfo()));
    issuedCertBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
    X509CertificateHolder issuedCertHolder = issuedCertBuilder.build(csrContentSigner);
    X509Certificate issuedCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(issuedCertHolder);
    issuedCert.verify(trustAnchorCert.getPublicKey(), "BC");
    return issuedCert;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 7 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project neo4j by neo4j.

the class CertificateChainFactory method generateCertificate.

private static X509Certificate generateCertificate(X509Certificate issuingCert, PrivateKey issuingPrivateKey, KeyPair certKeyPair, String certName, String ocspURL, Path certificatePath, Path keyPath, BouncyCastleProvider bouncyCastleProvider) throws Exception {
    X509v3CertificateBuilder builder;
    if (issuingCert == null) {
        builder = new JcaX509v3CertificateBuilder(// issuer authority
        new X500Name("CN=" + certName), // serial number of certificate
        BigInteger.valueOf(new Random().nextInt()), // start of validity
        NOT_BEFORE, // end of certificate validity
        NOT_AFTER, // subject name of certificate
        new X500Name("CN=" + certName), // public key of certificate
        certKeyPair.getPublic());
    } else {
        builder = new JcaX509v3CertificateBuilder(// issuer authority
        issuingCert, // serial number of certificate
        BigInteger.valueOf(new Random().nextInt()), // start of validity
        NOT_BEFORE, // end of certificate validity
        NOT_AFTER, // subject name of certificate
        new X500Name("CN=" + certName), // public key of certificate
        certKeyPair.getPublic());
    }
    // key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature));
    builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // embed ocsp URI
    builder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(new AccessDescription(AccessDescription.id_ad_ocsp, new GeneralName(GeneralName.uniformResourceIdentifier, ocspURL + "/" + certName))));
    X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(bouncyCastleProvider).build(// self sign if root cert
    issuingPrivateKey == null ? certKeyPair.getPrivate() : issuingPrivateKey)));
    writePem("CERTIFICATE", certificate.getEncoded(), certificatePath);
    writePem("PRIVATE KEY", certKeyPair.getPrivate().getEncoded(), keyPath);
    return certificate;
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) Random(java.util.Random) SecureRandom(java.security.SecureRandom) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 8 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project gitblit by gitblit.

the class X509Utils method newCertificateAuthority.

/**
 * Creates a new certificate authority PKCS#12 store.  This function will
 * destroy any existing CA store.
 *
 * @param metadata
 * @param storeFile
 * @param keystorePassword
 * @param x509log
 * @return
 */
public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
    try {
        KeyPair caPair = newKeyPair();
        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
        // clone metadata
        X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
        X500Name issuerDN = buildDistinguishedName(caMetadata);
        // Generate self-signed certificate
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), caMetadata.notBefore, caMetadata.notAfter, issuerDN, caPair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
        caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
        caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
        caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
        X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
        // confirm the validity of the CA certificate
        cert.checkValidity(new Date());
        cert.verify(cert.getPublicKey());
        // Delete existing keystore
        if (storeFile.exists()) {
            storeFile.delete();
        }
        // Save private key and certificate to new keystore
        KeyStore store = openKeyStore(storeFile, caMetadata.password);
        store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(), new Certificate[] { cert });
        saveKeyStore(storeFile, store, caMetadata.password);
        x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
        // update serial number in metadata object
        caMetadata.serialNumber = cert.getSerialNumber().toString();
        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate Gitblit CA certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 9 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project gitblit by gitblit.

the class X509Utils method newClientCertificate.

/**
 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
 * stores are destroyed.
 *
 * @param clientMetadata a container for dynamic parameters needed for generation
 * @param caKeystoreFile
 * @param caKeystorePassword
 * @param targetFolder
 * @return
 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();
        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());
        // verify user certificate chain
        verifyChain(userCert, caCert);
        targetFolder.mkdirs();
        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }
        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);
        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();
        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);
        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) FileWriter(java.io.FileWriter) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) PEMEncryptor(org.bouncycastle.openssl.PEMEncryptor) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcePEMEncryptorBuilder(org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 10 with KeyUsage

use of com.github.zhenwei.core.asn1.x509.KeyUsage in project acme4j by shred.

the class SMIMECSRBuilder method sign.

/**
 * Signs the completed S/MIME CSR.
 *
 * @param keypair
 *            {@link KeyPair} to sign the CSR with
 */
public void sign(KeyPair keypair) throws IOException {
    requireNonNull(keypair, "keypair");
    if (emaillist.isEmpty()) {
        throw new IllegalStateException("No email address was set");
    }
    try {
        int ix = 0;
        GeneralName[] gns = new GeneralName[emaillist.size()];
        for (InternetAddress email : emaillist) {
            gns[ix++] = new GeneralName(GeneralName.rfc822Name, email.getAddress());
        }
        GeneralNames subjectAltName = new GeneralNames(gns);
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        KeyUsage keyUsage = new KeyUsage(keyUsageType.getKeyUsageBits());
        extensionsGenerator.addExtension(Extension.keyUsage, true, keyUsage);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
        PrivateKey pk = keypair.getPrivate();
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);
        csr = p10Builder.build(signer);
    } catch (OperatorCreationException ex) {
        throw new IOException("Could not generate CSR", ex);
    }
}
Also used : InternetAddress(jakarta.mail.internet.InternetAddress) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ECKey(java.security.interfaces.ECKey) IOException(java.io.IOException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)49 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)40 X500Name (org.bouncycastle.asn1.x500.X500Name)33 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)30 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)30 X509Certificate (java.security.cert.X509Certificate)29 Date (java.util.Date)29 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)29 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)27 ContentSigner (org.bouncycastle.operator.ContentSigner)24 BigInteger (java.math.BigInteger)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)21 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)21 IOException (java.io.IOException)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)19 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)16 HashSet (java.util.HashSet)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)15 KeyPurposeId (org.bouncycastle.asn1.x509.KeyPurposeId)15 Extension (org.bouncycastle.asn1.x509.Extension)14