我在通过Android Studio为给定的字符串生成正确的哈希值时遇到问题。我已经阅读了很多解决方案,但不了解如何正确地进行转换。我需要正确的哈希,因为我正在使用它进行HTTP请求。
这是我在JAVA中的代码:
public String getHash(final String appSecret , final String sessionToken)throws NoSuchAlgorithmException ,UnsupportedEncodingException{
String input = sessionToken + appSecret;
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] byteData = digest.digest(input.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++){
sb.append(String.format("%02x", 0xFF & byteData[i]));
}
return sb.toString();
}
对于像这样的输入:
1130_11825_253402300799_1_1bcb4a27d42524de11325ec627b63878770a8651c0a0d8ddfc8fc06b92aea281634ff11f7d874c03851932304601439e
我需要确切的输出:
01a9d698f0587a25ad8ef56b0994ec0022364aff91d668a4b3a4b97c40167672
但我得到了错误的输出:
a60f61b5e9f832b153a91e8d2b1ffa28b9611b2d60c3669663cfe050ac8e28cc
我认为我的问题是如何读取/打印字符串,但我不知道如何更正它。我知道在线哈希计算器会返回正确的哈希值。谢谢。
我修改getHash
了单曲String
,我删除了对reset()
你的通话,你结束了digest()
。我也更喜欢for each
循环。喜欢,
public static String getHash(final String msg) {
StringBuilder sb = new StringBuilder();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(msg.getBytes());
byte[] byteData = digest.digest();
for (byte x : byteData) {
String str = Integer.toHexString(Byte.toUnsignedInt(x));
if (str.length() < 2) {
sb.append('0');
}
sb.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
并称它为
public static void main(String[] args) {
String out = getHash("1130_11825_253402300799_1_1bcb4a27d42524de11325ec627b63878770a8651c0a0d8ddfc8fc06b92aea281634ff11f7d874c03851932304601439e");
String expected = "01a9d698f0587a25ad8ef56b0994ec0022364aff91d668a4b3a4b97c40167672";
System.out.println(out.equals(expected));
}
我懂了
true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句