Example usage for java.security.cert X509Certificate verify

List of usage examples for java.security.cert X509Certificate verify

Introduction

In this page you can find the example usage for java.security.cert X509Certificate verify.

Prototype

public abstract void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException, SignatureException;

Source Link

Document

Verifies that this certificate was signed using the private key that corresponds to the specified public key.

Usage

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//from w w  w  . j  a va 2  s  . co  m
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.dspace.authenticate.X509Authentication.java

/**
 * Verify CERTIFICATE against KEY. Return true if and only if CERTIFICATE is
 * valid and can be verified against KEY.
 *
 * @param context/* ww w .  j  ava2 s .  c  o m*/
 *            The current DSpace context
 * @param certificate -
 *            An X509 certificate object
 * @return - True if CERTIFICATE is valid and can be verified against KEY,
 *         false otherwise.
 */
private static boolean isValid(Context context, X509Certificate certificate) {
    if (certificate == null) {
        return false;
    }

    // This checks that current time is within cert's validity window:
    try {
        certificate.checkValidity();
    } catch (CertificateException e) {
        log.info(LogManager.getHeader(context, "authentication",
                "X.509 Certificate is EXPIRED or PREMATURE: " + e.toString()));
        return false;
    }

    // Try CA public key, if available.
    if (caPublicKey != null) {
        try {
            certificate.verify(caPublicKey);
            return true;
        } catch (GeneralSecurityException e) {
            log.info(LogManager.getHeader(context, "authentication",
                    "X.509 Certificate FAILED SIGNATURE check: " + e.toString()));
        }
    }

    // Try it with keystore, if available.
    if (caCertKeyStore != null) {
        try {
            Enumeration ke = caCertKeyStore.aliases();

            while (ke.hasMoreElements()) {
                String alias = (String) ke.nextElement();
                if (caCertKeyStore.isCertificateEntry(alias)) {
                    Certificate ca = caCertKeyStore.getCertificate(alias);
                    try {
                        certificate.verify(ca.getPublicKey());
                        return true;
                    } catch (CertificateException ce) {
                    }
                }
            }
            log.info(LogManager.getHeader(context, "authentication",
                    "Keystore method FAILED SIGNATURE check on client cert."));
        } catch (GeneralSecurityException e) {
            log.info(LogManager.getHeader(context, "authentication",
                    "X.509 Certificate FAILED SIGNATURE check: " + e.toString()));
        }

    }
    return false;
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * This method sends a keypair off to be signed by the CA that issued the original keychain.
 * /*  w  w w . ja v  a 2 s. c  o m*/
 * @return a certificate that has been signed by the CA. 
 * @throws KeyRenewalFailedException if any error occurs during signing
 * @throws CryptoTokenOfflineException 
 */
@SuppressWarnings("unchecked")
private X509Certificate signCertificateByCa(EjbcaWS ejbcaWS, OcspSigningCacheEntry ocspSigningCacheEntry)
        throws KeyRenewalFailedException, CryptoTokenOfflineException {
    /* Construct a certification request in order to have the new keystore certified by the CA. 
     */
    //final int caId = CertTools.stringToBCDNString(tokenAndChain.getCaCertificate().getSubjectDN().toString()).hashCode();
    final int caId = CertTools.getSubjectDN(ocspSigningCacheEntry.getCaCertificateChain().get(0)).hashCode();
    final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate();
    final UserDataVOWS userData = getUserDataVOWS(ejbcaWS, ocspSigningCertificate, caId);
    if (userData == null) {
        final String msg = "User data for certificate with subject DN '"
                + CertTools.getSubjectDN(ocspSigningCertificate) + "' was not found.";
        log.error(msg);
        throw new KeyRenewalFailedException(msg);
    }
    editUser(ejbcaWS, userData);
    final int internalKeyBindingId = ocspSigningCacheEntry.getOcspKeyBinding().getId();
    final byte[] pkcs10CertificationRequest;
    try {
        pkcs10CertificationRequest = internalKeyBindingMgmtSession.generateCsrForNextKey(authenticationToken,
                internalKeyBindingId);
    } catch (AuthorizationDeniedException e) {
        throw new KeyRenewalFailedException(e);
    }
    CertificateResponse certificateResponse;
    try {
        certificateResponse = ejbcaWS.pkcs10Request(userData.getUsername(), userData.getPassword(),
                new String(Base64.encode(pkcs10CertificationRequest)), null,
                CertificateHelper.RESPONSETYPE_CERTIFICATE);
    } catch (Exception e) {
        //Way too many silly exceptions to handle, wrap instead.
        throw new KeyRenewalFailedException(e);
    }
    if (certificateResponse == null) {
        throw new KeyRenewalFailedException("Certificate Response was not received");
    }

    Collection<X509Certificate> certificates;
    try {
        certificates = (Collection<X509Certificate>) CertificateFactory.getInstance("X.509")
                .generateCertificates(new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));
    } catch (CertificateException e) {
        throw new KeyRenewalFailedException(e);
    }
    final byte[] publicKeyBytes;
    try {
        publicKeyBytes = internalKeyBindingMgmtSession
                .getNextPublicKeyForInternalKeyBinding(authenticationToken, internalKeyBindingId);
    } catch (AuthorizationDeniedException e) {
        throw new KeyRenewalFailedException(e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Number of certificates returned from WS: " + certificates.size());
    }
    X509Certificate signedCertificate = null;
    final X509Certificate caCertificate = ocspSigningCacheEntry.getCaCertificateChain().get(0);
    final PublicKey caCertificatePublicKey = caCertificate.getPublicKey();
    for (X509Certificate certificate : certificates) {
        if (log.isDebugEnabled()) {
            log.debug("Verifying certificate with SubjectDN : '" + CertTools.getSubjectDN(certificate)
                    + "' using public key from CA certificate with subject '"
                    + CertTools.getSubjectDN(caCertificate) + "'.");
        }
        try {
            certificate.verify(caCertificatePublicKey);
        } catch (Exception e) {
            //Ugly, but inherited from legacy code
            signedCertificate = null;
            log.error("Exception was caught when verifying certificate", e);
            continue;
        }
        // Comparing public keys is dependent on provider used, so we must ensure same provider is used for the public keys
        // Otherwise this will fail, even though it should work
        // Both certPublicKey and nextPublicKey is obtained using KeyTools.getPublicKeyFromBytes, which uses the BC provider
        final PublicKey certPublicKey = KeyTools.getPublicKeyFromBytes(certificate.getPublicKey().getEncoded());
        final PublicKey nextPublicKey = KeyTools.getPublicKeyFromBytes(publicKeyBytes);
        if (nextPublicKey.equals(certPublicKey)) {
            signedCertificate = certificate;
            break;
        } else if (log.isDebugEnabled()) {
            log.debug("Matching public keys failed: ");
            log.debug("Certificate public key: " + certificate.getPublicKey());
            log.debug("Next public key: " + nextPublicKey);
        }
    }
    if (signedCertificate == null) {
        throw new KeyRenewalFailedException("No certificate signed by correct CA generated.");
    }
    return signedCertificate;
}

From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

private boolean checkAuthorization(X509Certificate[] certificates, String remoteAddress, String remoteHost) {

    if (certificates == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", remoteAddress, remoteHost);
        m_log.error(errMsg);//  w  ww. j a  v a  2  s  . c o  m
        return false;
    }
    // The certificate of the entity is nr 0
    X509Certificate cert = certificates[0];
    if (cert == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", remoteAddress, remoteHost);
        m_log.error(errMsg);
        return false;
    }
    // Check if the certificate is authorised to access the Fnr
    if (this.trustedCerts.contains(cert.getSerialNumber())) {
        // If we found in the hashmap the same key with issuer and serialnumber, we know we got it. 
        // Just verify it as well to be damn sure
        try {
            cert.verify(this.cacert.getPublicKey());
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorverifycert");
            m_log.error(errMsg, e);
            return false;
        }
        // If verify was successful we know if was good!
        return true;
    }
    String errMsg = intres.getLocalizedMessage("ocsp.erroruntrustedclientauth", remoteAddress, remoteHost);
    m_log.error(errMsg);
    return false;
}

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

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  ww  .j a  va2s .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.OCSPUnidExtension.java

boolean checkAuthorization(HttpServletRequest request) {
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(),
                request.getRemoteHost());
        m_log.error(errMsg);/*  w  ww  . ja  va 2s.c o m*/
        return false;
    }
    // The certificate of the entity is nr 0
    X509Certificate cert = certs[0];
    if (cert == null) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(),
                request.getRemoteHost());
        m_log.error(errMsg);
        return false;
    }
    // Check if the certificate is authorised to access the Fnr
    if (this.trustedCerts.contains(cert.getSerialNumber())) {
        // If we found in the hashmap the same key with issuer and serialnumber, we know we got it. 
        // Just verify it as well to be damn sure
        try {
            cert.verify(this.cacert.getPublicKey());
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("ocsp.errorverifycert");
            m_log.error(errMsg, e);
            return false;
        }
        // If verify was successful we know if was good!
        return true;
    }
    String errMsg = intres.getLocalizedMessage("ocsp.erroruntrustedclientauth", request.getRemoteAddr(),
            request.getRemoteHost());
    m_log.error(errMsg);
    return false;
}

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

/** 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
 * //  ww w  .j av  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
 */
public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req,
        ICertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException,
        CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException {

    X509Certificate signercert = null;

    if (!req.isSigned()) {
        String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr);
        m_log.info(infoMsg);
        throw new SignRequestException(infoMsg);
    }
    // Get all certificates embedded in the request (probably a certificate chain)
    X509Certificate[] certs = req.getCerts("BC");
    // Set, as a try, the signer to be the first certificate, so we have a name to log...
    String signer = null;
    if (certs.length > 0) {
        signer = CertTools.getSubjectDN(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.verify(certs[i].getPublicKey(), "BC") == true) {
            signercert = certs[i];
            signer = CertTools.getSubjectDN(signercert);
            Date now = new Date();
            String signerissuer = CertTools.getIssuerDN(signercert);
            String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer);
            m_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 (m_log.isDebugEnabled()) {
                        m_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());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (InvalidKeyException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject,
                            issuer, e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateNotYetValidException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                } catch (CertificateExpiredException e) {
                    infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer,
                            e.getMessage());
                    m_log.info(infoMsg);
                    verifyOK = false;
                }
            } else {
                infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer);
                m_log.info(infoMsg);
                verifyOK = false;
            }
            break;
        }
    }
    if (!verifyOK) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer);
        m_log.info(errMsg);
        throw new SignRequestSignatureException(errMsg);
    }

    return signercert;
}

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

@Test
public void testKeyRenewal() throws Exception {
    //Add localhost to list of rekeying triggering hosts.
    Set<String> originalHosts = OcspConfiguration.getRekeyingTriggingHosts();
    String originalRekeyingPassword = OcspConfiguration.getRekeyingTriggingPassword();
    configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_HOSTS, "127.0.0.1");
    configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_PASSWORD, "foo123");
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();
    List<X509Certificate> oldValues = ocspResponseGeneratorTestSession.getCacheOcspCertificates();
    try {/*  www  .j  av  a  2 s .co  m*/
        X509Certificate cert = getActiveTestCert();
        X509Certificate caCertificate = getCaCert(cert);
        helper.renewAllKeys();
        ocspResponseGeneratorTestSession.reloadOcspSigningCache();
        List<X509Certificate> newValues = ocspResponseGeneratorTestSession.getCacheOcspCertificates();
        //Make sure that cache contains one and only one value
        assertEquals(
                "Cache contains a different amount of values after rekeying than before. This indicates a test failure",
                oldValues.size(), newValues.size());
        //Make check that the certificate has changed (sanity check)
        X509Certificate newSigningCertificate = null;
        for (X509Certificate signingCertificate : newValues) {
            if (CertTools.getIssuerDN(signingCertificate).equals(CertTools.getSubjectDN(caCertificate))) {
                newSigningCertificate = signingCertificate;
                break;
            }
        }
        assertNotEquals("The same certificate was returned after the renewal process. Key renewal failed",
                cert.getSerialNumber(), newSigningCertificate.getSerialNumber());
        //Make sure that the new certificate is signed by the CA certificate
        try {
            newSigningCertificate.verify(caCertificate.getPublicKey());
        } catch (SignatureException e) {
            log.error("Exception caught", e);
            fail("The new signing certificate was not signed correctly.");
        }

    } finally {
        StringBuilder originalHostsString = new StringBuilder();
        for (String host : originalHosts.toArray(new String[originalHosts.size()])) {
            originalHostsString.append(host + ";");
        }
        configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_HOSTS,
                originalHostsString.toString());
        configurationSession.setConfigurationValue(OcspConfiguration.REKEYING_TRIGGERING_PASSWORD,
                originalRekeyingPassword);
    }
}

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

/** 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  w w .j a  v a2 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

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  ww  w . j  a  va  2 s.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);
            }
        }
    }

}