I'm trying to get the SHA256 hash of a string in base64 format.
I'm using DigestUtils from org.apache.commons.codec.digest. I don't know how to get the Base64 format, even though I can get the Hex format.
Sha256String = org.apache.commons.codec.digest.DigestUtils.sha256Hex(StringText); Using "a" as stringtest, this line returns
ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb But what I actually need is ypeBEsobvcr6wjGzmiPcTaeG7/gUfE5yuYB3ha/uSLs.
I have been reading nonstop, and can't understand how to do it.
Now I'm trying this
Byte[] digest = org.apache.commons.codec.digest.DigestUtils.sha256(StringText); And this I need to store it in a variable, so I'm trying this
String OutStr = new String(digest); With no luck. I don't know where else to search help, for I had read all the google searches a lot of times (and if the answer is there, I'm not seeing it)
I don't code in java, but this time I need this to get working! Love!
11 Answer
You can use the Base64.Encoder.encodeToString() method to convert the byte array into a Base64.
Here is a short example: (since I am not familiar with your util, just replace the some data with your byte array)
byte[] data = someData; MessageDigest digester = MessageDigest.getInstance("SHA-256"); digester.update(data); String base64Encoded = Base64.getEncoder().encodeToString(digester.digest()); 1