我试图签署base64编码的json字符串的SHA256哈希,并根据生成的签名验证它。
我使用以下代码签署哈希:
必需输出:使用私钥的有效负载JSON的Base64的SHA-256哈希的PKCS#7签名
String input="Base64encodedJsonData";
byte[] hashedData = DigestUtils.sha256(input.getBytes());
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
Certificate cert = keystore.getCertificate("KEY_ALIAS");
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build());
generator.addSignerInfoGenerator(jcaSignerInfoGeneratorBuilder.build(signer,(X509Certificate) cert));
CMSTypedData cmsdata = new CMSProcessableByteArray(hashedData);
CMSSignedData signeddata = generator.generate(cmsdata,true);
byte[] signedBytes= signeddata.getEncoded();
String encrypted = Base64.getEncoder().encodeToString(signedBytes);
验证:我使用以下代码验证签名数据。它返回false,表示签名无效。
boolean verifiedStatus = false;
byte[] signedBytes = Base64
.decodeBase64(encrypted.getBytes());
cmsSignedData = new CMSSignedData(
new CMSProcessableByteArray(hashedData)),
signedBytes);
Store certStore = cmsSignedData.getCertificates();
SignerInformationStore signers = cmsSignedData.getSignerInfos();
Iterator signersIterator = signers.getSigners().iterator();
while (signersIterator.hasNext()) {
SignerInformation signer = (SignerInformation) signersIterator
.next();
Collection certCollection = certStore
.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certHolder = (X509CertificateHolder) certIt
.next();
X509Certificate x509Certificate = new JcaX509CertificateConverter()
.setProvider(BC).getCertificate(certHolder);
verifiedStatus = signer
.verify(new JcaSimpleSignerInfoVerifierBuilder()
.setProvider(BC).build(x509Certificate));//returning false
如果我直接签署base64编码的字符串(没有散列),它返回true.I' m我在上面的代码中遗漏了什么?使用充气城堡签署SHA256哈希有什么不同的方法吗?