0

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.

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156
Paulo
  • 1
  • Setting buffer to 1 seems to work. I think it was processing the 0's or nulls in the last buffer iteration. Is there any other way to fix it? – Paulo Feb 08 '10 at 18:31

2 Answers2

2

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
  • 3,867
  • 20
  • 34
1

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
  • 48,631
  • 24
  • 141
  • 189