Reputation: 3161
I am trying to write a small Java code to see how to properly use SHA1.
Following is the code snippet I came up with:
package dummyJavaExp;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Exp1 {
public static void main(String[] args) throws NoSuchAlgorithmException {
// TODO Auto-generated method stub
String str = "Hello there";
String hashstr = new String(MessageDigest.getInstance("SHA1").digest(str.getBytes()));
System.out.println("Encrypted value of " + str + " is: " + hashstr);
}
}
But the above code gives some weird characters as shown in the following output message when I run the above code:
Encrypted value of Hello there is: rlvU>?Þ¢‘4ónjòêì\Î
I thought the encrypted message will be some alphanumeric string.
Am I missing something in my code?
Upvotes: 0
Views: 1229
Reputation: 3148
When you use String sample = new String(byte[] bytes)
it will create a string with platform's default charset, your digest bytes may not have alphanumeric representation in that charset.
Try to use Base64 or HexString to display digest message.
For example in JAVA8:
You can encode your digest bytes to string with:
String hashstr = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA1").digest(str.getBytes("UTF-8")));
You can decode your Base64 with:
byte [] digest = Base64.getDecoder().decode(hashstr);
Upvotes: 2