Search in sources :

Example 1 with PKCS10CertificationRequest

use of org.bouncycastle.jce.PKCS10CertificationRequest in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Example 2 with PKCS10CertificationRequest

use of org.bouncycastle.jce.PKCS10CertificationRequest in project nhin-d by DirectProject.

the class CAPanel method signCSR.

private void signCSR() {
    JFileChooser fc = new JFileChooser();
    fc.setDragEnabled(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    fc.setDialogTitle("Open Signing Request PEM File");
    int result = fc.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        final File fl = fc.getSelectedFile();
        PEMReader reader = null;
        try {
            reader = new PEMReader(new InputStreamReader(FileUtils.openInputStream(fl)));
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) reader.readObject();
            certReq.verify();
            final X509Certificate signedCert = CertGenerator.createCertFromCSR(certReq, currentCert);
            // validate the certificate 
            signedCert.verify(currentCert.getSignerCert().getPublicKey());
            // write it to a file
            final String addressName = CryptoExtensions.getSubjectAddress(signedCert);
            final File outFile = new File(addressName + ".der");
            FileUtils.writeByteArrayToFile(outFile, signedCert.getEncoded());
            JOptionPane.showMessageDialog(this, "Signing successful.\r\nCertificate saved to " + outFile.getAbsolutePath(), "CSR Sign", JOptionPane.PLAIN_MESSAGE);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error signging CSR: " + e.getMessage(), "CSR Sign Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) JFileChooser(javax.swing.JFileChooser) InputStreamReader(java.io.InputStreamReader) PEMReader(org.bouncycastle.openssl.PEMReader) File(java.io.File) X509Certificate(java.security.cert.X509Certificate)

Example 3 with PKCS10CertificationRequest

use of org.bouncycastle.jce.PKCS10CertificationRequest 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 4 with PKCS10CertificationRequest

use of org.bouncycastle.jce.PKCS10CertificationRequest in project oxTrust by GluuFederation.

the class ManageCertificateAction method generateCSR.

public String generateCSR(String fileName) throws IOException {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    KeyPair pair = getKeyPair(fileName);
    boolean result = false;
    if (pair != null) {
        String url = appConfiguration.getIdpUrl().replaceFirst(".*//", "");
        String csrPrincipal = String.format("CN=%s", url);
        X500Principal principal = new X500Principal(csrPrincipal);
        PKCS10CertificationRequest csr = null;
        try {
            csr = new PKCS10CertificationRequest("SHA1withRSA", principal, pair.getPublic(), null, pair.getPrivate());
        } catch (GeneralSecurityException e) {
            log.error(e.getMessage(), e);
            return OxTrustConstants.RESULT_FAILURE;
        }
        // Form download responce
        StringBuilder response = new StringBuilder();
        response.append(BEGIN_CERT_REQ + "\n");
        response.append(WordUtils.wrap(new String(Base64.encode(csr.getEncoded(ASN1Encoding.DER))), 64, "\n", true) + "\n");
        response.append(END_CERT_REQ + "\n");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        result = ResponseHelper.downloadFile("csr.pem", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN, response.toString().getBytes(), facesContext);
    }
    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) FacesContext(javax.faces.context.FacesContext) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) X500Principal(javax.security.auth.x500.X500Principal) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

PKCS10CertificationRequest (org.bouncycastle.jce.PKCS10CertificationRequest)4 X509Certificate (java.security.cert.X509Certificate)3 File (java.io.File)2 KeyPair (java.security.KeyPair)2 PrivateKey (java.security.PrivateKey)2 X500Principal (javax.security.auth.x500.X500Principal)2 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)2 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 BigInteger (java.math.BigInteger)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Key (java.security.Key)1 KeyStore (java.security.KeyStore)1 PublicKey (java.security.PublicKey)1 CRLException (java.security.cert.CRLException)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 X509CRL (java.security.cert.X509CRL)1 DSAPrivateKey (java.security.interfaces.DSAPrivateKey)1 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)1 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)1