views:

68

answers:

2

Hi!

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. Thanks for your help.

+1  A: 

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;
Rasmus Faber
+1  A: 

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