Example usage for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest

List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest

Introduction

In this page you can find the example usage for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest.

Prototype

public PKCS10CertificationRequest(ASN1Sequence sequence) 

Source Link

Usage

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception {
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile));
    String subject = csr.getCertificationRequestInfo().getSubject().toString();

    // Generate the app certificate
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();/*from w ww  . j  a v  a  2s.co m*/
    X509Certificate rootCert = (X509Certificate) store.getCertificate(alias);
    if (rootCert == null) {
        System.out
                .println("ERROR: Aborting application certificate creation." + " No root certificate to sign.");
        cleanup(); // removes the self signed certificate from the keystore
        System.exit(1);
    }
    cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter()));
    cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter()));
    cg.setNotBefore(rootCert.getNotBefore());
    cg.setNotAfter(rootCert.getNotAfter());
    cg.setPublicKey(csr.getPublicKey());
    cg.setSerialNumber(appCertSerNo);

    // BD-J mandates using SHA1WithRSA as a signature Algorithm
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature));

    // FIXME: Ideally this should be pulled out from the original app cert's
    // extension. Email on X500Name is not encoded with UTF8String.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    // Assuming that the root certificate was generated using our tool,
    // the certificate should have IssuerAlternativeNames as an extension.
    if (rootCert.getIssuerAlternativeNames() == null) {
        System.out.println("ERROR: the root certificate must have an alternate name");
        System.exit(1);
    }
    List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next();
    cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false,
            getRfc822Name((String) issuerName.get(1)));
    PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray());
    X509Certificate cert = cg.generate(privateKey);

    // Now, write leaf certificate
    System.out.println("Writing cert to " + certfile + ".");
    FileOutputStream str = new FileOutputStream(certfile);
    str.write(cert.getEncoded());
    str.close();
}

From source file:net.jxta.impl.protocol.CertificateSigningRequest.java

License:Open Source License

/**
 *  Initializes the message from a document.
 **///w  w w. j a v  a 2  s .  co  m
protected void initialize(Element root) {
    if (!XMLElement.class.isInstance(root)) {
        throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement");
    }

    XMLElement doc = (XMLElement) root;

    String docName = doc.getName();

    if (!docName.equals(getMessageType())) {
        throw new IllegalArgumentException(
                "Could not construct : " + getClass().getName() + "from doc containing a " + docName);
    }

    String value = doc.getTextValue();

    value = value.trim();

    try {
        byte[] csr_der = PSEUtils.base64Decode(new StringReader(value));

        csr = new PKCS10CertificationRequest(csr_der);
    } catch (IOException error) {
        throw new IllegalArgumentException("bad certificate signing request.");
    }

    // Begin checking sanity!
    if (null == csr) {
        throw new IllegalArgumentException("certificate signing request not initialized.");
    }
}

From source file:org.apache.cloudstack.ca.provider.RootCAProvider.java

License:Apache License

private Certificate generateCertificateUsingCsr(final String csr, final List<String> domainNames,
        final List<String> ipAddresses, final int validityDays)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException,
        SignatureException, IOException, OperatorCreationException {
    PemObject pemObject = null;// ww w.jav  a 2 s  .c o m

    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }

    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }

    final PKCS10CertificationRequest request = new PKCS10CertificationRequest(pemObject.getContent());

    final String subject = request.getCertificationRequestInfo().getSubject().toString();
    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(caCertificate, caKeyPair,
            request.getPublicKey(), subject, CAManager.CertSignatureAlgorithm.value(), validityDays,
            domainNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}

From source file:org.cagrid.gaards.pki.BouncyCastleCertProcessingFactory.java

License:Open Source License

/**
 * Creates a proxy certificate from the certificate request. (Signs a
 * certificate request creating a new certificate)
 * /*  w w w  . j av a  2  s .c om*/
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int,
 *      int, X509ExtensionSet, String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less
 *            then) the new certificate will have the same lifetime as the
 *            issuing certificate.
 * @param delegationMode
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy
 *            certificate. Can be null. If delegation mode is
 *            {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.GSI_3_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension 
 *            ProxyCertInfoExtension} must be present in the extension set.
 * @param cnValue
 *            the value of the CN component of the subject of the new
 *            certificate. If null, the defaults will be used depending on
 *            the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate
 * @exception IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createCertificate(String provider, InputStream certRequestInputStream,
        X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet,
        String cnValue, String signatureAlgorithm) throws IOException, GeneralSecurityException {

    DERInputStream derin = new DERInputStream(certRequestInputStream);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    return createProxyCertificate(provider, cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode,
            extSet, cnValue, signatureAlgorithm);
}

From source file:org.deviceconnect.android.ssl.CertificateAuthority.java

License:MIT License

/**
 * ??????./*from  w  w  w  .ja v a 2  s.  c o m*/
 *
 * @param pkcs10 PKCS#10?????.
 * @return ???????. ?????null
 */
byte[] requestCertificate(final byte[] pkcs10) {
    try {
        if (getRootCertificate() == null) {
            return null;
        }

        // ??
        PKCS10CertificationRequest request = new PKCS10CertificationRequest(pkcs10);
        PrivateKey signingKey = mRootKeyStoreMgr.getPrivateKey(mIssuerName);
        KeyPair keyPair = new KeyPair(request.getPublicKey(), signingKey);
        X500Principal subject = new X500Principal("CN=localhost");
        X500Principal issuer = new X500Principal("CN=" + mIssuerName);
        GeneralNames generalNames = parseSANs(request);

        // 
        Certificate certificate = mRootKeyStoreMgr.generateX509V3Certificate(keyPair, subject, issuer,
                generalNames, false);
        return certificate.getEncoded();
    } catch (GeneralSecurityException e) {
        mLogger.log(Level.SEVERE, "Failed to generate certificate to byte array.", e);
    } catch (IOException e) {
        mLogger.log(Level.SEVERE, "Failed to parse SANs in certificate.", e);
    }
    return null;
}

From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java

License:Open Source License

private void init() {
    pkcs10 = new PKCS10CertificationRequest(p10msg);
}

From source file:org.ejbca.core.protocol.ws.common.PKCS10Helper.java

License:Open Source License

/**
 * Retrieves the pkcs10 from the encoded data.
 *//*from   w w  w .  j a  v a2 s  .  c om*/
public static PKCS10CertificationRequest getPKCS10(byte[] pkcs10Data) {
    return new PKCS10CertificationRequest(pkcs10Data);
}

From source file:org.ejbca.externalra.gui.EnrollInterfaceBean.java

License:Open Source License

/**
 * Used for reading a Certificate Signing Request file upload into the certificate request String.
 * @param actionEvent is the parameter from the web framework containing the file.
 *//*from  www.  ja v  a2 s.  c om*/
public void uploadActionListener(ActionEvent actionEvent) {
    InputFile inputFile = (InputFile) actionEvent.getSource();
    FacesContext context = FacesContext.getCurrentInstance();
    if (inputFile.getFileInfo().isSaved()) {
        // Validate that it is a CSR..
        File f = inputFile.getFileInfo().getFile();
        // Assume this is a small file.. it should be..
        long len = f.length();
        if (len < 16 * 1024L) {
            byte[] buf = new byte[(int) len];
            try {
                FileInputStream in = new FileInputStream(f);
                in.read(buf);
                in.close();
            } catch (IOException e) {
                context.addMessage(null /*actionEvent.getComponent().getClientId(context)*/, new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, getMessage("enroll.csrcert.uploadfailed"), null));
                log.debug("Rejected uploaded file due to IOException.");
                return;
            }
            try {
                // See if it was a PEM
                buf = FileTools.getBytesFromPEM(buf, PEM_CSR_BEGIN, PEM_CSR_END);
            } catch (IOException e) {
                log.debug("Uploaded file was not a PEM.. tryin to parse it as a DER encoded request.");
            }
            // See if it as a PKCS10
            try {
                new PKCS10CertificationRequest(buf);
            } catch (Exception e) {
                context.addMessage(null /*actionEvent.getComponent().getClientId(context)*/, new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, getMessage("enroll.csrcert.uploadfailednotpkcs10"), null));
                log.debug("Rejected uploaded file since it's not a valid PKCS#10 request.");
                return;
            }
            // Convert it back to a PEM
            String pem = PEM_CSR_BEGIN + "\n" + new String(Base64.encode(buf)) + "\n" + PEM_CSR_END;
            certificateRequest = pem;
            context.addMessage(null /*actionEvent.getComponent().getClientId(context)*/,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("enroll.csrcert.uploadok"), null));
        } else {
            context.addMessage(null /*actionEvent.getComponent().getClientId(context)*/, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, getMessage("enroll.csrcert.uploadfailedtoolarge"), null));
        }
    } else {
        log.debug("File upload failed: " + inputFile.getFileInfo().getException().getMessage());
        context.addMessage(null /*actionEvent.getComponent().getClientId(context)*/,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.csrcert.uploadfailed"), null));
    }
}

From source file:org.ejbca.externalra.gui.EnrollInterfaceBean.java

License:Open Source License

/**
 * Action that requests a certificate from EJBCA using the given credentials and the Certificate Signing Request.
 *///from   ww  w  .j ava2s. c  om
public void createCertFromCSR() {
    log.info("Recieved a certificate signing request for username '" + username + "' from "
            + getRemoteAddress());
    if (log.isDebugEnabled()) {
        log.debug("certificateRequest: " + certificateRequest);
    }
    FacesContext context = FacesContext.getCurrentInstance();
    if (username == null || username.length() == 0 || password == null || password.length() == 0
            || certificateRequest == null || certificateRequest.length() == 0) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.incompletefields"), null));
        return;
    }
    // Verify that we got a valid Certificate Signing Request
    try {
        // Clean it up if windows has messed it up..
        byte[] buf = (PEM_CSR_BEGIN + certificateRequest.replaceFirst(PEM_CSR_BEGIN, "")
                .replaceFirst(PEM_CSR_END, "").replaceAll(" ", "").replaceAll("\r", "") + PEM_CSR_END)
                        .getBytes();
        // See if it is a PEM
        buf = FileTools.getBytesFromPEM(buf, PEM_CSR_BEGIN, PEM_CSR_END);
        certificateRequest = PEM_CSR_BEGIN + "\n" + new String(Base64.encode(buf)) + "\n" + PEM_CSR_END;
        if (log.isDebugEnabled()) {
            log.debug("cleaned req: " + certificateRequest);
        }
        new PKCS10CertificationRequest(buf);
    } catch (Exception e) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
        return;
    }
    // Determine what kind of response the user has requested
    int responseType = CertificateRequestRequest.RESPONSE_TYPE_ENCODED;
    if ("pkcs7".equals(requestedResponseType)) {
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
    }
    // Request the certificate from the CA
    ResponseData csrResponse = getRequestDispatcher().getCertificateSigningRequestResponse(username, password,
            certificateRequest, responseType);
    // Check if got a valid result
    if (csrResponse == null) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.noresponse"), null));
        log.error("Certificate request for '" + username + "' failed. No response from CA.");
        return;
    } else if (csrResponse.getErrorMessage() != null) {
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                getMessage("enroll.csrcert.couldnotcreate"), null));
        log.info("Certificate request for '" + username + "' failed. " + csrResponse.getErrorMessage());
        return;
    }
    // Handle response
    switch (csrResponse.getResponseType()) {
    case CertificateRequestRequest.RESPONSE_TYPE_ENCODED:
        if ("pem".equals(requestedResponseType)) {
            Certificate[] certs = new Certificate[1];
            try {
                certs[0] = CertTools.getCertfromByteArray(csrResponse.getResponseData());
                resource = new ByteArrayResource(
                        CertTools.getPEMFromCerts(CertTools.getCertCollectionFromArray(certs, "BC")));
                filename = username + ".pem";
                mimeType = "application/x-pem-file";
            } catch (Exception e) {
                log.error("", e);
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        getMessage("enroll.invalidresponse"), null));
            }
        } else {
            resource = new ByteArrayResource(csrResponse.getResponseData());
            filename = username + ".der";
            mimeType = "application/pkix-cert";
        }
        break;
    case CertificateRequestRequest.RESPONSE_TYPE_PKCS7:
        resource = new ByteArrayResource(csrResponse.getResponseData());
        filename = username + ".p7b";
        mimeType = "application/x-pkcs7-certificates";
        break;
    default:
        filename = username + ".unknown";
        mimeType = "application/octet-stream";
        break;
    }
    log.info("Certificate request with response-type " + csrResponse.getResponseType() + " for '" + username
            + "' was successful.");
}

From source file:org.ejbca.externalra.gui.EnrollInterfaceBean.java

License:Open Source License

/**
 * Action that requests a certificate from EJBCA using the given credentials and the Certificate Signing Request created by the browser.
 *///from ww  w . ja va  2  s  .  com
public void createCertFromBrowser() {
    log.info("Recieved a browser generated certificate request of type " + certificateRequestType
            + " for username '" + username + "' from " + getRemoteAddress());
    if (log.isDebugEnabled()) {
        log.debug("certificateRequest: " + certificateRequest);
    }
    FacesContext context = FacesContext.getCurrentInstance();
    if (username == null || username.length() == 0 || password == null || password.length() == 0
            || certificateRequest == null || certificateRequest.length() == 0 || certificateRequestType == null
            || certificateRequestType.length() == 0) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.incompletefields"), null));
        return;
    }
    // Verify that we got a valid certificate request and determine response type
    byte[] buf = null;
    int requestType = Integer.parseInt(certificateRequestType);
    int responseType;
    switch (requestType) {
    case CertificateRequestRequest.REQUEST_TYPE_CRMF:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        buf = Base64.decode(certificateRequest.getBytes());
        ASN1InputStream asn1InputStream = new ASN1InputStream(buf);
        try {
            // Verify that we can parse this as a CRMF object
            CertReqMessages.getInstance(asn1InputStream.readObject()).getCertReqMsg(0);
        } catch (IOException e) {
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            log.error("", e);
        }
        break;
    case CertificateRequestRequest.REQUEST_TYPE_PKCS10:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        try {
            if (!isWindowsNT5()) {
                responseType = CertificateRequestRequest.RESPONSE_TYPE_UNSIGNEDPKCS7;
            }
            // Replace Vista PEM markers
            certificateRequest = certificateRequest.replaceAll(PEM_CSR_BEGIN_VISTA, PEM_CSR_BEGIN);
            certificateRequest = certificateRequest.replaceAll(PEM_CSR_END_VISTA, PEM_CSR_END);
            if (certificateRequest.indexOf(PEM_CSR_BEGIN) == -1) {
                certificateRequest = PEM_CSR_BEGIN + "\n" + certificateRequest + "\n" + PEM_CSR_END;
            }
            buf = FileTools.getBytesFromPEM(certificateRequest.getBytes(), PEM_CSR_BEGIN, PEM_CSR_END);
            new PKCS10CertificationRequest(buf);
        } catch (Exception e) {
            log.error("", e);
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            return;
        }
        break;
    case CertificateRequestRequest.REQUEST_TYPE_KEYGEN:
        responseType = CertificateRequestRequest.RESPONSE_TYPE_PKCS7;
        try {
            buf = Base64.decode(certificateRequest.getBytes());
            ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buf));
            ASN1Sequence spkac = (ASN1Sequence) in.readObject();
            in.close();
            NetscapeCertRequest nscr = new NetscapeCertRequest(spkac);
            // Verify POPO, we don't care about the challenge, it's not important.
            nscr.setChallenge("challenge");
            if (nscr.verify("challenge") == false) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        getMessage("enroll.invalidreqdata"), null));
                return;
            }
        } catch (Exception e) {
            log.error("", e);
            context.addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.invalidreqdata"), null));
            return;
        }
        break;
    case -1:
        // This is a workaround to hide errors when we use the KeyGenServlet..
        return;
    default:
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.unknownrequesttype"), null));
        return;
    }
    // Request the certificate from the CA
    if (log.isDebugEnabled()) {
        log.debug("Got requestType " + requestType + " and is expecting responseType " + responseType
                + " for user " + username);
    }
    ResponseData responseData = getRequestDispatcher().getCertificateResponse(username, password, requestType,
            buf, responseType);
    // Check if got a valid result
    if (responseData == null) {
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.noresponse"), null));
        log.error("Certificate request for '" + username + "' failed. No response from CA.");
        return;
    } else if (responseData.getErrorMessage() != null) {
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                getMessage("enroll.browsercert.couldnotcreate"), null));
        log.info("Certificate request for '" + username + "' failed. " + responseData.getErrorMessage());
        return;
    }
    // Handle response
    certificateResponseType = "" + responseData.getResponseType();
    switch (responseData.getResponseType()) {
    case CertificateRequestRequest.RESPONSE_TYPE_PKCS7:
        if (isInternetExplorer()) {
            // Working for XP+IE7
            certificateResponse = new String(Base64.encode(responseData.getResponseData(), false));
        } else {
            resource = new ByteArrayResource(responseData.getResponseData());
            mimeType = "application/x-x509-user-cert";
        }
        break;
    case CertificateRequestRequest.RESPONSE_TYPE_UNSIGNEDPKCS7:
        // Working for Vista+IE8
        certificateResponse = new String(Base64.encode(responseData.getResponseData(), false));
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            String pkcs7 = PEM_PKCS7_BEGIN + "\n"
                    + new String(Base64.encode(responseData.getResponseData(), true)) + "\n" + PEM_PKCS7_END
                    + "\n";
            log.debug("pkcs7=" + pkcs7);
            CertPath certPath = cf.generateCertPath(new ByteArrayInputStream(responseData.getResponseData()),
                    "PKCS7");
            List<? extends Certificate> certList = certPath.getCertificates();
            Certificate caCert = certList.get(certList.size() - 1);
            String caCertificate = new String(Base64.encode(caCert.getEncoded(), false));
            resource = new ByteArrayResource(caCertificate.getBytes());
            mimeType = "application/x-x509-ca-cert";
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        if (log.isDebugEnabled()) {
            log.debug("certificateResponse: " + certificateResponse);
        }
        break;
    default:
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("enroll.unknownresponsetype"), null));
        log.error("Unknown result type: " + certificateResponseType);
        break;
    }
    log.info("Certificate request with response-type " + responseData.getResponseType() + " for '" + username
            + "' was successful.");
}