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");
You can verify detached signature by the following code :
the key for verify detached pKCS7 is use of CMSTypedStream ,like code bellow:
You can find the answer to this post here. This happening because how bouncy castle/open ssl treats the S/MIME message when S/MIME headers are not present.Solution is to add S/MIME headers to the message before signimg