Search in sources :

Example 81 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project ats-framework by Axway.

the class SMimePackageEncryptor method sign.

@PublicAtsApi
public Package sign(Package sourcePackage) throws ActionException {
    try {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        KeyStore ks = getKeystore();
        // TODO wrap exception with possible causes and add some hint
        PrivateKey privateKey = (PrivateKey) ks.getKey(aliasOrCN, certPassword.toCharArray());
        // Get whole certificate chain
        Certificate[] certArr = ks.getCertificateChain(aliasOrCN);
        // Pre 4.0.6 behavior was not to attach full cert. chain X509Certificate cer = (X509Certificate) ks.getCertificate(aliasOrCN);
        if (certArr.length >= 1) {
            LOG.debug("Found certificate of alias: " + aliasOrCN + ". Lenght of cert chain: " + certArr.length + ", child cert:" + certArr[0].toString());
        }
        X509Certificate childCert = (X509Certificate) certArr[0];
        /* Create the SMIMESignedGenerator */
        ASN1EncodableVector attributes = new ASN1EncodableVector();
        attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(new X500Name(childCert.getIssuerDN().getName()), childCert.getSerialNumber())));
        SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
        capabilities.addCapability(SMIMECapability.aES128_CBC);
        capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
        capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
        capabilities.addCapability(SMIMECapability.dES_CBC);
        attributes.add(new SMIMECapabilitiesAttribute(capabilities));
        if (signatureAlgorithm == null) {
            // not specified explicitly
            // TODO check defaults to be used
            signatureAlgorithm = SignatureAlgorithm.DSA.equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA";
        }
        SMIMESignedGenerator signer = new SMIMESignedGenerator();
        JcaSimpleSignerInfoGeneratorBuilder signerGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder();
        signerGeneratorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
        signerGeneratorBuilder.setSignedAttributeGenerator(new AttributeTable(attributes));
        signer.addSignerInfoGenerator(signerGeneratorBuilder.build(signatureAlgorithm, privateKey, childCert));
        /* Add the list of certs to the generator */
        List<X509Certificate> certList = new ArrayList<X509Certificate>();
        for (int i = 0; i < certArr.length; i++) {
            // first add child cert, and CAs
            certList.add((X509Certificate) certArr[i]);
        }
        Store<?> certs = new JcaCertStore(certList);
        signer.addCertificates(certs);
        /* Sign the message */
        Session session = Session.getDefaultInstance(System.getProperties(), null);
        MimeMultipart mm = signer.generate(getMimeMessage(sourcePackage));
        MimeMessage signedMessage = new MimeMessage(session);
        /* Set all original MIME headers in the signed message */
        Enumeration<?> headers = getMimeMessage(sourcePackage).getAllHeaderLines();
        while (headers.hasMoreElements()) {
            signedMessage.addHeaderLine((String) headers.nextElement());
        }
        /* Set the content of the signed message */
        signedMessage.setContent(mm);
        signedMessage.saveChanges();
        return new MimePackage(signedMessage);
    } catch (Exception e) {
        throw new ActionException(EXCEPTION_WHILE_SIGNING, e);
    }
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) PrivateKey(java.security.PrivateKey) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ArrayList(java.util.ArrayList) SMIMESignedGenerator(org.bouncycastle.mail.smime.SMIMESignedGenerator) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) X500Name(org.bouncycastle.asn1.x500.X500Name) MimePackage(com.axway.ats.action.objects.MimePackage) SMIMEEncryptionKeyPreferenceAttribute(org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) JcaSimpleSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) ActionException(com.axway.ats.action.model.ActionException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) ActionException(com.axway.ats.action.model.ActionException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Session(javax.mail.Session) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 82 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project j2objc by google.

the class PKCS7 method populateCertIssuerNames.

/**
 * Populate array of Issuer DNs from certificates and convert
 * each Principal to type X500Name if necessary.
 */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;
    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal) tbsCert.get(X509CertInfo.ISSUER + "." + X509CertInfo.DN_NAME);
            } catch (Exception e) {
            // error generating X500Name object from the cert's
            // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
Also used : X509CertInfo(sun.security.x509.X509CertInfo) X500Name(sun.security.x509.X500Name) X509Certificate(java.security.cert.X509Certificate) X500Principal(javax.security.auth.x500.X500Principal) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) CertificateException(java.security.cert.CertificateException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CRLException(java.security.cert.CRLException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 83 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project acme4j by shred.

the class CertificateUtils method createTestIntermediateCertificate.

/**
 * Creates an intermediate certificate that is signed by an issuer.
 * <p>
 * The generated certificate is only meant for testing purposes!
 *
 * @param subject
 *         This certificate's subject X.500 name.
 * @param notBefore
 *         {@link Instant} before which the certificate is not valid.
 * @param notAfter
 *         {@link Instant} after which the certificate is not valid.
 * @param intermediatePublicKey
 *         {@link PublicKey} of this certificate
 * @param issuer
 *         The issuer's {@link X509Certificate}.
 * @param issuerPrivateKey
 *         {@link PrivateKey} of the issuer. This is not the private key of this
 *         intermediate certificate.
 * @return Generated {@link X509Certificate}
 * @since 2.8
 */
public static X509Certificate createTestIntermediateCertificate(String subject, Instant notBefore, Instant notAfter, PublicKey intermediatePublicKey, X509Certificate issuer, PrivateKey issuerPrivateKey) {
    Objects.requireNonNull(subject, "subject");
    Objects.requireNonNull(notBefore, "notBefore");
    Objects.requireNonNull(notAfter, "notAfter");
    Objects.requireNonNull(intermediatePublicKey, "intermediatePublicKey");
    Objects.requireNonNull(issuer, "issuer");
    Objects.requireNonNull(issuerPrivateKey, "issuerPrivateKey");
    JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(new X500Name(issuer.getIssuerX500Principal().getName()), BigInteger.valueOf(System.currentTimeMillis()), Date.from(notBefore), Date.from(notAfter), new X500Name(subject), intermediatePublicKey);
    return buildCertificate(certBuilder::build, issuerPrivateKey);
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder)

Example 84 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project acme4j by shred.

the class CSRBuilderTest method csrTest.

/**
 * Checks if the CSR contains the right parameters.
 * <p>
 * This is not supposed to be a Bouncy Castle test. If the
 * {@link PKCS10CertificationRequest} contains the right parameters, we assume that
 * Bouncy Castle encodes it properly.
 */
private void csrTest(PKCS10CertificationRequest csr) {
    X500Name name = csr.getSubject();
    try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
        softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("abc.de");
        softly.assertThat(name.getRDNs(BCStyle.C)).as("C").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("XX");
        softly.assertThat(name.getRDNs(BCStyle.L)).as("L").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testville");
        softly.assertThat(name.getRDNs(BCStyle.O)).as("O").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testing Co");
        softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testunit");
        softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("ABC");
    }
    Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    assertThat(attr).hasSize(1);
    ASN1Encodable[] extensions = attr[0].getAttrValues().toArray();
    assertThat(extensions).hasSize(1);
    GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName);
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.dNSName).extracting(gn -> ASN1IA5String.getInstance(gn.getName()).getString()).containsExactlyInAnyOrder("abc.de", "fg.hi", "jklm.no", "pqr.st", "uv.wx", "y.z", "*.wild.card", "ide1.nt", "ide2.nt", "ide3.nt");
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.iPAddress).extracting(gn -> getIP(gn.getName()).getHostAddress()).containsExactlyInAnyOrder("192.168.0.1", "192.168.0.2", "10.0.0.1", "10.0.0.2", "fd00:0:0:0:0:0:0:1", "fd00:0:0:0:0:0:0:2", "192.168.5.5", "192.168.5.6", "192.168.5.7");
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Identifier(org.shredzone.acme4j.Identifier) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) Extension(org.bouncycastle.asn1.x509.Extension) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Security(java.security.Security) DEROctetString(org.bouncycastle.asn1.DEROctetString) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) InetAddress(java.net.InetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) BeforeAll(org.junit.jupiter.api.BeforeAll) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) PEMParser(org.bouncycastle.openssl.PEMParser) StringWriter(java.io.StringWriter) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) StandardCharsets(java.nio.charset.StandardCharsets) Extensions(org.bouncycastle.asn1.x509.Extensions) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Test(org.junit.jupiter.api.Test) GeneralName(org.bouncycastle.asn1.x509.GeneralName) StringReader(java.io.StringReader) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions)

Example 85 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project acme4j by shred.

the class SMIMECSRBuilderTest method smimeCsrTest.

/**
 * Checks if the S/MIME CSR contains the right parameters.
 * <p>
 * This is not supposed to be a Bouncy Castle test. If the
 * {@link PKCS10CertificationRequest} contains the right parameters, we assume that
 * Bouncy Castle encodes it properly.
 */
private void smimeCsrTest(PKCS10CertificationRequest csr) {
    X500Name name = csr.getSubject();
    try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
        softly.assertThat(name.getRDNs(BCStyle.CN)).as("CN").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("mail@example.com");
        softly.assertThat(name.getRDNs(BCStyle.C)).as("C").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("XX");
        softly.assertThat(name.getRDNs(BCStyle.L)).as("L").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testville");
        softly.assertThat(name.getRDNs(BCStyle.O)).as("O").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testing Co");
        softly.assertThat(name.getRDNs(BCStyle.OU)).as("OU").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("Testunit");
        softly.assertThat(name.getRDNs(BCStyle.ST)).as("ST").extracting(rdn -> rdn.getFirst().getValue().toString()).contains("ABC");
    }
    Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    assertThat(attr).hasSize(1);
    ASN1Encodable[] extensions = attr[0].getAttrValues().toArray();
    assertThat(extensions).hasSize(1);
    GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName);
    assertThat(names.getNames()).filteredOn(gn -> gn.getTagNo() == GeneralName.rfc822Name).extracting(gn -> DERIA5String.getInstance(gn.getName()).getString()).containsExactlyInAnyOrder("mail@example.com", "info@example.com", "sales@example.com", "shop@example.com", "support@example.com", "help@example.com");
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) Extension(org.bouncycastle.asn1.x509.Extension) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Security(java.security.Security) DERBitString(org.bouncycastle.asn1.DERBitString) AddressException(jakarta.mail.internet.AddressException) BCStyle(org.bouncycastle.asn1.x500.style.BCStyle) InternetAddress(jakarta.mail.internet.InternetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) BeforeAll(org.junit.jupiter.api.BeforeAll) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) UTF_8(java.nio.charset.StandardCharsets.UTF_8) PEMParser(org.bouncycastle.openssl.PEMParser) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Test(org.junit.jupiter.api.Test) GeneralName(org.bouncycastle.asn1.x509.GeneralName) StringReader(java.io.StringReader) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairUtils(org.shredzone.acme4j.util.KeyPairUtils) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) AutoCloseableSoftAssertions(org.assertj.core.api.AutoCloseableSoftAssertions)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)182 BigInteger (java.math.BigInteger)175 Date (java.util.Date)168 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)158 ContentSigner (org.bouncycastle.operator.ContentSigner)149 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)145 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)127 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)127 IOException (java.io.IOException)104 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 RDN (org.bouncycastle.asn1.x500.RDN)75 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)55 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 SecureRandom (java.security.SecureRandom)54