I\'m trying to get the SHA256 of a string in Android.
Here is the PHP code that I want to match:
echo bin2hex(mhash(MHASH_SHA256,\"asdf\"));
//output
Complete answer with use example, thanks to erickson.
Put this into your "Utils" class.
public static String getSha256Hash(String password) {
try {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
digest.reset();
return bin2hex(digest.digest(password.getBytes()));
} catch (Exception ignored) {
return null;
}
}
private static String bin2hex(byte[] data) {
StringBuilder hex = new StringBuilder(data.length * 2);
for (byte b : data)
hex.append(String.format("%02x", b & 0xFF));
return hex.toString();
}
Example of use:
Toast.makeText(this, Utils.getSha256Hash("123456_MY_PASSWORD"), Toast.LENGTH_SHORT).show();