gpt4 book ai didi

java - android中sha256哈希计算错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:21 24 4
gpt4 key购买 nike

我在通过 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

我认为我的问题是如何读取/打印字符串,但我不知道如何纠正它。我知道在线哈希计算器会返回正确的哈希值。谢谢。

最佳答案

import static org.junit.Assert.assertEquals;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.junit.Test;

public class Sha256Test {

@Test
public void sha256Test() throws NoSuchAlgorithmException {
String out = hash256("1130_11825_253402300799_1_1bcb4a27d42524de11325ec627b63878770a8651c0a0d8ddfc8fc06b92aea281634ff11f7d874c03851932304601439e");
String in = "01a9d698f0587a25ad8ef56b0994ec0022364aff91d668a4b3a4b97c40167672";
assertEquals(in, out);
}

private String hash256(String data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
return bytesToHex(md.digest());
}

private String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte byt : bytes) {
result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1));
}
return result.toString();
}
}

参见:https://gist.github.com/avilches/750151

关于java - android中sha256哈希计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com