Search in sources :

Example 31 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project XobotOS by xamarin.

the class AttributeCertificateInfo method toASN1Object.

/**
     * Produce an object suitable for an ASN1OutputStream.
     * <pre>
     *  AttributeCertificateInfo ::= SEQUENCE {
     *       version              AttCertVersion -- version is v2,
     *       holder               Holder,
     *       issuer               AttCertIssuer,
     *       signature            AlgorithmIdentifier,
     *       serialNumber         CertificateSerialNumber,
     *       attrCertValidityPeriod   AttCertValidityPeriod,
     *       attributes           SEQUENCE OF Attribute,
     *       issuerUniqueID       UniqueIdentifier OPTIONAL,
     *       extensions           Extensions OPTIONAL
     *  }
     *
     *  AttCertVersion ::= INTEGER { v2(1) }
     * </pre>
     */
public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(version);
    v.add(holder);
    v.add(issuer);
    v.add(signature);
    v.add(serialNumber);
    v.add(attrCertValidityPeriod);
    v.add(attributes);
    if (issuerUniqueID != null) {
        v.add(issuerUniqueID);
    }
    if (extensions != null) {
        v.add(extensions);
    }
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Example 32 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method engineLoad.

public void engineLoad(InputStream stream, char[] password) throws IOException {
    if (// just initialising
    stream == null) {
        return;
    }
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    BufferedInputStream bufIn = new BufferedInputStream(stream);
    bufIn.mark(10);
    int head = bufIn.read();
    if (head != 0x30) {
        throw new IOException("stream does not represent a PKCS12 key store");
    }
    bufIn.reset();
    ASN1InputStream bIn = new ASN1InputStream(bufIn);
    ASN1Sequence obj = (ASN1Sequence) bIn.readObject();
    Pfx bag = new Pfx(obj);
    ContentInfo info = bag.getAuthSafe();
    Vector chain = new Vector();
    boolean unmarkedKey = false;
    boolean wrongPKCS12Zero = false;
    if (// check the mac code
    bag.getMacData() != null) {
        MacData mData = bag.getMacData();
        DigestInfo dInfo = mData.getMac();
        AlgorithmIdentifier algId = dInfo.getAlgorithmId();
        byte[] salt = mData.getSalt();
        int itCount = mData.getIterationCount().intValue();
        byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
        try {
            byte[] res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, false, data);
            byte[] dig = dInfo.getDigest();
            if (!Arrays.constantTimeAreEqual(res, dig)) {
                if (password.length > 0) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                // Try with incorrect zero length password
                res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, true, data);
                if (!Arrays.constantTimeAreEqual(res, dig)) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                wrongPKCS12Zero = true;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException("error constructing MAC: " + e.toString());
        }
    }
    keys = new IgnoresCaseHashtable();
    localIds = new Hashtable();
    if (info.getContentType().equals(data)) {
        bIn = new ASN1InputStream(((ASN1OctetString) info.getContent()).getOctets());
        AuthenticatedSafe authSafe = new AuthenticatedSafe((ASN1Sequence) bIn.readObject());
        ContentInfo[] c = authSafe.getContentInfo();
        for (int i = 0; i != c.length; i++) {
            if (c[i].getContentType().equals(data)) {
                ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString) c[i].getContent()).getOctets());
                ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        if (b.getBagAttributes() != null) {
                            Enumeration e = b.getBagAttributes().getObjects();
                            while (e.hasMoreElements()) {
                                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                                DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                                ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                                DERObject attr = null;
                                if (attrSet.size() > 0) {
                                    attr = (DERObject) attrSet.getObjectAt(0);
                                    DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                    if (existing != null) {
                                        // OK, but the value has to be the same
                                        if (!existing.getDERObject().equals(attr)) {
                                            throw new IOException("attempt to add existing attribute with different value");
                                        }
                                    } else {
                                        bagAttr.setBagAttribute(aOid, attr);
                                    }
                                }
                                if (aOid.equals(pkcs_9_at_friendlyName)) {
                                    alias = ((DERBMPString) attr).getString();
                                    keys.put(alias, privKey);
                                } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                    localId = (ASN1OctetString) attr;
                                }
                            }
                        }
                        if (localId != null) {
                            String name = new String(Hex.encode(localId.getOctets()));
                            if (alias == null) {
                                keys.put(name, privKey);
                            } else {
                                localIds.put(alias, name);
                            }
                        } else {
                            unmarkedKey = true;
                            keys.put("unmarked", privKey);
                        }
                    } else if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else {
                        System.out.println("extra in data " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else if (c[i].getContentType().equals(encryptedData)) {
                EncryptedData d = new EncryptedData((ASN1Sequence) c[i].getContent());
                byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
                ASN1Sequence seq = (ASN1Sequence) ASN1Object.fromByteArray(octets);
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
                    if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            DERObject attr = null;
                            if (attrSet.size() > 0) {
                                attr = (DERObject) attrSet.getObjectAt(0);
                                DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.getDERObject().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else if (b.getBagId().equals(keyBag)) {
                        org.bouncycastle.asn1.pkcs.PrivateKeyInfo pIn = new org.bouncycastle.asn1.pkcs.PrivateKeyInfo((ASN1Sequence) b.getBagValue());
                        PrivateKey privKey = JDKKeyFactory.createPrivateKeyFromPrivateKeyInfo(pIn);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            DERObject attr = null;
                            if (attrSet.size() > 0) {
                                attr = (DERObject) attrSet.getObjectAt(0);
                                DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.getDERObject().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else {
                        System.out.println("extra in encryptedData " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else {
                System.out.println("extra " + c[i].getContentType().getId());
                System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
            }
        }
    }
    certs = new IgnoresCaseHashtable();
    chainCerts = new Hashtable();
    keyCerts = new Hashtable();
    for (int i = 0; i != chain.size(); i++) {
        SafeBag b = (SafeBag) chain.elementAt(i);
        CertBag cb = new CertBag((ASN1Sequence) b.getBagValue());
        if (!cb.getCertId().equals(x509Certificate)) {
            throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
        }
        Certificate cert;
        try {
            ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
            cert = certFact.generateCertificate(cIn);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
        //
        // set the attributes
        //
        ASN1OctetString localId = null;
        String alias = null;
        if (b.getBagAttributes() != null) {
            Enumeration e = b.getBagAttributes().getObjects();
            while (e.hasMoreElements()) {
                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                DERObjectIdentifier oid = (DERObjectIdentifier) sq.getObjectAt(0);
                DERObject attr = (DERObject) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
                PKCS12BagAttributeCarrier bagAttr = null;
                if (cert instanceof PKCS12BagAttributeCarrier) {
                    bagAttr = (PKCS12BagAttributeCarrier) cert;
                    DEREncodable existing = bagAttr.getBagAttribute(oid);
                    if (existing != null) {
                        // OK, but the value has to be the same
                        if (!existing.getDERObject().equals(attr)) {
                            throw new IOException("attempt to add existing attribute with different value");
                        }
                    } else {
                        bagAttr.setBagAttribute(oid, attr);
                    }
                }
                if (oid.equals(pkcs_9_at_friendlyName)) {
                    alias = ((DERBMPString) attr).getString();
                } else if (oid.equals(pkcs_9_at_localKeyId)) {
                    localId = (ASN1OctetString) attr;
                }
            }
        }
        chainCerts.put(new CertId(cert.getPublicKey()), cert);
        if (unmarkedKey) {
            if (keyCerts.isEmpty()) {
                String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
                keyCerts.put(name, cert);
                keys.put(name, keys.remove("unmarked"));
            }
        } else {
            //
            if (localId != null) {
                String name = new String(Hex.encode(localId.getOctets()));
                keyCerts.put(name, cert);
            }
            if (alias != null) {
                certs.put(alias, cert);
            }
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERObject(org.bouncycastle.asn1.DERObject) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) MacData(org.bouncycastle.asn1.pkcs.MacData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Hashtable(java.util.Hashtable) IOException(java.io.IOException) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CertBag(org.bouncycastle.asn1.pkcs.CertBag) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) DEREncodable(org.bouncycastle.asn1.DEREncodable) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 33 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project XobotOS by xamarin.

the class CertPathValidatorUtilities method getCRLIssuersFromDistributionPoint.

/**
     * Add the CRL issuers from the cRLIssuer field of the distribution point or
     * from the certificate if not given to the issuer criterion of the
     * <code>selector</code>.
     * <p>
     * The <code>issuerPrincipals</code> are a collection with a single
     * <code>X500Principal</code> for <code>X509Certificate</code>s. For
     * {@link X509AttributeCertificate}s the issuer may contain more than one
     * <code>X500Principal</code>.
     *
     * @param dp The distribution point.
     * @param issuerPrincipals The issuers of the certificate or attribute
     *            certificate which contains the distribution point.
     * @param selector The CRL selector.
     * @param pkixParams The PKIX parameters containing the cert stores.
     * @throws AnnotatedException if an exception occurs while processing.
     * @throws ClassCastException if <code>issuerPrincipals</code> does not
     * contain only <code>X500Principal</code>s.
     */
protected static void getCRLIssuersFromDistributionPoint(DistributionPoint dp, Collection issuerPrincipals, X509CRLSelector selector, ExtendedPKIXParameters pkixParams) throws AnnotatedException {
    List issuers = new ArrayList();
    // indirect CRL
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        // look for a DN
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    issuers.add(new X500Principal(genNames[j].getName().getDERObject().getEncoded()));
                } catch (IOException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
    } else {
        /*
             * certificate issuer is CRL issuer, distributionPoint field MUST be
             * present.
             */
        if (dp.getDistributionPoint() == null) {
            throw new AnnotatedException("CRL issuer is omitted from distribution point but no distributionPoint field present.");
        }
        // add and check issuer principals
        for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) {
            issuers.add((X500Principal) it.next());
        }
    }
    // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
    // distributionPoint
    //        if (dp.getDistributionPoint() != null)
    //        {
    //            // look for nameRelativeToCRLIssuer
    //            if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
    //            {
    //                // append fragment to issuer, only one
    //                // issuer can be there, if this is given
    //                if (issuers.size() != 1)
    //                {
    //                    throw new AnnotatedException(
    //                        "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
    //                }
    //                DEREncodable relName = dp.getDistributionPoint().getName();
    //                Iterator it = issuers.iterator();
    //                List issuersTemp = new ArrayList(issuers.size());
    //                while (it.hasNext())
    //                {
    //                    Enumeration e = null;
    //                    try
    //                    {
    //                        e = ASN1Sequence.getInstance(
    //                            new ASN1InputStream(((X500Principal) it.next())
    //                                .getEncoded()).readObject()).getObjects();
    //                    }
    //                    catch (IOException ex)
    //                    {
    //                        throw new AnnotatedException(
    //                            "Cannot decode CRL issuer information.", ex);
    //                    }
    //                    ASN1EncodableVector v = new ASN1EncodableVector();
    //                    while (e.hasMoreElements())
    //                    {
    //                        v.add((DEREncodable) e.nextElement());
    //                    }
    //                    v.add(relName);
    //                    issuersTemp.add(new X500Principal(new DERSequence(v)
    //                        .getDEREncoded()));
    //                }
    //                issuers.clear();
    //                issuers.addAll(issuersTemp);
    //            }
    //        }
    Iterator it = issuers.iterator();
    while (it.hasNext()) {
        try {
            selector.addIssuerName(((X500Principal) it.next()).getEncoded());
        } catch (IOException ex) {
            throw new AnnotatedException("Cannot decode CRL issuer information.", ex);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) X500Principal(javax.security.auth.x500.X500Principal) List(java.util.List) ArrayList(java.util.ArrayList) CertificateList(org.bouncycastle.asn1.x509.CertificateList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 34 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Example 35 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method logDigests.

protected void logDigests(SignerInformation sigInfo) {
    // will fail
    if (this.m_logDigest && sigInfo != null) {
        try {
            //get the digests
            final Attribute digAttr = sigInfo.getSignedAttributes().get(CMSAttributes.messageDigest);
            final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
            final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
            final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
            LOGGER.info("Signed Message Digest: " + signedDigestHex);
            // should have the computed digest now
            final byte[] digest = sigInfo.getContentDigest();
            final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
            LOGGER.info("Computed Message Digest: " + digestHex);
        } catch (Throwable t) {
        /* no-op.... logging digests is a quiet operation */
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERObject(org.bouncycastle.asn1.DERObject) Attribute(org.bouncycastle.asn1.cms.Attribute) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString)

Aggregations

ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)18 IOException (java.io.IOException)16 ArrayList (java.util.ArrayList)13 List (java.util.List)11 Attribute (org.bouncycastle.asn1.cms.Attribute)10 X509Certificate (java.security.cert.X509Certificate)9 DEROctetString (org.bouncycastle.asn1.DEROctetString)9 DERSequence (org.bouncycastle.asn1.DERSequence)9 GeneralName (org.bouncycastle.asn1.x509.GeneralName)9 Iterator (java.util.Iterator)8 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)8 DERObject (org.bouncycastle.asn1.DERObject)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)6 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)6 ASN1Set (org.bouncycastle.asn1.ASN1Set)6 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)6 Enumeration (java.util.Enumeration)5 X500Principal (javax.security.auth.x500.X500Principal)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Vector (java.util.Vector)4