Search in sources :

Example 56 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project indy by Commonjava.

the class CertUtils method generateX509Certificate.

/**
 * Create a self-signed X.509 cert
 *
 * @param pair      KeyPair generated for this request
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param days      how many days from now the cert is valid for
 * @param algorithm the signing algorithm, eg "SHA256withRSA"
 * @return X509Certificate newly generated certificate
 */
public static X509Certificate generateX509Certificate(KeyPair pair, String dn, int days, String algorithm) throws GeneralSecurityException, OperatorCreationException, IOException {
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    PrivateKey subPrivKey = pair.getPrivate();
    PublicKey subPubKey = pair.getPublic();
    ContentSigner contentSignerBuilder = new JcaContentSignerBuilder(algorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(subPrivKey);
    X500Name name = new X500Name(dn);
    Date expires = new Date(System.currentTimeMillis() + (MILLIS_IN_DAY * days));
    X509CertificateHolder holder = new X509v3CertificateBuilder(name, allocateSerialNumber(), new Date(), expires, name, SubjectPublicKeyInfo.getInstance(subPubKey.getEncoded())).build(contentSignerBuilder);
    X509Certificate cert = converter.getCertificate(holder);
    logger.debug("Created cert using CA private key:\n" + cert.toString());
    return cert;
}
Also used : PrivateKey(java.security.PrivateKey) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 57 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project indy by Commonjava.

the class CertUtils method createSignedCertificate.

/**
 * Generate X509Certificate using objects from existing issuer and subject certificates.
 * The generated certificate is signed by issuer PrivateKey.
 * @param certificate
 * @param issuerCertificate
 * @param issuerPrivateKey
 * @param isIntermediate
 * @return
 * @throws Exception
 */
public static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean isIntermediate) throws Exception {
    String issuerSigAlg = issuerCertificate.getSigAlgName();
    X500Principal principal = issuerCertificate.getIssuerX500Principal();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(issuerSigAlg).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaX509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(principal, certificate.getSerialNumber(), certificate.getNotBefore(), certificate.getNotAfter(), certificate.getSubjectX500Principal(), certificate.getPublicKey());
    if (isIntermediate) {
        v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(-1));
    }
    return converter.getCertificate(v3CertGen.build(contentSignerBuilder.build(issuerPrivateKey)));
}
Also used : JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X500Principal(javax.security.auth.x500.X500Principal) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 58 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project tomee by apache.

the class SslTomEETest method test.

@Test
public void test() throws Exception {
    final File keystore = new File("target/keystore");
    {
        // generate keystore/trustore
        if (keystore.exists()) {
            Files.delete(keystore);
        }
        keystore.getParentFile().mkdirs();
        try (final FileOutputStream fos = new FileOutputStream(keystore)) {
            final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
            keyGenerator.initialize(1024);
            final KeyPair pair = keyGenerator.generateKeyPair();
            final boolean addBc = Security.getProvider("BC") == null;
            if (addBc) {
                Security.addProvider(new BouncyCastleProvider());
            }
            try {
                final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(new X500Name("cn=serveralias"), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)), new X500Name("cn=serveralias"), pair.getPublic());
                final X509CertificateHolder certHldr = x509v1CertificateBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(pair.getPrivate()));
                final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);
                final KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(null, "changeit".toCharArray());
                ks.setKeyEntry("serveralias", pair.getPrivate(), "changeit".toCharArray(), new Certificate[] { cert });
                ks.store(fos, "changeit".toCharArray());
            } finally {
                if (addBc) {
                    Security.removeProvider("BC");
                }
            }
        } catch (final Exception e) {
            Assert.fail(e.getMessage());
        }
    }
    final Configuration configuration = new Configuration();
    configuration.setSsl(true);
    configuration.setKeystoreFile(keystore.getAbsolutePath());
    configuration.setKeystorePass("changeit");
    configuration.setKeyAlias("serveralias");
    final Container container = new Container();
    container.setup(configuration);
    container.start();
    Connector[] connectors = container.getTomcat().getService().findConnectors();
    for (Connector conn : connectors) {
        if (conn.getPort() == 8443) {
            Object propertyObject = conn.getProperty("keystoreFile");
            assertNotNull(propertyObject);
            assertEquals(keystore.getAbsolutePath(), propertyObject.toString());
        }
    }
    try {
        assertEquals(8443, ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("Tomcat:type=ProtocolHandler,port=8443"), "port"));
    } finally {
        container.stop();
    }
    // ensure it is not always started
    configuration.setSsl(false);
    container.setup(configuration);
    container.start();
    try {
        assertFalse(ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName("Tomcat:type=ProtocolHandler,port=8443")));
    } finally {
        container.close();
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ObjectName(javax.management.ObjectName) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) File(java.io.File) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 59 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project zookeeper by apache.

the class QuorumSSLTest method buildEndEntityCert.

public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
    X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
    List<GeneralName> generalNames = new ArrayList<>();
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }
    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }
    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
    X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
    JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic());
    X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)).addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)).addExtension(Extension.basicConstraints, true, new BasicConstraints(false)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }
    if (crlPath != null) {
        DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));
        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
    }
    if (ocspPort != null) {
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
    }
    return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Random(java.util.Random) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BcX509ExtensionUtils(org.bouncycastle.cert.bc.BcX509ExtensionUtils) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BcX509ExtensionUtils(org.bouncycastle.cert.bc.BcX509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 60 with JcaContentSignerBuilder

use of org.bouncycastle.operator.jcajce.JcaContentSignerBuilder in project zookeeper by apache.

the class QuorumSSLTest method setup.

@BeforeEach
public void setup() throws Exception {
    quorumX509Util = new QuorumX509Util();
    ClientBase.setupTestEnv();
    tmpDir = createTmpDir().getAbsolutePath();
    clientPortQp1 = PortAssignment.unique();
    clientPortQp2 = PortAssignment.unique();
    clientPortQp3 = PortAssignment.unique();
    validKeystorePath = tmpDir + "/valid.jks";
    truststorePath = tmpDir + "/truststore.jks";
    quorumConfiguration = generateQuorumConfiguration();
    Security.addProvider(new BouncyCastleProvider());
    certStartTime = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(certStartTime);
    cal.add(Calendar.YEAR, 1);
    certEndTime = cal.getTime();
    rootKeyPair = createKeyPair();
    contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(rootKeyPair.getPrivate());
    rootCertificate = createSelfSignedCertifcate(rootKeyPair);
    // Write the truststore
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, PASSWORD);
    trustStore.setCertificateEntry(rootCertificate.getSubjectDN().toString(), rootCertificate);
    FileOutputStream outputStream = new FileOutputStream(truststorePath);
    trustStore.store(outputStream, PASSWORD);
    outputStream.flush();
    outputStream.close();
    defaultKeyPair = createKeyPair();
    X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(), HOSTNAME, "127.0.0.1", null, null);
    writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
    setSSLSystemProperties();
}
Also used : QuorumX509Util(org.apache.zookeeper.common.QuorumX509Util) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) FileOutputStream(java.io.FileOutputStream) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)133 ContentSigner (org.bouncycastle.operator.ContentSigner)100 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)66 Date (java.util.Date)64 X500Name (org.bouncycastle.asn1.x500.X500Name)63 X509Certificate (java.security.cert.X509Certificate)58 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)56 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)43 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)43 BigInteger (java.math.BigInteger)40 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)39 KeyPair (java.security.KeyPair)33 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)29 KeyPairGenerator (java.security.KeyPairGenerator)25 SecureRandom (java.security.SecureRandom)25 IOException (java.io.IOException)24 KeyStore (java.security.KeyStore)22 CertificateException (java.security.cert.CertificateException)19 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)19 ArrayList (java.util.ArrayList)18