> OTOH, you are right, there is no such thing in Sun's JCE as a
> HMACSecretKeySpec, neither a SecretKeyFactory for HMAC keys. I don't
[quoted text clipped - 6 lines]
> You don't need a SecretKeyFactory here because SecretKeySpec implements
> the SecretKey interface. You can also set any algorithm name you like.
Some implementations require the algorithm name to match an implemented
scheme ("DES", etc.). Which (as you stated) is somewhat annoying
because there is no "HMAC" key type, so anything that is selected ends
up being kludgy.
> In your case, using DESKeySpec keys is also wrong, because des keys are
> 56 bits, while HMAC-MD5 keys are 128 bits.
HMAC keys can actually be arbitrary length (really up to the block size
of the hash function, which is 64 bytes for MD5). *Optimal* key length
is the length of the hash function output (128 bits for MD5). If the
key material happens to be longer than the hash function block size, the
hash function is first applied to the key material and the resulting
digest is used as the key for the MAC.
Incidentally, HMAC is fairly trivial to implement using just the
MessageDigest primitive; here is HMAC-MD5:
private static byte[] HmacMD5(byte[] key, byte[] data)
throws Exception {
if (key.length > 64) {
key = MessageDigest.getInstance("MD5").digest(key);
}
byte[] ipad = new byte[64];
byte[] opad = new byte[64];
for (int i = 0; i < 64; i++) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
}
for (int i = key.length - 1; i >= 0; i--) {
ipad[i] ^= key[i];
opad[i] ^= key[i];
}
byte[] tmp = new byte[data.length + 64];
System.arraycopy(ipad, 0, tmp, 0, 64);
System.arraycopy(data, 0, tmp, 64, data.length);
data = MessageDigest.getInstance("MD5").digest(tmp);
tmp = new byte[data.length + 64];
System.arraycopy(opad, 0, tmp, 0, 64);
System.arraycopy(data, 0, tmp, 64, data.length);
return MessageDigest.getInstance("MD5").digest(tmp);
}
JK - 01 Dec 2003 08:53 GMT
Right, I mixed something up.
JK
... snipped...
> HMAC keys can actually be arbitrary length (really up to the block size
> of the hash function, which is 64 bytes for MD5). *Optimal* key length
> is the length of the hash function output (128 bits for MD5). If the
> key material happens to be longer than the hash function block size, the
> hash function is first applied to the key material and the resulting
> digest is used as the key for the MAC.
... snipped...