CMSSignedDataStreamGenerator 哈希不匹配
我正在编写一个使用 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();
我不知道我做错了什么。
I'm writing an application that signs and envelopes data using BouncyCastle
.
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?
Here`s the code:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意 Rasmus Faber 的观点,读/写循环是不可靠的。
将其替换
为:
I agree with Rasmus Faber, the read/write loop is dodgy.
Replace this:
with:
一个可能的问题是行
FileInputStream.read
仅保证读取 1 到unitsize
字节之间的内容。尝试写作
One possible problem is the line
FileInputStream.read
is only guaranteed to read between 1 andunitsize
bytes.Try writing