I use java.security.Signature to sign data. Signing does the following process:
- Create the hash of the data
- Encrypt it with the private key
I would like to store the hash of the data in order to re-sign the content later without the need of the full data. My questions are now:
- How do I get the hash of the data? As a workaround, I could hash it on my own again using the same hash function (SHA1, MD5, ...). Is there a better way?
- How can I create a signature of the given hash, instead of creating a signature of the data itself?
I'm aware of this thread that describes how Java signs, but the interface does not provide the functionality requested.
Edit 1
The currently used signature algorithm is SHA1 with DSA. Here's the code:
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(privateKey);
ByteBuffer[] byteBuffers = buf.nioBuffers();
int len = byteBuffers.length;
for (int i = 0; i < len; i++) {
ByteBuffer buffer = byteBuffers[i];
signature.update(buffer);
}
byte[] signatureData = signature.sign();
Edit 2
With the help of the user mkl, I was able to construct a demo-code that actually runs using RSA. The steps are
- Create a dummy object, sign it with private key 1 using the 'official' signature functionality
- Decrypt the signature with public key 1 in order to get the hash
- Encrypt this hash with private key 2
- Verify the 2nd signature using the 'official' signature functionality.
The code can be found here. Even though it is working, I still wonder if there is a more elegant way to do this?