Example usage for org.bouncycastle.operator ContentVerifier getOutputStream

List of usage examples for org.bouncycastle.operator ContentVerifier getOutputStream

Introduction

In this page you can find the example usage for org.bouncycastle.operator ContentVerifier getOutputStream.

Prototype

OutputStream getOutputStream();

Source Link

Document

Returns a stream that will accept data for the purpose of calculating a signature for later verification.

Usage

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * Validates the certificate signature (hash).
 * //from  w  ww .j  a  va  2 s . c  o  m
 * @param cert
 *            The certificate to be validated.
 * @param issuerCert
 *            the issuer (normally a C.A.) certificate corresponding to the
 *            key used to sign the certificate indicated at the previous
 *            parameter.
 * 
 * @param errors
 *            a list to be filled - if needed - with errors detected during
 *            the validation process. See
 *            {@link CertificateValidationException#setErrors(List)}.
 * 
 * @return True if the certificate signature is valid. False otherwise.
 * @throws IOException
 * @throws InvalidCipherTextException
 * @throws CertException
 * @throws OperatorCreationException
 * 
 */
public static boolean verifySignature(org.bouncycastle.asn1.x509.Certificate cert,
        org.bouncycastle.asn1.x509.Certificate issuerCert, List errors)
        throws OperatorCreationException, CertException, IOException {
    boolean retval = false;
    if (!CertificateValidatorUtils.isAlgIdEqual(cert.getTBSCertificate().getSignature(),
            cert.getSignatureAlgorithm())) {
        throw new CertException("signature invalid - algorithm identifier mismatch");
    }

    ContentVerifierProvider verifierProvider = new BcRSAContentVerifierProviderBuilder(
            new DefaultDigestAlgorithmIdentifierFinder()).build(
                    PublicKeyFactory.createKey(issuerCert.getTBSCertificate().getSubjectPublicKeyInfo()));
    ContentVerifier verifier;
    try {
        verifier = verifierProvider.get((cert.getTBSCertificate().getSignature()));

        OutputStream sOut = verifier.getOutputStream();
        DEROutputStream dOut = new DEROutputStream(sOut);

        dOut.writeObject(cert.getTBSCertificate());

        sOut.close();
    } catch (Exception e) {
        throw new CertException("unable to process signature: " + e.getMessage(), e);
    }

    retval = verifier.verify(cert.getSignature().getBytes());

    if (retval == false) {
        String error = "Invalid certificate signature for [[" + extractCommonName(cert, true)
                + "]] validated against the Signer Certificate [[" + extractCommonName(issuerCert, true)
                + "]].";
        HttpsConnectionUtils.logError(error);
        errors.add(error);
    }
    return retval;
}