How can I verify a detached signature (CMS/pkcs #7 signature) using the BouncyCastle provider in Java?
Currently, my code below throws an exception with the message message-digest attribute value does not match calculated value
Security.addProvider(new BouncyCastleProvider());
File f = new File(filename);
byte[] buffer = new byte[(int)f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
CMSSignedData signature = new CMSSignedData(buffer);
SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");
Iterator iter = cs.getCertificates(signer.getSID()).iterator();
X509Certificate certificate = (X509Certificate) iter.next();
CMSProcessable sc = signature.getSignedContent();
signer.verify(certificate, "BC");
See Question&Answers more detail:os