How to convert Mac to string?

How to convert MAC data type to String? I can use base64 to encode SecretKey data type into String, but this does not 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 conclusion

 Key:lnGahJHeKDqMG+c/K8OHx9HiQQl+aqhCNb0QtnDAdhzE3Xs7gP0uXf93ESO9Demrnl0XFCqHVUBsU9oppkmgVQ== MAC: javax.crypto.Mac@1ce92674 

Desired Sampling Result

 Key: lqC5SNoKYPnQRVFxTp2YhvBQpWiZU7sWTjziVXgMmcFkxvBJQA81PoTqrvscOyj05pvm6MBtlvP6gkqJvisiNQ== MAC: xca73kbvEEZBKwb0aWMhGA== 
+5
source share
2 answers

The Mac class itself is not data — it stores data and updates it when update and doFinal .

Currently, you only call init with the key - then you need to call update (optional), and then doFinal . When you call doFinal , this will return the byte[] actual hash. Currently, we cannot see any data that you want to use, but your sample will be modified as follows:

 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 data transfer - if you have only one piece of data for the hash, it means that you do not need to call update :

 Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key); byte[] hash = mac.doFinal(data); String base64Hash = Base64.getEncoder().encodeToString(hash); 
+31
source

HmacSHA1 is a hash, so it means that it works in only one way, you cannot get the original value from it. You will need to use an algorithm that is reversible.

-1
source

Source: https://habr.com/ru/post/1274540/


All Articles