问题
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.
回答1:
I agree with Rasmus Faber, the read/write loop is dodgy.
Replace this:
while (read < offset) {
    unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
    is.read(buffer, 0, unitsize);
    sigOut.write(buffer);
    read += unitsize;
}
with:
org.bouncycastle.util.io.Streams.pipeAll(is, sigOut);
    回答2:
One possible problem is the line
 is.read(buffer, 0, unitsize);
FileInputStream.read is only guaranteed to read between 1 and unitsize bytes.
Try writing
int actuallyRead = is.read(buffer, 0, unitsize);
sigOut.write(buffer, 0, actuallyRead);
read += actuallyRead;
    来源:https://stackoverflow.com/questions/2223759/cmssigneddatastreamgenerator-hash-does-not-match