Search in sources :

Example 41 with JcaX509v3CertificateBuilder

use of org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder in project credhub by cloudfoundry-incubator.

the class SignedCertificateGeneratorTest method beforeEach.

@Before
public void beforeEach() throws Exception {
    timeProvider = mock(DateTimeProvider.class);
    now = Calendar.getInstance();
    now.setTimeInMillis(1493066824);
    later = (Calendar) now.clone();
    later.add(Calendar.DAY_OF_YEAR, expectedDurationInDays);
    when(timeProvider.getNow()).thenReturn(now);
    serialNumberGenerator = mock(RandomSerialNumberGenerator.class);
    when(serialNumberGenerator.generate()).thenReturn(BigInteger.valueOf(1337));
    jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    generator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    // doesn't matter for testing
    generator.initialize(1024);
    issuerKey = generator.generateKeyPair();
    issuerDn = new X500Principal(caName);
    generatedCertificateKeyPair = generator.generateKeyPair();
    certificateGenerationParameters = defaultCertificateParameters();
    subject = new SignedCertificateGenerator(timeProvider, serialNumberGenerator, jcaContentSignerBuilder, jcaX509CertificateConverter, getBouncyCastleProvider());
    caSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(issuerKey.getPublic());
    caSerialNumber = BigInteger.valueOf(42l);
    JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(issuerDn, caSerialNumber, Date.from(now.toInstant()), Date.from(later.toInstant()), issuerDn, issuerKey.getPublic());
    certificateAuthority = createCertificateAuthority(x509v3CertificateBuilder);
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, caSubjectKeyIdentifier);
    certificateAuthorityWithSubjectKeyId = createCertificateAuthority(x509v3CertificateBuilder);
    expectedSubjectKeyIdentifier = certificateAuthorityWithSubjectKeyId.getExtensionValue(Extension.subjectKeyIdentifier.getId());
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) DateTimeProvider(org.springframework.data.auditing.DateTimeProvider) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X500Principal(javax.security.auth.x500.X500Principal) Before(org.junit.Before)

Example 42 with JcaX509v3CertificateBuilder

use of org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder in project cloudstack by apache.

the class CertUtils method generateV3Certificate.

public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair, final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm, final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException {
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final BigInteger serial = generateRandomBigInt();
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    final X509v3CertificateBuilder certBuilder;
    if (caCert == null) {
        // Generate CA certificate
        certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject), clientPublicKey);
        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
    } else {
        // Generate client certificate
        certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey);
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert));
    }
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(clientPublicKey));
    final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    if (publicIPAddresses != null) {
        for (final String publicIPAddress : new HashSet<>(publicIPAddresses)) {
            if (StringUtils.isEmpty(publicIPAddress)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress));
        }
    }
    if (dnsNames != null) {
        for (final String dnsName : new HashSet<>(dnsNames)) {
            if (StringUtils.isEmpty(dnsName)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName));
        }
    }
    if (subjectAlternativeNames.size() > 0) {
        final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {})));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }
    final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(caKeyPair.getPrivate());
    final X509CertificateHolder certHolder = certBuilder.build(signer);
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
    if (caCert != null) {
        cert.verify(caCert.getPublicKey());
    } else {
        cert.verify(caKeyPair.getPublic());
    }
    return cert;
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) DateTime(org.joda.time.DateTime) X509Certificate(java.security.cert.X509Certificate) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) HashSet(java.util.HashSet)

Example 43 with JcaX509v3CertificateBuilder

use of org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder in project Openfire by igniterealtime.

the class KeystoreTestUtils method generateTestCertificate.

private static X509Certificate generateTestCertificate(final boolean isValid, final KeyPair issuerKeyPair, final KeyPair subjectKeyPair, int indexAwayFromEndEntity) throws Exception {
    // Issuer and Subject.
    final X500Name subject = new X500Name("CN=" + Base64.encodeBytes(subjectKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
    final X500Name issuer = new X500Name("CN=" + Base64.encodeBytes(issuerKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
    // Validity
    final Date notBefore;
    final Date notAfter;
    if (isValid) {
        // 30 days ago
        notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
        // 99 days from now.
        notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
    } else {
        // Generate a certificate for which the validate period has expired.
        // 40 days ago
        notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 40));
        // 10 days ago
        notAfter = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 10));
    }
    // The new certificate should get a unique serial number.
    final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectKeyPair.getPublic());
    // When this certificate is used to sign another certificate, basic constraints need to be set.
    if (indexAwayFromEndEntity > 0) {
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(indexAwayFromEndEntity - 1));
    }
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(issuerKeyPair.getPrivate());
    final X509CertificateHolder certificateHolder = builder.build(contentSigner);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
}
Also used : JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date)

Example 44 with JcaX509v3CertificateBuilder

use of org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder in project Openfire by igniterealtime.

the class CertificateManagerTest method testServerIdentitiesDnsSrv.

/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'DNS SRV' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-dnsSRV"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesDnsSrv() throws Exception {
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr";
    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
    new X500Name("CN=MyIssuer"), // Random serial number
    BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
    new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
    new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
    final DERSequence otherName = new DERSequence(new ASN1Encodable[] { DNS_SRV_OID, new DERUTF8String("_xmpp-server." + subjectAltNameDnsSrv) });
    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, otherName));
    builder.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
    final X509CertificateHolder certificateHolder = builder.build(contentSigner);
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
    // Verify result
    assertEquals(1, serverIdentities.size());
    assertTrue(serverIdentities.contains(subjectAltNameDnsSrv));
    assertFalse(serverIdentities.contains(subjectCommonName));
}
Also used : SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Test(org.junit.Test)

Example 45 with JcaX509v3CertificateBuilder

use of org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder in project Openfire by igniterealtime.

the class CertificateManagerTest method testServerIdentitiesXmppAddrAndDNS.

/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddrAndDNS() throws Exception {
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";
    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
    new X500Name("CN=MyIssuer"), // Random serial number
    BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
    new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
    new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
    final DERSequence otherName = new DERSequence(new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String(subjectAltNameXmppAddr) });
    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.otherName, otherName), new GeneralName(GeneralName.dNSName, subjectAltNameDNS) });
    builder.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
    final X509CertificateHolder certificateHolder = builder.build(contentSigner);
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
    // Verify result
    assertEquals(2, serverIdentities.size());
    assertTrue(serverIdentities.contains(subjectAltNameXmppAddr));
    assertFalse(serverIdentities.contains(subjectCommonName));
}
Also used : SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Test(org.junit.Test)

Aggregations

JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)54 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)48 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)41 X509Certificate (java.security.cert.X509Certificate)38 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)36 ContentSigner (org.bouncycastle.operator.ContentSigner)34 X500Name (org.bouncycastle.asn1.x500.X500Name)32 Date (java.util.Date)28 BigInteger (java.math.BigInteger)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)26 KeyPair (java.security.KeyPair)22 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)21 SecureRandom (java.security.SecureRandom)18 GeneralName (org.bouncycastle.asn1.x509.GeneralName)17 X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)16 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)16 KeyStore (java.security.KeyStore)14 KeyPairGenerator (java.security.KeyPairGenerator)12 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)11 PrivateKey (java.security.PrivateKey)10