Search in sources :

Example 26 with Attributes

use of org.bouncycastle.asn1.cms.Attributes 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 27 with Attributes

use of org.bouncycastle.asn1.cms.Attributes in project ddf by codice.

the class PkiTools method makeDistinguishedName.

/**
 * Create an X500 name with a single populated attribute, the "common name". An X500 name object
 * details the identity of a machine, person, or organization. The name object is used as the
 * "subject" of a certificate. SSL/TLS typically uses a subject's common name as the DNS name for
 * a machine and this name must be correct or SSl/TLS will not trust the machine's certificate.
 *
 * <p>TLS can use a different set of attributes to, the Subject Alternative Names. SANs are
 * extensions to the X509 specification and can include IP addresses, DNS names and other machine
 * information. This package does not use SANs.
 *
 * @param commonName the fully qualified host name of the end entity
 * @return X500 name object with common name attribute set
 * @see <a href="https://www.ietf.org/rfc/rfc4514.txt">RFC 4514, section 'LDAP: Distinguished
 *     Names'</a>
 * @see <a href="https://tools.ietf.org/html/rfc4519">RFC 4519 details the exact construction of
 *     distinguished names</a>
 * @see <a href="https://en.wikipedia.org/wiki/SubjectAltName">Subject Alternative Names on
 *     Wikipedia'</a>
 */
public static X500Name makeDistinguishedName(String commonName) {
    Validate.isTrue(commonName != null, "Certificate common name cannot be null");
    if (commonName.isEmpty()) {
        LOGGER.warn("Setting certificate common name to empty string. This could result in an unusable TLS certificate.");
    }
    X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE);
    // Add more nameBuilder.addRDN(....) statements to support more X500 attributes.
    nameBuilder.addRDN(RFC4519Style.cn, commonName);
    return nameBuilder.build();
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Example 28 with Attributes

use of org.bouncycastle.asn1.cms.Attributes in project athenz by yahoo.

the class Crypto method extractX509CSRSANField.

private static List<String> extractX509CSRSANField(PKCS10CertificationRequest certReq, int tagNo) {
    List<String> values = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            // /CLOVER:OFF
            if (gns == null) {
                continue;
            }
            // /CLOVER:ON
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == tagNo) {
                    values.add(((DERIA5String) name.getName()).getString());
                }
            }
        }
    }
    return values;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions)

Example 29 with Attributes

use of org.bouncycastle.asn1.cms.Attributes in project pdfbox by apache.

the class CRLVerifier method downloadCRLFromLDAP.

/**
 * Downloads a CRL from given LDAP url, e.g.
 * ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 */
private static X509CRL downloadCRLFromLDAP(String ldapURL) throws CertificateException, NamingException, CRLException, CertificateVerificationException {
    @SuppressWarnings({ "squid:S1149" }) Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapURL);
    // https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/create.html
    // don't wait forever behind corporate proxy
    env.put("com.sun.jndi.ldap.connect.timeout", "1000");
    DirContext ctx = new InitialDirContext(env);
    Attributes avals = ctx.getAttributes("");
    Attribute aval = avals.get("certificateRevocationList;binary");
    byte[] val = (byte[]) aval.get();
    if (val == null || val.length == 0) {
        throw new CertificateVerificationException("Can not download CRL from: " + ldapURL);
    } else {
        InputStream inStream = new ByteArrayInputStream(val);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509CRL) cf.generateCRL(inStream);
    }
}
Also used : X509CRL(java.security.cert.X509CRL) Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attributes(javax.naming.directory.Attributes) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) CertificateFactory(java.security.cert.CertificateFactory) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 30 with Attributes

use of org.bouncycastle.asn1.cms.Attributes in project robovm by robovm.

the class X509AttributeCertificateHolder method getAttributes.

/**
     * Return the attributes, if any associated with this request.
     *
     * @return an array of Attribute, zero length if none present.
     */
public Attribute[] getAttributes() {
    ASN1Sequence seq = attrCert.getAcinfo().getAttributes();
    Attribute[] attrs = new Attribute[seq.size()];
    for (int i = 0; i != seq.size(); i++) {
        attrs[i] = Attribute.getInstance(seq.getObjectAt(i));
    }
    return attrs;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Attribute(org.bouncycastle.asn1.x509.Attribute)

Aggregations

ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)16 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)15 DEROctetString (org.bouncycastle.asn1.DEROctetString)13 X509Certificate (java.security.cert.X509Certificate)12 IOException (java.io.IOException)10 Date (java.util.Date)10 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)10 DERSequence (org.bouncycastle.asn1.DERSequence)9 DERIA5String (org.bouncycastle.asn1.DERIA5String)8 DERSet (org.bouncycastle.asn1.DERSet)8 Attribute (org.bouncycastle.asn1.cms.Attribute)8 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)8 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 BigInteger (java.math.BigInteger)7 KeyStore (java.security.KeyStore)7 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)7 DERTaggedObject (org.bouncycastle.asn1.DERTaggedObject)7