我正在尝试在Android中获取一个字符串的SHA256。
这里是我想匹配的PHP代码:
echo bin2hex(mhash(MHASH_SHA256,"asdf"));
//outputs "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"
现在,我正在Java中尝试执行以下操作:
String password="asdf"
MessageDigest digest=null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
digest.reset();
try {
Log.i("Eamorr",digest.digest(password.getBytes("UTF-8")).toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是这会输出:"a42yzk3axdv3k4yh98g8"
我在这里做错了什么?
感谢erickson提供的解决方案:
Log.i("Eamorr",bin2hex(getHash("asdf")));
public byte[] getHash(String password) {
MessageDigest digest=null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
digest.reset();
return digest.digest(password.getBytes());
}
static String bin2hex(byte[] data) {
return String.format("%0" + (data.length*2) + "X", new BigInteger(1, data));
}
getBytes()
方法? - Roland Illignew String(inputBytes, StandardCharsets.UTF_8);
或类似的方法(你需要提前知道编码)。 - indivisible