我们使用以下代码段对PKCS7文件进行签名和制作。
public static String signAttached(X509Certificate obCert,PrivateKey obPvtKey,String signData, boolean attached){
byte[] envelopedData = null;
try{
Security.addProvider(new BouncyCastleProvider());
//Signed Attributes for TimeStamping
final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date())));
signedAttributes.add(signingAttribute);
// Create the signing table
final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
// Create the table table generator that will added to the Signer builder
final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable);
//Build CMS
X509Certificate cert = (X509Certificate) obCert;
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signData.getBytes(java.nio.charset.StandardCharsets.UTF_8));
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("SunMSCAPI").build(obPvtKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
gen.addCertificates(certs);
//true means Attached; false means detached content
CMSSignedData sigData = gen.generate(msg, attached);
envelopedData = sigData.getEncoded();
}catch(Exception e){
e.printStackTrace();
}
return new String(Base64.encode(envelopedData));
}
最终的Base64编码的信封保留在文件中。稍后,当我尝试使用以下命令来验证签名时;
$ openssl cms -verify -noverify -inform PEM -in new.p7s
Verification successful
madan prabhu nic tamilnadu state unit
用于附加签名;它工作正常。分离的签名也是如此;它不起作用。
$openssl cms -verify -noverify -inform PEM -in newd.p7s -content newd.txt
madan prabhu nic tamilnadu state unit
Verification failure
140109147780928:error:2E09A09E:CMS routines:CMS_SignerInfo_verify_content:verification failure:crypto/cms/cms_sd.c:821:
140109147780928:error:2E09D06D:CMS routines:CMS_verify:content verify error:crypto/cms/cms_smime.c:393:
newd.txt文件的内容完全相同。
请建议我如何成功解决Openssl验证;因为我们正在开发跨平台支持的解决方案。
注意:使用JcaSimpleSignerInfoVerifierBuilder在BC Java代码验证中,对两个签名(附加和分离)的验证都可以正常工作。