Example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter.

Prototype

public JcaX509CertificateConverter() 

Source Link

Document

Base constructor, configure with the default provider.

Usage

From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java

License:Open Source License

@SuppressWarnings("unchecked")
private static CMSValidationResult validateCMS(final CMSSignedData signedData,
        final Collection<Certificate> trustedCerts) {

    final CMSValidationResult result = new CMSValidationResult();

    try {// w w w.  ja  v a2  s  .co m
        final ContentInfo ci = signedData.toASN1Structure();
        if (LOG.isDebugEnabled()) {
            LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: "
                    + signedData.getSignedContent());
        }

        final Object content = signedData.getSignedContent().getContent();

        if (content instanceof byte[]) {
            result.setContent((byte[]) content);
        }

        Store certs = signedData.getCertificates();
        SignerInformationStore signers = signedData.getSignerInfos();
        for (Object o : signers.getSigners()) {
            if (o instanceof SignerInformation) {
                SignerInformation si = (SignerInformation) o;

                if (LOG.isDebugEnabled()) {
                    LOG.debug("*** SIGNATURE: " + "\n" + si.getSID());
                }

                final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs
                        .getMatches(si.getSID());

                if (LOG.isDebugEnabled()) {
                    LOG.debug("signerCerts: " + signerCerts);
                }
                JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
                for (X509CertificateHolder signerCert : signerCerts) {
                    final X509Certificate signerX509Cert = jcaX509CertificateConverter
                            .getCertificate(signerCert);

                    // Verify the signature
                    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    boolean consistent = si
                            .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey()));
                    if (consistent) {

                        if (LOG.isDebugEnabled()) {
                            LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from "
                                    + signerX509Cert.getSubjectDN() + " issued by "
                                    + signerX509Cert.getIssuerDN());
                        }

                        result.setValidSignature(consistent);

                        try {
                            final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs,
                                    trustedCerts);

                            result.setValidChain(true);
                            result.setSignerChain(signerChain);

                            JOptionPane.showMessageDialog(null,
                                    "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"",
                                    "Signature check", JOptionPane.INFORMATION_MESSAGE);

                        } catch (CertPathBuilderException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(),
                                    "Signature check", JOptionPane.ERROR_MESSAGE);
                        } catch (CertPathValidatorException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null,
                                    "Error: Certificate validation:\n" + ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (InvalidAlgorithmParameterException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (NoSuchAlgorithmException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (GeneralSecurityException e) {
                            //Crappy catch-all, but not much to do due to underlying BC-code
                            result.setError(e.getMessage());
                            JOptionPane.showMessageDialog(null, e.getMessage(),
                                    "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        result.setError("Inconsistent signature!");
                        JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        }

    } catch (CMSException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (OperatorCreationException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (CertificateException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    }
    return result;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

License:Open Source License

private OCSPUnidResponse sendOCSPRequest(byte[] ocspPackage, X509Certificate knownTrustAnchor, boolean useGet)
        throws IOException, OCSPException, OperatorCreationException, CertificateException,
        UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final HttpURLConnection con;
    if (useGet) {
        String b64 = new String(Base64.encode(ocspPackage, false));
        URL url = new URL(httpReqPath + '/' + b64);
        con = (HttpURLConnection) url.openConnection();
    } else {/*w w w.  jav  a  2  s  .  c o m*/
        // POST the OCSP request
        URL url = new URL(httpReqPath);
        con = (HttpURLConnection) getUrlConnection(url);
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = null;
        try {
            os = con.getOutputStream();
            os.write(ocspPackage);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
    final OCSPUnidResponse ret = new OCSPUnidResponse();
    ret.setHttpReturnCode(con.getResponseCode());
    if (ret.getHttpReturnCode() != 200) {
        if (ret.getHttpReturnCode() == 401) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNAUTHORIZED);
        } else {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNKNOWN);
        }
        return ret;
    }
    final OCSPResp response;
    {
        final InputStream in = con.getInputStream();
        if (in != null) {
            try {
                response = new OCSPResp(IOUtils.toByteArray(in));
            } finally {
                in.close();
            }
        } else {
            response = null;
        }
    }
    if (response == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    ret.setResp(response);
    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    if (brep == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    // Compare nonces to see if the server sent the same nonce as we sent
    final byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
            .getEncoded();
    if (noncerep != null) {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        boolean eq = ArrayUtils.isEquals(this.nonce, oct.getOctets());
        if (!eq) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_NONCE);
            return ret;
        }
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Primitive();
    final RespID respId;
    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate = converter.getCertificate(chain[0]);
    final PublicKey signerPub = signerCertificate.getPublicKey();
    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        respId = new JcaRespID(signerPub, SHA1DigestCalculator.buildSha1Instance());
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERID);
    }
    if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerPub))) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNATURE);
        return ret;
    }

    /* 
     * Okay, at this point we have three different variables and six different possible valid use cases. These
     * variables are:
     *          1. If the OCSP reply is from a CA (integrated) or an OCSP responder (standalone) 
     *          2. If it was from a CA, then if that CA is self signed or a subCA
     *          3. If the server (in the integrated case) or keybinding (standalone case) was set to include the certificate chain
     */

    //If we have a chain, verify it
    if (chain.length > 1) {
        // end at one shortof chain.length, because the root certificate is (usually) not included in the OCSP response
        // TODO: improve this when we can pass in the root cert from parameter to properly validate the whole chain
        for (int i = 0; i + 1 < chain.length; i++) {
            final X509Certificate cert1 = converter.getCertificate(chain[i]);
            final X509Certificate cert2 = converter.getCertificate(chain[Math.min(i + 1, chain.length - 1)]);
            try {
                cert1.verify(cert2.getPublicKey());
            } catch (GeneralSecurityException e) {
                m_log.info("Verifying problem with", e);
                m_log.info("Certificate to be verified: " + cert1);
                m_log.info("Verifying certificate: " + cert2);
                ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
                return ret;
            }
        }
    }

    if (CertTools.isCA(signerCertificate)) {
        //Verify that the signer certificate was the same as the trust anchor
        if (!signerCertificate.getSerialNumber().equals(knownTrustAnchor.getSerialNumber())) {
            m_log.info("Signing certificate for integrated OCSP was not the provided trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else if (CertTools.isOCSPCert(signerCertificate)) {
        //If an OCSP certificate was used to sign
        try {
            signerCertificate.verify(knownTrustAnchor.getPublicKey());
        } catch (GeneralSecurityException e) {
            m_log.info("Signing certificate was not signed by known trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else {
        m_log.info("Signing certificate was not an OCSP certificate.");
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
        return ret;
    }

    String fnr = getFnr(brep);
    if (fnr != null) {
        ret.setFnr(fnr);
    }
    return ret;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

/** Checks the signature on an OCSP request and checks that it is signed by an allowed CA.
 * Does not check for revocation of the signer certificate
 * //from   w  ww .j a  v  a 2 s  .co  m
 * @param clientRemoteAddr The ip address or hostname of the remote client that sent the request, can be null.
 * @param req The signed OCSPReq
 * @param cacerts a CertificateCache of Certificates, the authorized CA-certificates. The signer certificate must be issued by one of these.
 * @return X509Certificate which is the certificate that signed the OCSP request
 * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized
 * @throws SignRequestException if there is no signature on the OCSPReq
 * @throws OCSPException if the request can not be parsed to retrieve certificates
 * @throws NoSuchProviderException if the BC provider is not installed
 * @throws CertificateException if the certificate can not be parsed
 * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm
 * @throws InvalidKeyException if the certificate, or CA key is invalid
 * @throws OperatorCreationException 
 */
public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req,
        CaCertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException,
        CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException,
        OperatorCreationException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    X509CertificateHolder[] certs = req.getCerts();
    // Set, as a try, the signer to be the first certificate, so we have a name to log...
    String signer = null;
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    if (certs.length > 0) {
        signer = CertTools.getSubjectDN(converter.getCertificate(certs[0]));
    }

    // We must find a cert to verify the signature with...
    boolean verifyOK = false;
    for (int i = 0; i < certs.length; i++) {
        if (req.isSignatureValid(new JcaContentVerifierProviderBuilder().build(certs[i])) == true) {
            signercert = converter.getCertificate(certs[i]);
            signer = CertTools.getSubjectDN(signercert);
            Date now = new Date();
            String signerissuer = CertTools.getIssuerDN(signercert);
            String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer);
            log.info(infoMsg);
            verifyOK = true;
            // Also check that the signer certificate can be verified by one of the CA-certificates
            // that we answer for
            X509Certificate signerca = cacerts.findLatestBySubjectDN(HashID.getFromIssuerDN(certs[i]));
            String subject = signer;
            String issuer = signerissuer;
            if (signerca != null) {
                try {
                    signercert.verify(signerca.getPublicKey());
                    if (log.isDebugEnabled()) {
                        log.debug("Checking validity. Now: " + now + ", signerNotAfter: "
                                + signercert.getNotAfter());
                    }
                    CertTools.checkValidity(signercert, now);
                    // Move the error message string to the CA cert
                    subject = CertTools.getSubjectDN(signerca);
                    issuer = CertTools.getIssuerDN(signerca);
                    CertTools.checkValidity(signerca, now);
                } catch (SignatureException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (InvalidKeyException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateNotYetValidException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                            e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateExpiredException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                            e.getMessage());
                    log.info(infoMsg);
                    verifyOK = false;
                }
            } else {
                infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                log.info(infoMsg);
                verifyOK = false;
            }
            break;
        }
    }
    if (!verifyOK) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
        log.info(errMsg);
        throw new SignRequestSignatureException(errMsg);
    }

    return signercert;
}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

License:Open Source License

private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId,
        boolean crlRep, String digestOid, boolean noca)
        throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException,
        InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException {

    // Parse response message
    ////from  w ww .  j a v a2s . c o  m
    CMSSignedData s = new CMSSignedData(retMsg);
    // The signer, i.e. the CA, check it's the right CA
    SignerInformationStore signers = s.getSignerInfos();
    @SuppressWarnings("unchecked")
    Collection<SignerInformation> col = signers.getSigners();
    assertTrue(col.size() > 0);
    Iterator<SignerInformation> iter = col.iterator();
    SignerInformation signerInfo = iter.next();
    // Check that the message is signed with the correct digest alg
    assertEquals(signerInfo.getDigestAlgOID(), digestOid);
    SignerId sinfo = signerInfo.getSID();
    // Check that the signer is the expected CA
    assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()),
            CertTools.stringToBCDNString(sinfo.getIssuer().toString()));
    // Verify the signature
    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey()));
    assertTrue(ret);
    // Get authenticated attributes
    AttributeTable tab = signerInfo.getSignedAttributes();
    // --Fail info
    Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo));
    // No failInfo on this success message
    assertNull(attr);
    // --Message type
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType));
    assertNotNull(attr);
    ASN1Set values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String messageType = str.getString();
    assertEquals("3", messageType);
    // --Success status
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString());
    // --SenderNonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    assertTrue(octstr.getOctets().length == 16);
    // --Recipient Nonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // recipient nonce should be the same as we sent away as sender nonce
    assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets())));
    // --Transaction ID
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    // transid should be the same as the one we sent
    assertEquals(_transId, str.getString());

    //
    // Check different message types
    //
    if (messageType.equals("3")) {
        // First we extract the encrypted data from the CMS enveloped data
        // contained
        // within the CMS signed data
        final CMSProcessable sp = s.getSignedContent();
        final byte[] content = (byte[]) sp.getContent();
        final CMSEnvelopedData ed = new CMSEnvelopedData(content);
        final RecipientInformationStore recipients = ed.getRecipientInfos();
        Store certstore;

        @SuppressWarnings("unchecked")
        Collection<RecipientInformation> c = recipients.getRecipients();
        assertEquals(c.size(), 1);
        Iterator<RecipientInformation> riIterator = c.iterator();
        byte[] decBytes = null;
        RecipientInformation recipient = riIterator.next();
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate());
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
        decBytes = recipient.getContent(rec);
        // This is yet another CMS signed data
        CMSSignedData sd = new CMSSignedData(decBytes);
        // Get certificates from the signed data
        certstore = sd.getCertificates();

        if (crlRep) {
            // We got a reply with a requested CRL
            @SuppressWarnings("unchecked")
            final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null);
            assertEquals(crls.size(), 1);
            final Iterator<X509CRLHolder> it = crls.iterator();
            // CRL is first (and only)
            final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next());
            log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName());

            // check the returned CRL
            assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl));
            retCrl.verify(cacert.getPublicKey());
        } else {
            // We got a reply with a requested certificate
            @SuppressWarnings("unchecked")
            final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore
                    .getMatches(null);
            // EJBCA returns the issued cert and the CA cert (cisco vpn
            // client requires that the ca cert is included)
            if (noca) {
                assertEquals(certs.size(), 1);
            } else {
                assertEquals(certs.size(), 2);
            }
            final Iterator<X509CertificateHolder> it = certs.iterator();
            // Issued certificate must be first
            boolean verified = false;
            boolean gotcacert = false;
            JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
            while (it.hasNext()) {
                X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next());
                log.info("Got cert with DN: " + retcert.getSubjectDN().getName());

                // check the returned certificate
                String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
                if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) {
                    // issued certificate
                    assertEquals(CertTools.stringToBCDNString(userDN), subjectdn);
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert));
                    retcert.verify(cacert.getPublicKey());
                    assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey()));
                    verified = true;
                } else {
                    // ca certificate
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert));
                    gotcacert = true;
                }
            }
            assertTrue(verified);
            if (noca) {
                assertFalse(gotcacert);
            } else {
                assertTrue(gotcacert);
            }
        }
    }

}

From source file:org.ejbca.ui.web.pub.AutoEnrollServletTest.java

License:Open Source License

/**
 * Post Certificate request to Servlet //from   w  w  w.  j  a v a  2s  . c om
 */
private X509Certificate doRequest(String remoteUser, String requestData) throws Exception {
    final String remoteHost = SystemTestsConfiguration.getRemoteHost("127.0.0.1");
    final String remotePort = SystemTestsConfiguration.getRemotePortHttp("8080");
    URL localAutoEnrollServletURL = new URL("http://" + remoteHost + ":" + remotePort + "/ejbca/autoenroll");
    HttpURLConnection localServletConnection = (HttpURLConnection) localAutoEnrollServletURL.openConnection();
    localServletConnection.setRequestProperty("X-Remote-User", remoteUser);
    localServletConnection.setRequestMethod("POST");
    localServletConnection.setDoOutput(true);
    localServletConnection.connect();
    OutputStream os = localServletConnection.getOutputStream();
    os.write(("request=" + requestData + "&").getBytes());
    os.write("debug=false&".getBytes());
    //os.write(("CertificateTemplate=" + certificateTemplate).getBytes());
    os.flush();
    os.close();
    InputStream is = localServletConnection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String response = "";
    while (br.ready()) {
        response += br.readLine();
    }
    assertFalse("AutoEnrollment has to be enabled for this test to work.", response.contains("Not allowed."));
    response = response.replaceFirst("-----BEGIN PKCS7-----", "").replaceFirst("-----END PKCS7-----", "");
    byte[] responseData = Base64.decode(response.getBytes());
    X509Certificate returnCertificate = null;
    CMSSignedData p7b = new CMSSignedData(responseData);
    Store certStore = p7b.getCertificates();
    SignerInformationStore signers = p7b.getSignerInfos();
    @SuppressWarnings("unchecked")
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
    while (iter.hasNext()) {
        SignerInformation signer = iter.next();
        @SuppressWarnings("unchecked")
        List<X509CertificateHolder> certCollection = (List<X509CertificateHolder>) certStore
                .getMatches(signer.getSID());
        X509Certificate caCert = new JcaX509CertificateConverter().getCertificate(certCollection.get(0));
        @SuppressWarnings("unchecked")
        Iterator<X509CertificateHolder> iter2 = certStore.getMatches(null).iterator();
        if (iter2.hasNext()) {
            X509Certificate cert = jcaX509CertificateConverter.getCertificate(iter2.next());
            if (!CertTools.getSubjectDN(caCert).equals(CertTools.getSubjectDN(cert))) {
                returnCertificate = cert;
            }
        }
    }
    assertNotNull("No requested certificate present in response.", returnCertificate);
    return returnCertificate;
}

From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java

License:Open Source License

/**
 * Generates a signed certificate/*  ww  w.  j  av a  2s . co  m*/
 *
 * @param principal          the principal of the certificate; commonly referred to as the
 *                           distinguished name (DN)
 * @param subjectAltNames    the subject alternative names that should be added to the
 *                           certificate as an X509v3 extension. May be {@code null}
 * @param keyPair            the key pair that will be associated with the certificate
 * @param caCert             the CA certificate. If {@code null}, this results in a self signed
 *                           certificate
 * @param caPrivKey          the CA private key. If {@code null}, this results in a self signed
 *                           certificate
 * @param isCa               whether or not the generated certificate is a CA
 * @param days               no of days certificate will be valid from now
 * @param signatureAlgorithm algorithm used for signing certificate. If {@code null} or
 *                           empty, then use default algorithm {@link CertGenUtils#getDefaultSignatureAlgorithm(PrivateKey)}
 * @return a signed {@link X509Certificate}
 */
private static X509Certificate generateSignedCertificate(X500Principal principal, GeneralNames subjectAltNames,
        KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivKey, boolean isCa, int days,
        String signatureAlgorithm)
        throws NoSuchAlgorithmException, CertificateException, CertIOException, OperatorCreationException {
    Objects.requireNonNull(keyPair, "Key-Pair must not be null");
    final DateTime notBefore = new DateTime(DateTimeZone.UTC);
    if (days < 1) {
        throw new IllegalArgumentException("the certificate must be valid for at least one day");
    }
    final DateTime notAfter = notBefore.plusDays(days);
    final BigInteger serial = CertGenUtils.getSerial();
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    X500Name subject = X500Name.getInstance(principal.getEncoded());
    final X500Name issuer;
    final AuthorityKeyIdentifier authorityKeyIdentifier;
    if (caCert != null) {
        if (caCert.getBasicConstraints() < 0) {
            throw new IllegalArgumentException("ca certificate is not a CA!");
        }
        issuer = X500Name.getInstance(caCert.getIssuerX500Principal().getEncoded());
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey());
    } else {
        issuer = subject;
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(keyPair.getPublic());
    }

    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial,
            new Time(notBefore.toDate(), Locale.ROOT), new Time(notAfter.toDate(), Locale.ROOT), subject,
            keyPair.getPublic());

    builder.addExtension(Extension.subjectKeyIdentifier, false,
            extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);
    if (subjectAltNames != null) {
        builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }
    builder.addExtension(Extension.basicConstraints, isCa, new BasicConstraints(isCa));

    PrivateKey signingKey = caPrivKey != null ? caPrivKey : keyPair.getPrivate();
    ContentSigner signer = new JcaContentSignerBuilder(
            (Strings.isNullOrEmpty(signatureAlgorithm)) ? getDefaultSignatureAlgorithm(signingKey)
                    : signatureAlgorithm).setProvider(CertGenUtils.BC_PROV).build(signingKey);
    X509CertificateHolder certificateHolder = builder.build(signer);
    return new JcaX509CertificateConverter().getCertificate(certificateHolder);
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

License:Open Source License

/**
 * Generates a self signed certificate using the given properties.
 *
 * @param commonName the subject's common name
 * @param organization the subject's organization name
 * @param organizationUnit the subject's organization unit name
 * @param stateOrProvince the subject's state or province
 * @param country the subject's country code
 * @param locality the subject's locality
 * @param algorithm the algorithm to use
 * @param keySize the keysize to use/*from w w  w .  j a  v a  2 s  . c  o  m*/
 * @param signatureAlgorithm the signature algorithm to use
 * @param validFrom when the certificate is valid from
 * @param validTo when the certificate is valid until
 * @return The generated certificate
 * @throws Exception
 */
protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization,
        String organizationUnit, String stateOrProvince, String country, String locality, String algorithm,
        int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC"
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, country);
    builder.addRDN(BCStyle.ST, stateOrProvince);
    builder.addRDN(BCStyle.L, locality);
    builder.addRDN(BCStyle.OU, organizationUnit);
    builder.addRDN(BCStyle.O, organization);
    builder.addRDN(BCStyle.CN, commonName);

    Date notBefore = null;
    Date notAfter = null;
    if (validFrom == null) {
        notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    } else {
        DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom);
        if (notBeforeDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validFrom' property");
        } else {
            notBefore = notBeforeDateTime.toDate();
        }
    }
    if (validTo == null) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, 10);
        notAfter = date.getTime();
    } else {
        DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo);
        if (notAfterDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validTo' property");
        } else {
            notAfter = notAfterDateTime.toDate();
        }
    }

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), keyPair.getPublic());

    ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC)
            .build(keyPair.getPrivate());

    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
            .getCertificate(v3CertGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());

    return Pair.of(cert, keyPair.getPrivate());
}

From source file:org.fuin.esmp.EventStoreCertificateMojo.java

License:Open Source License

private static X509Certificate signCertificate(final X509v3CertificateBuilder certificateBuilder,
        final PrivateKey privateKey) {
    try {//from   ww  w .  ja  v a2s .c  om
        final ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateBuilder.build(signer));
    } catch (final OperatorCreationException | CertificateException ex) {
        throw new RuntimeException("Couldn't sign certificate", ex);
    }
}

From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

License:MIT License

/**
 * If there is no certificate selected, or certificate is invalid -
 * generates one.//from  w w  w.j  a v a2s . c  om
 * 
 * @author Oleksiy Tataryn
 * @return certificate for generated SP
 * @throws CertificateEncodingException
 */
private String getCertForGeneratedSP() {
    X509Certificate cert = SSLService.instance().getCertificate(certWrapper.getStream());
    if (cert == null) {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();

            String url = trustRelationship.getUrl().replaceFirst(".*//", "");

            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"),
                    BigInteger.valueOf(new SecureRandom().nextInt()),
                    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
                    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(
                    new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_END_LINE);

            saveCert(trustRelationship, pemCertPre);
            saveKey(trustRelationship, keyWriter.toString());

        } catch (Exception e) {

            e.printStackTrace();
        }

        //         String certName = applicationConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(applicationConfiguration.getOrgInum())
        //               + "-shib.crt";
        //         File certFile = new File(certName);
        //         if (certFile.exists()) {
        //            cert = SSLService.instance().getCertificate(certName);
        //         }
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(Severity.ERROR,
                    "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }

    return certificate;
}

From source file:org.graylog.plugins.auth.tls.sso.CertificateTools.java

License:Open Source License

private static Map<String, String> convertCertificateInformation(X509CertificateHolder certificate)
        throws CertificateException {
    final X500NameStyle x500NameStyle = BCStyle.INSTANCE;
    final CertificateInfo<String, String> certInfo = new CertificateInfo<>();

    // Stores relative distinguished names of Subject
    X500Name subject = certificate.getSubject();
    for (RDN rdn : subject.getRDNs()) {
        if (rdn.getFirst() == null) {
            log.warn("Unable to get first RDN");
            continue;
        }//from  w  ww  .j ava 2 s .c o m
        AttributeTypeAndValue atav = rdn.getFirst();
        if (atav == null) {
            log.warn("Unable to get first AttributeTypeAndValue");
            continue;
        }
        String displayName = x500NameStyle.oidToDisplayName(atav.getType());
        ASN1Encodable value = atav.getValue();
        if (displayName != null && value != null) {
            certInfo.putLogString(displayName, value);
        }
    }

    certInfo.putLogString("CERT_SERIAL", certificate.getSerialNumber());
    certInfo.putLogString("ISSUER", certificate.getIssuer());

    // Convert to java.security.cert.X509Certificate
    X509Certificate jcert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificate);

    // Set subject alternate names
    // There may be several of the same type in the certificate. This implementation will overwrite in collisions!
    Collection<List<?>> sans = jcert.getSubjectAlternativeNames();
    if (sans != null)
        for (List<?> san : sans) {
            Object[] sanArray = san.toArray();
            switch ((Integer) sanArray[0]) {
            // These are known to be Strings
            case 1:
                if (sanArray[1] != null)
                    certInfo.putLogString("rfc822Name", sanArray[1]);
                break;
            case 2:
                if (sanArray[1] != null)
                    certInfo.putLogString("dNSName", sanArray[1]);
                break;
            case 4:
                if (sanArray[1] != null)
                    certInfo.putLogString("directoryName", sanArray[1]);
                break;
            case 6:
                if (sanArray[1] != null)
                    certInfo.putLogString("uniformResourceIdentifier", sanArray[1]);
                break;
            case 7:
                if (sanArray[1] != null)
                    certInfo.putLogString("iPAddress", sanArray[1]);
                break;
            case 8:
                if (sanArray[1] != null)
                    certInfo.putLogString("registeredID", sanArray[1]);
                break;
            }
        }

    // Populate key usages
    boolean[] keyUsages = jcert.getKeyUsage();
    if (keyUsages != null && keyUsages.length == 9) {
        if (keyUsages[0])
            certInfo.putLogString("Usage digitalSignature", "true");
        if (keyUsages[1])
            certInfo.putLogString("Usage nonRepudiation", "true");
        if (keyUsages[2])
            certInfo.putLogString("Usage keyEncipherment", "true");
        if (keyUsages[3])
            certInfo.putLogString("Usage dataEncipherment", "true");
        if (keyUsages[4])
            certInfo.putLogString("Usage keyAgreement", "true");
        if (keyUsages[5])
            certInfo.putLogString("Usage keyCertSign", "true");
        if (keyUsages[6])
            certInfo.putLogString("Usage cRLSign", "true");
        if (keyUsages[7])
            certInfo.putLogString("Usage encipherOnly", "true");
        if (keyUsages[8])
            certInfo.putLogString("Usage decipherOnly", "true");
    }

    // Populate extended usages
    List<String> extendedUsage = jcert.getExtendedKeyUsage();
    if (extendedUsage != null)
        for (String s : extendedUsage) {
            if (extendedUsageOids.containsKey(s)) {
                certInfo.putLogString("Usage " + extendedUsageOids.get(s), "true");
            } else {
                log.warn("Unknown extended usage OID: {}", s);
            }
        }

    return certInfo;
}