I'm trying to implement RSA sign on Java Card version 2.2.1. I have implemented RSA 2048 and tested this successfully, but when trying to hash using the MessageDigest
class, I'm unable to get the correct answer in response.
Here is my code:
MessageDigest md = MessageDigest.getInstance(MessageDigest.ALG_SHA, false);
md.reset();
md.doFinal(toSign, bOffset, bLength, tempBuffer, (short) 0);`
But I do not get the correct answer; neighther for ALG_SHA
nor for ALG_MD5
.
I'm wondering what the problem is. All samples I have seen use the same methods and parameters.
The Java Card 2.2.1 specification does not support SHA-256 (or any of the other SHA-2 message digests). It only supports SHA1 and MD5, two complete different cryptographic hash functions. Consequently, neither MessageDigest.ALG_SHA
nor MessageDigest.ALG_MD5
will get you an instance of MessageDigest
that could calculate the SHA-256 hash function.
Only Java Card 2.2.2 and onwards supports various SHA2 functions. In that specification, the MessageDigest
class would also support
MessageDigest.ALG_SHA_256
,MessageDigest.ALG_SHA_384
, andMessageDigest.ALG_SHA_512
.So if you are lucky and your card actually supports Java Card 2.2.2, you could actually use those constants to obtain a proper MessageDigest
object.
If your card does not support Java Card 2.2.2, then, of course, you can't use should not1 be able to use those constants. You could still check the manual of your card if it supports some proprietary implementation of the MessageDigest
that also has support for SHA-256, though I highly doubt that.
1) Thanks to vlp for pointing out that there are actually cards that are Java Card 2.2.1 (or below) that seemingly support using the constants for SHA-2 algorithms introduced in the Java Card 2.2.2 API. This might just be caused by other implementation bugs and nobody seems to have tested if these algorithms actually work on those cards. See the JCAlgTest list for findings on that.