Search in sources :

Example 16 with X509Extensions

use of org.gudy.bouncycastle.asn1.x509.X509Extensions 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 17 with X509Extensions

use of org.gudy.bouncycastle.asn1.x509.X509Extensions in project BiglyBT by BiglySoftware.

the class X509CRLEntryObject method getExtensionOIDs.

private Set getExtensionOIDs(boolean critical) {
    X509Extensions extensions = c.getExtensions();
    if (extensions != null) {
        HashSet set = new HashSet();
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (critical == ext.isCritical()) {
                set.add(oid.getId());
            }
        }
        return set;
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension) X509Extensions(org.gudy.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.gudy.bouncycastle.asn1.DERObjectIdentifier) HashSet(java.util.HashSet)

Example 18 with X509Extensions

use of org.gudy.bouncycastle.asn1.x509.X509Extensions in project BiglyBT by BiglySoftware.

the class X509CertificateObject method hasUnsupportedCriticalExtension.

@Override
public boolean hasUnsupportedCriticalExtension() {
    if (this.getVersion() == 3) {
        X509Extensions extensions = c.getTBSCertificate().getExtensions();
        if (extensions != null) {
            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                if (oid.getId().equals("2.5.29.15") || oid.getId().equals("2.5.29.19")) {
                    continue;
                }
                X509Extension ext = extensions.getExtension(oid);
                if (ext.isCritical()) {
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension)

Example 19 with X509Extensions

use of org.gudy.bouncycastle.asn1.x509.X509Extensions in project BiglyBT by BiglySoftware.

the class X509CertificateObject method toString.

public String toString() {
    StringBuilder buf = new StringBuilder();
    String nl = System.getProperty("line.separator");
    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
    byte[] sig = this.getSignature();
    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
        if (i < sig.length - 20) {
            buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
        } else {
            buf.append("                       ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
        }
    }
    X509Extensions extensions = c.getTBSCertificate().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("       Extensions: \n");
        }
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (ext.getValue() != null) {
                byte[] octs = ext.getValue().getOctets();
                ByteArrayInputStream bIn = new ByteArrayInputStream(octs);
                DERInputStream dIn = new DERInputStream(bIn);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(X509Extensions.BasicConstraints)) {
                        buf.append(new BasicConstraints((ASN1Sequence) dIn.readObject())).append(nl);
                    } else if (oid.equals(X509Extensions.KeyUsage)) {
                        buf.append(new KeyUsage((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
                        buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
                        buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
                        buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    // buf.append(" value = " + "*****" + nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    // buf.append(" value = " + new String(Hex.encode(ext.getValue().getOctets())) + nl);
                    buf.append(" value = " + "*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    return buf.toString();
}
Also used : VerisignCzagExtension(org.gudy.bouncycastle.asn1.misc.VerisignCzagExtension) X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension) NetscapeRevocationURL(org.gudy.bouncycastle.asn1.misc.NetscapeRevocationURL) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) NetscapeCertType(org.gudy.bouncycastle.asn1.misc.NetscapeCertType)

Example 20 with X509Extensions

use of org.gudy.bouncycastle.asn1.x509.X509Extensions in project BiglyBT by BiglySoftware.

the class X509CertificateObject method getExtensionValue.

@Override
public byte[] getExtensionValue(String oid) {
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null) {
        X509Extension ext = exts.getExtension(new DERObjectIdentifier(oid));
        if (ext != null) {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            DEROutputStream dOut = new DEROutputStream(bOut);
            try {
                dOut.writeObject(ext.getValue());
                return bOut.toByteArray();
            } catch (Exception e) {
                throw new RuntimeException("error encoding " + e.toString());
            }
        }
    }
    return null;
}
Also used : X509Extension(org.gudy.bouncycastle.asn1.x509.X509Extension) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

Enumeration (java.util.Enumeration)12 X509Extensions (org.bouncycastle.asn1.x509.X509Extensions)11 X509Extension (org.gudy.bouncycastle.asn1.x509.X509Extension)11 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)10 X509Extension (org.bouncycastle.asn1.x509.X509Extension)10 HashSet (java.util.HashSet)8 IOException (java.io.IOException)7 Set (java.util.Set)6 X509Extensions (org.gudy.bouncycastle.asn1.x509.X509Extensions)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)3 DERObjectIdentifier (org.gudy.bouncycastle.asn1.DERObjectIdentifier)3 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SignatureException (java.security.SignatureException)2 CRLException (java.security.cert.CRLException)2 CertificateException (java.security.cert.CertificateException)2 CertificateExpiredException (java.security.cert.CertificateExpiredException)2