Search in sources :

Example 31 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project ambry by linkedin.

the class TestSSLUtils method generateCertificate.

/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 32 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project android by nextcloud.

the class CsrHelper method generateCSR.

/**
 * Create the certificate signing request (CSR) from private and public keys
 *
 * @param keyPair the KeyPair with private and public keys
 * @param userId userId of CSR owner
 * @return PKCS10CertificationRequest with the certificate signing request (CSR) data
 * @throws IOException thrown if key cannot be created
 * @throws OperatorCreationException thrown if contentSigner cannot be build
 */
private static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String userId) throws IOException, OperatorCreationException {
    String principal = "CN=" + userId;
    AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WITHRSA");
    AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find("SHA-1");
    ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm).build(privateKey);
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(principal), keyPair.getPublic());
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
    return csrBuilder.build(signer);
}
Also used : BcRSAContentSignerBuilder(org.spongycastle.operator.bc.BcRSAContentSignerBuilder) JcaPKCS10CertificationRequestBuilder(org.spongycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) AsymmetricKeyParameter(org.spongycastle.crypto.params.AsymmetricKeyParameter) ContentSigner(org.spongycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.spongycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.spongycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) X500Name(org.spongycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder) BasicConstraints(org.spongycastle.asn1.x509.BasicConstraints) AlgorithmIdentifier(org.spongycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.spongycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) ExtensionsGenerator(org.spongycastle.asn1.x509.ExtensionsGenerator)

Example 33 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project airlift by airlift.

the class TestCertificationRequest method test.

@Test
public void test() throws Exception {
    // test only with state because BC encodes every other value using UTF8String instead of PrintableString used by the JDK
    String name = "C=country";
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp256r1"));
    KeyPair keyPair = generator.generateKeyPair();
    CertificationRequestInfo certificationRequestInfo = new CertificationRequestInfo(new X500Principal(name), keyPair.getPublic());
    SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = findSignatureAlgorithmIdentifier("SHA256withECDSA");
    byte[] signature = certificationRequestInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate());
    CertificationRequest certificationRequest = new CertificationRequest(certificationRequestInfo, signatureAlgorithmIdentifier, signature);
    assertEquals(certificationRequest.getCertificationRequestInfo(), certificationRequestInfo);
    assertEquals(certificationRequest.getSignatureAlgorithmIdentifier(), signatureAlgorithmIdentifier);
    assertEquals(base16().encode(certificationRequest.getSignature()), base16().encode(signature));
    assertEquals(certificationRequest, certificationRequest);
    assertEquals(certificationRequest.hashCode(), certificationRequest.hashCode());
    PKCS10CertificationRequest expectedCertificationRequest = new PKCS10CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()), new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA"), new DERBitString(signature)));
    assertEquals(base16().encode(certificationRequest.getEncoded()), base16().encode(expectedCertificationRequest.getEncoded()));
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) DERBitString(org.bouncycastle.asn1.DERBitString) DERBitString(org.bouncycastle.asn1.DERBitString) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) DERSet(org.bouncycastle.asn1.DERSet) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier(io.airlift.security.csr.SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier) X500Principal(javax.security.auth.x500.X500Principal) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Test(org.testng.annotations.Test)

Example 34 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project nifi by apache.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 35 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project nifi by apache.

the class TlsHelper method generateCertificationRequest.

public static JcaPKCS10CertificationRequest generateCertificationRequest(String requestedDn, String domainAlternativeNames, KeyPair keyPair, String signingAlgorithm) throws OperatorCreationException {
    JcaPKCS10CertificationRequestBuilder jcaPKCS10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(requestedDn), keyPair.getPublic());
    // add Subject Alternative Name(s)
    try {
        jcaPKCS10CertificationRequestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, createDomainAlternativeNamesExtensions(domainAlternativeNames, requestedDn));
    } catch (IOException e) {
        throw new OperatorCreationException("Error while adding " + domainAlternativeNames + " as Subject Alternative Name.", e);
    }
    JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(signingAlgorithm);
    return new JcaPKCS10CertificationRequest(jcaPKCS10CertificationRequestBuilder.build(jcaContentSignerBuilder.build(keyPair.getPrivate())));
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)193 X509Certificate (java.security.cert.X509Certificate)88 Date (java.util.Date)71 BigInteger (java.math.BigInteger)63 X500Name (sun.security.x509.X500Name)53 IOException (java.io.IOException)49 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)47 ContentSigner (org.bouncycastle.operator.ContentSigner)45 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)44 RDN (org.bouncycastle.asn1.x500.RDN)43 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)42 KeyPair (java.security.KeyPair)41 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)41 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)36 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)33 PrivateKey (java.security.PrivateKey)32 KeyPairGenerator (java.security.KeyPairGenerator)31 GeneralName (org.bouncycastle.asn1.x509.GeneralName)31 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)28 SecureRandom (java.security.SecureRandom)27