views:

19

answers:

1
try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm
     KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
     SecretKey key = keyGen.generateKey(); 
    // Generate a key for the HMAC-SHA1 keyed-hashing algorithm 
keyGen = KeyGenerator.getInstance("HmacSHA1"); 
        key = keyGen.generateKey(); } 
        catch (java.security.NoSuchAlgorithmException e) { }

Above code would give us keys to digest a message using HMAC. Now i wanted to implement a HMAC logic in java where the key would be given by user. Any ideas?

A: 

Construct a KeySpec using the provided user key (either a SecretKeySpec if it's a byte array, or a PBEKeySpec if it's a password), then use a SecretKeyFactory to turn that into a SecretKey.

crazyscot