gpt4 book ai didi

java - CMSSignedDataStreamGenerator 哈希不匹配

转载 作者:行者123 更新时间:2023-12-02 00:52:59 24 4
gpt4 key购买 nike

我正在编写一个使用 BouncyCaSTLe 对数据进行签名和封装的应用程序。

我需要对大文件进行签名,因此我选择使用 CMSSignedDataStreamGenerator,而不是使用 CMSSignedDataGenerator(它适用于小文件)。正在生成签名文件,但 SHA1 哈希与原始文件不匹配。你能帮我吗?

代码如下:

try {

int buff = 16384;
byte[] buffer = new byte[buff];
int unitsize = 0;
long read = 0;
long offset = file.length();
FileInputStream is = new FileInputStream(file);
FileOutputStream bOut = new FileOutputStream("teste.p7s");
Certificate cert = keyStore.getCertificate(alias);
PrivateKey key = (PrivateKey) keyStore.getKey(alias, null);
Certificate[] chain = keyStore.getCertificateChain(alias);
CertStore certStore = CertStore.getInstance("Collection",new CollectionCertStoreParameters(Arrays.asList(chain)));
CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator();
gen.addSigner(key, (X509Certificate) cert, CMSSignedDataGenerator.DIGEST_SHA1, "SunPKCS11-iKey2032");
gen.addCertificatesAndCRLs(certStore);
OutputStream sigOut = gen.open(bOut,true);

while (read < offset) {
unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
is.read(buffer, 0, unitsize);
sigOut.write(buffer);
read += unitsize;
}
sigOut.close();
bOut.close();
is.close();

我不知道我做错了什么。

最佳答案

我同意 Rasmus Faber 的观点,读/写循环是不可靠的。

替换这个:

while (read < offset) {
unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
is.read(buffer, 0, unitsize);
sigOut.write(buffer);
read += unitsize;
}

与:

org.bouncycastle.util.io.Streams.pipeAll(is, sigOut);

关于java - CMSSignedDataStreamGenerator 哈希不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2223759/

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