How do I convert the MAC data type to String? I am able to use base64 to encode the SecretKey data type into a String but this doesn't work for MAC.
// Generate a secret MAC key
KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
SecretKey key = kg.generateKey();
String encodedkey=Base64.getEncoder().encodeToString(key.getEncoded());
// Create and initialize a MAC with the key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
// Print the key
System.out.println("Key:" + encodedkey);
// Print out the resulting MAC
System.out.println("MAC:" + mac);
My output
Key:lnGahJHeKDqMG+c/K8OHx9HiQQl+aqhCNb0QtnDAdhzE3Xs7gP0uXf93ESO9Demrnl0XFCqHVUBsU9oppkmgVQ==
MAC:javax.crypto.Mac@1ce92674
Desired sample output
Key: lqC5SNoKYPnQRVFxTp2YhvBQpWiZU7sWTjziVXgMmcFkxvBJQA81PoTqrvscOyj05pvm6MBtlvP6gkqJvisiNQ==
MAC: xca73kbvEEZBKwb0aWMhGA==
The Mac
class itself isn't the data - it holds the data and updates it on calls to update
and doFinal
.
Currently you're only calling init
with the key - you then need to call update
(optionally) and then doFinal
. When you call doFinal
, that will return a byte[]
of the actual hash. Currently we can't see any data that you want to hash, but your sample would be changed like this:
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
mac.update(data1);
mac.update(data2);
mac.update(data3);
// Etc...
byte[] hash = mac.doFinal();
String base64Hash = Base64.getEncoder().encodeToString(hash);
You can also call doFinal
passing in data - if you only have a single piece of data to hash, this means you don't need to call update
at all:
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
byte[] hash = mac.doFinal(data);
String base64Hash = Base64.getEncoder().encodeToString(hash);
See more on this question at Stackoverflow