Search in sources :

Example 86 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.

the class X509V3CertificateGenerator method copyAndAddExtension.

/**
     * add a given extension field for the standard extensions tag (tag 3)
     * copying the extension value from another certificate.
     * @throws CertificateParsingException if the extension cannot be extracted.
     */
public void copyAndAddExtension(String oid, boolean critical, X509Certificate cert) throws CertificateParsingException {
    byte[] extValue = cert.getExtensionValue(oid);
    if (extValue == null) {
        throw new CertificateParsingException("extension " + oid + " not present");
    }
    try {
        ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue);
        this.addExtension(oid, critical, value);
    } catch (IOException e) {
        throw new CertificateParsingException(e.toString());
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) IOException(java.io.IOException)

Example 87 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.

the class V3TBSCertificateGenerator method generateTBSCertificate.

public TBSCertificateStructure generateTBSCertificate() {
    if ((serialNumber == null) || (signature == null) || (issuer == null) || (startDate == null) || (endDate == null) || (subject == null && !altNamePresentAndCritical) || (subjectPublicKeyInfo == null)) {
        throw new IllegalStateException("not all mandatory fields set in V3 TBScertificate generator");
    }
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(version);
    v.add(serialNumber);
    v.add(signature);
    v.add(issuer);
    //
    // before and after dates
    //
    ASN1EncodableVector validity = new ASN1EncodableVector();
    validity.add(startDate);
    validity.add(endDate);
    v.add(new DERSequence(validity));
    if (subject != null) {
        v.add(subject);
    } else {
        v.add(new DERSequence());
    }
    v.add(subjectPublicKeyInfo);
    if (issuerUniqueID != null) {
        v.add(new DERTaggedObject(false, 1, issuerUniqueID));
    }
    if (subjectUniqueID != null) {
        v.add(new DERTaggedObject(false, 2, subjectUniqueID));
    }
    if (extensions != null) {
        v.add(new DERTaggedObject(3, extensions));
    }
    return new TBSCertificateStructure(new DERSequence(v));
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Example 88 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.

the class X509Extensions method toASN1Object.

/**
     * <pre>
     *     Extensions        ::=   SEQUENCE SIZE (1..MAX) OF Extension
     *
     *     Extension         ::=   SEQUENCE {
     *        extnId            EXTENSION.&amp;id ({ExtensionSet}),
     *        critical          BOOLEAN DEFAULT FALSE,
     *        extnValue         OCTET STRING }
     * </pre>
     */
public DERObject toASN1Object() {
    ASN1EncodableVector vec = new ASN1EncodableVector();
    Enumeration e = ordering.elements();
    while (e.hasMoreElements()) {
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
        X509Extension ext = (X509Extension) extensions.get(oid);
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(oid);
        if (ext.isCritical()) {
            // BEGIN android-changed
            v.add(DERBoolean.TRUE);
        // END android-changed
        }
        v.add(ext.getValue());
        vec.add(new DERSequence(v));
    }
    return new DERSequence(vec);
}
Also used : Enumeration(java.util.Enumeration) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 89 with Extensions

use of org.bouncycastle.asn1.x509.Extensions 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 90 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project nhin-d by DirectProject.

the class TrustChainValidator method getIntermediateCertsByAIA.

/**
     * Retrieves intermediate certificate using the AIA extension.
     * @param certificate The certificate to search for AIA extensions.
     * @return Returns a collection of intermediate certs using the AIA extension.  If the AIA extension does not exists
     * or the certificate cannot be downloaded from the URL, then an empty list is returned.
     */
protected Collection<X509Certificate> getIntermediateCertsByAIA(X509Certificate certificate) {
    final Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    // check to see if there are extensions
    final AuthorityInfoAccessExtentionField aiaField = new AuthorityInfoAccessExtentionField(false);
    try {
        // we can get all names from the AuthorityInfoAccessExtentionField objects
        aiaField.injectReferenceValue(certificate);
        final Collection<String> urlPairs = aiaField.getPolicyValue().getPolicyValue();
        // look through all of the values (if they exist) for caIssuers
        for (String urlPair : urlPairs) {
            if (urlPair.startsWith(CA_ISSUER_CHECK_STRING)) {
                // the url pair is in the format of caIssuer:URL... need to break it 
                // apart to get the url
                final String url = urlPair.substring(CA_ISSUER_CHECK_STRING.length());
                // now pull the certificate from the URL
                try {
                    final Collection<X509Certificate> intermCerts = downloadCertsFromAIA(url);
                    retVal.addAll(intermCerts);
                } catch (NHINDException e) {
                    LOGGER.warn("Intermediate cert cannot be resolved from AIA extension.", e);
                }
            }
        }
    }///CLOVER:OFF
     catch (PolicyProcessException e) {
        LOGGER.warn("Intermediate cert cannot be resolved from AIA extension.", e);
    }
    return retVal;
}
Also used : AuthorityInfoAccessExtentionField(org.nhindirect.policy.x509.AuthorityInfoAccessExtentionField) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) PolicyProcessException(org.nhindirect.policy.PolicyProcessException)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Extensions (org.bouncycastle.asn1.x509.Extensions)62 Extension (org.bouncycastle.asn1.x509.Extension)58 IOException (java.io.IOException)45 DEROctetString (org.bouncycastle.asn1.DEROctetString)39 HashSet (java.util.HashSet)35 Enumeration (java.util.Enumeration)34 X500Name (org.bouncycastle.asn1.x500.X500Name)32 BigInteger (java.math.BigInteger)30 Date (java.util.Date)30 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 X509Certificate (java.security.cert.X509Certificate)25 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)25 ContentSigner (org.bouncycastle.operator.ContentSigner)24 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)23 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)22 ArrayList (java.util.ArrayList)21