CMSSignedDataStreamGenerator哈希值不匹配 [英] CMSSignedDataStreamGenerator hash does not match

查看:199
本文介绍了CMSSignedDataStreamGenerator哈希值不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an application that signs and envelopes data using BouncyCastle.

我需要对大型文件进行签名,所以不要使用 CMSSignedDataGenerator (对小文件也很好)选择使用 CMSSignedDataStreamGenerator 。正在生成签名文件,但是 SHA1 哈希与原始文件不匹配。您能帮我吗?

I need to sign large files so instead of using the CMSSignedDataGenerator (which works just fine for small files) I chose to use CMSSignedDataStreamGenerator. The signed files are being generated but the SHA1 hash does not match with the original file. Could you help me?

这里是代码:

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();

我不知道我在做什么错。

I don't know what I'm doing wrong.

推荐答案

我同意Rasmus Faber的观点,读/写循环是狡猾的。

I agree with Rasmus Faber, the read/write loop is dodgy.

替换此:

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);

这篇关于CMSSignedDataStreamGenerator哈希值不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆