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

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

Introduction

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

Prototype

public X509Certificate getCertificate(X509CertificateHolder certHolder) throws CertificateException 

Source Link

Document

Use the configured converter to produce a X509Certificate object from a X509CertificateHolder object.

Usage

From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*  w  w w  . j  a  v  a  2  s . c om*/
    String requestPolicy = signatureConfig.getTspRequestPolicy();
    if (requestPolicy != null) {
        requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
    }
    ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
    TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP POST request
    Proxy proxy = Proxy.NO_PROXY;
    if (signatureConfig.getProxyUrl() != null) {
        URL proxyUrl = new URL(signatureConfig.getProxyUrl());
        String host = proxyUrl.getHost();
        int port = proxyUrl.getPort();
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port)));
    }

    HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);

    if (signatureConfig.getTspUser() != null) {
        String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
        String encoding = DatatypeConverter
                .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
        huc.setRequestProperty("Authorization", "Basic " + encoding);
    }

    huc.setRequestMethod("POST");
    huc.setConnectTimeout(20000);
    huc.setReadTimeout(20000);
    huc.setDoOutput(true); // also sets method to POST.
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request"
            : "application/timestamp-query"); // "; charset=ISO-8859-1");

    OutputStream hucOut = huc.getOutputStream();
    hucOut.write(encodedRequest);

    // invoke TSP service
    huc.connect();

    int statusCode = huc.getResponseCode();
    if (statusCode != 200) {
        LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl());
    }

    // HTTP input validation
    String contentType = huc.getHeaderField("Content-Type");
    if (null == contentType) {
        throw new RuntimeException("missing Content-Type header");
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(huc.getInputStream(), bos);
    LOG.log(POILogger.DEBUG, "response content: ", bos.toString());

    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response"
            : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }

    if (bos.size() == 0) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
        LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
            if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) {
                LOG.log(POILogger.DEBUG, "unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Name signerCertIssuer = signerId.getIssuer();
    LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
    LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);

    X509CertificateHolder signerCert = null;
    Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
    for (X509CertificateHolder certificate : certificates) {
        if (signerCertIssuer.equals(certificate.getIssuer())
                && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
            signerCert = certificate;
        }
        certificateMap.put(certificate.getSubject(), certificate);
    }

    // TSP signer cert path building
    if (signerCert == null) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
    JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
    x509converter.setProvider("BC");
    X509CertificateHolder certificate = signerCert;
    do {
        LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
        tspCertificateChain.add(x509converter.getCertificate(certificate));
        if (certificate.getSubject().equals(certificate.getIssuer())) {
            break;
        }
        certificate = certificateMap.get(certificate.getIssuer());
    } while (null != certificate);

    // verify TSP signer signature
    X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
    DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
    DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
    BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder,
            hashAlgoFinder, calculator);
    SignerInformationVerifier verifier = verifierBuilder.build(holder);

    timeStampToken.validate(verifier);

    // verify TSP signer certificate
    if (signatureConfig.getTspValidator() != null) {
        signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
    }

    LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Converts a X509CertificateHolder chain into a X509Certificate chain.
 * //  ww  w.j a va2s .  c  o m
 * @param certificateHolderChain input chain to be converted
 * @return the result
 * @throws CertificateException if there is a problem extracting the certificate information.
 */
public static final List<X509Certificate> convertToX509CertificateList(
        Collection<X509CertificateHolder> certificateHolderChain) throws CertificateException {
    final List<X509Certificate> ret = new ArrayList<X509Certificate>();
    final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
    for (final X509CertificateHolder certificateHolder : certificateHolderChain) {
        ret.add(jcaX509CertificateConverter.getCertificate(certificateHolder));
    }
    return ret;
}

From source file:org.codice.ddf.security.certificate.generator.CertificateAuthority.java

License:Open Source License

public KeyStore.PrivateKeyEntry sign(CertificateSigningRequest csr) {
    //Converters, holders, and builders! Oh my!
    JcaX509v3CertificateBuilder builder = csr.newCertificateBuilder(getCertificate());
    X509CertificateHolder holder = builder.build(getContentSigner());
    JcaX509CertificateConverter converter = newCertConverter();
    X509Certificate signedCert;//from w  w  w  . j ava 2 s .c  o m
    try {
        signedCert = converter.getCertificate(holder);
    } catch (CertificateException e) {
        throw new CertificateGeneratorException("Could not create signed certificate.", e.getCause());
    }

    X509Certificate[] chain = new X509Certificate[2];
    chain[0] = signedCert;
    chain[1] = getCertificate();

    return new KeyStore.PrivateKeyEntry(csr.getSubjectPrivateKey(), chain);
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * The message to decode a certification response
 *
 * @param message//from  w w  w. ja v a  2  s. c o  m
 * @return response message
 * @throws IOException
 * @throws PKICMPMessageException
 */
PKICMPResponse processResponse(byte[] message) throws IOException, PKICMPMessageException, CertificateException,
        OperatorCreationException, CMPException, PKIKeyStoreException, ParseException {
    CertificationResult certificationResult = new CertificationResult();

    ProtectedPKIMessage pkiMessage = new ProtectedPKIMessage(new GeneralPKIMessage(message));

    /* Verify Signature */
    ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder()
            .setProvider(pkiKeyStore.getProvider()).build(pkiKeyStore.getRecipientCertificate());

    if (!pkiMessage.verify(verifierProvider)) {
        throw new PKICMPMessageException("E: Verification failed this is an untrusted Message ["
                + pkiMessage.getHeader().getSender() + "]");
    }

    if (!Arrays.equals(senderNonce, pkiMessage.getHeader().getRecipNonce().getOctets()))
        throw new PKICMPMessageException(
                "E: Recipient Nonce in response does not correspond with Sender Nonce in request!");
    if (pkiMessage.getHeader().getMessageTime() != null) {
        pkiKeyStore.verifyCertificate(pkiKeyStore.getRecipientCertificate(),
                pkiMessage.getHeader().getMessageTime().getDate());
    } else {
        pkiKeyStore.verifyCertificate(pkiKeyStore.getRecipientCertificate(), new Date());
    }
    PKICMPResponse pkicmpResponse = new PKICMPResponse();

    pkicmpResponse.setPkiBody(pkiMessage.getBody());
    pkicmpResponse.setPkiHeader(pkiMessage.getHeader());

    X509CertificateHolder[] x509CertificateHolders = pkiMessage.getCertificates();
    JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
    for (X509CertificateHolder x509CertificateHolder : x509CertificateHolders) {
        pkicmpResponse.getX509CertifificateList()
                .add(jcaX509CertificateConverter.getCertificate(x509CertificateHolder));

    }
    return pkicmpResponse;
}

From source file:org.eclipse.andmore.android.certmanager.core.KeyStoreUtils.java

License:Apache License

/**
 * Create a new X509 certificate for a given KeyPair
 * //w  w  w .  jav  a 2s  .c om
 * @param keyPair
 *            the {@link KeyPair} used to create the certificate,
 *            RSAPublicKey and RSAPrivateKey are mandatory on keyPair,
 *            IllegalArgumentExeption will be thrown otherwise.
 * @param issuerName
 *            The issuer name to be used on the certificate
 * @param ownerName
 *            The owner name to be used on the certificate
 * @param expireDate
 *            The expire date
 * @return The {@link X509Certificate}
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 */
public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails)
        throws IOException, OperatorCreationException, CertificateException {

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) {
        throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected);
    }

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;

    // Transform the PublicKey into the BouncyCastle expected format
    ASN1InputStream asn1InputStream = null;
    X509Certificate x509Certificate = null;

    try {
        asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded()));
        SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());

        X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle());
        addField(BCStyle.C, certDetails.getCountry(), nameBuilder);
        addField(BCStyle.ST, certDetails.getState(), nameBuilder);
        addField(BCStyle.L, certDetails.getLocality(), nameBuilder);
        addField(BCStyle.O, certDetails.getOrganization(), nameBuilder);
        addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder);
        addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder);

        X500Name subjectName = nameBuilder.build();
        X500Name issuerName = subjectName;
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,
                BigInteger.valueOf(new SecureRandom().nextInt()), Calendar.getInstance().getTime(),
                certDetails.getExpirationDate(), subjectName, pubKey);

        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);

        // Create RSAKeyParameters, the private key format expected by
        // Bouncy Castle
        RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(),
                rsaPrivateKey.getModulus());

        ContentSigner contentSigner = sigGen.build(keyParams);
        X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);

        // Convert the X509Certificate from BouncyCastle format to the
        // java.security format
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        x509Certificate = certConverter.getCertificate(certificateHolder);
    } finally {
        if (asn1InputStream != null) {
            try {
                asn1InputStream.close();
            } catch (IOException e) {
                AndmoreLogger
                        .error("Could not close stream while creating X509 certificate. " + e.getMessage());
            }
        }
    }

    return x509Certificate;
}

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.  java  2  s .c om
        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 {/*from w  w  w.  j  a  v  a2  s. c  om*/
        // 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  .  c  o 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  w  w. jav  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 av  a  2 s . c o m*/
 */
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;
}