gpt4 book ai didi

java - 用 BC 验证分离的签名

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:15 24 4
gpt4 key购买 nike

如何使用 Java 中的 BouncyCaSTLe 提供程序验证分离的签名(CMS/pkcs #7 签名)?

目前,我的下面的代码抛出异常消息 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");

最佳答案

您可以通过以下代码验证分离签名:

public static boolean verif_Detached(String signed_file_name,String original_file_name) throws IOException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CertificateExpiredException, CertificateNotYetValidException{

boolean result= false;
Security.addProvider(new BouncyCastleProvider());

File f = new File(signed_file_name);
byte[] Sig_Bytes = new byte[(int)f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(Sig_Bytes);
in.close();

File fi = new File(original_file_name);
byte[] Data_Bytes = new byte[(int)fi.length()];
DataInputStream input = new DataInputStream(new FileInputStream(fi));
input.readFully(Data_Bytes);
input.close();

try{
CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(Data_Bytes), Sig_Bytes);
CertStore certStore = cms.getCertificatesAndCRLs("Collection", "BC");
SignerInformationStore signers = cms.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = certStore.getCertificates(signer.getSID());
Iterator certIt = certCollection.iterator();
X509Certificate cert = (X509Certificate) certIt.next();
cert_signer=cert;
result=signer.verify(cert, "BC");
}
}catch(Exception e){
e.printStackTrace();
result=false;
}
return result;
}

关于java - 用 BC 验证分离的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8243566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com