gpt4 book ai didi

java - 如何在java中使用md5计算哈希值

转载 作者:行者123 更新时间:2023-12-02 05:07:48 31 4
gpt4 key购买 nike

我在将 md5 哈希码转换为字节码时遇到问题。使用 C#,服务端从哈希码生成一些字节码,但我无法获得相同的字节码。请帮助我如何获得相同的字节码。

C#:

 MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes = null;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Loginentities.Password));

encoder.GetBytes(Loginentities.Password)

对于这一行,我得到的字节例如[19, 15, 101, 15, 4, 104, 105, 14, 7, 1]

hashedBytes 正在获取这些字节[149,229,240 ,182 ,152 ,142 ,199, 3 ,232 ,50, 23, 47, 112, 206 ,125, 199]

哈希码:95e5f0b69asdda3e832172f70ce7dc7

Java:

String str1 ="ramprasad";
byte[] bytes1 = str1.getBytes();
System.out.println("uno shriram is "+Arrays.toString(bytes1));

对于 bytes1,我得到 [117, 110, 111, 115, 104, 114, 105, 114, 97, 109]

     try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(bytes);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
System.out.println( "0X"+sb.toString());
OUTPUT:0X95e5f0b21398asdas03e832172f70ce7dc7
String x= "0x"+sb.toString();
System.out.println(x.getBytes() );
OUTPUT:[B@1174b07
System.out.println("uno shriram is "+Arrays.toString(x.getBytes()));
OUTPUT:uno shriram is [48, 120, 57, 53, 101, 53, 102, 48, 98, 54, 57, 56, 56, 101, 99, 55, 48, 51, 101, 56, 51, 50, 49, 55, 50, 102, 55, 48, 99, 101, 55, 100, 99, 55]
try
{
byte[] bytesasd = x.getBytes("UTF-8");
MessageDigest m = MessageDigest.getInstance("MD5");

byte[] hashedbyte = m.digest(bytesasd);

System.out.println(hashedbyte);
}
catch(Exception e)
{
e.printStackTrace();
}

} catch (java.security.NoSuchAlgorithmException e) {
}
try
{
String doc2 = new String(bytes, "UTF-8");
System.out.println(""+doc2);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

如何在 java 中获取精确的散列字节。请帮助我如何获得它

最佳答案

不要忘记调用getBytes("UTF-8"),否则您的编码可能会关闭。类似的东西

String str1 = "unoshriram";
String outHash = "95e5f0b6988ec703e832172f70ce7dc7";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(str1.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : array) {
sb.append(String.format("%02X", b));
}
System.out.println(sb.toString());
System.out.println(sb.toString().equalsIgnoreCase(outHash));
} catch (Exception e) {
e.printStackTrace();
}

输出为

95E5F0B6988EC703E832172F70CE7DC7
true

关于java - 如何在java中使用md5计算哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27614456/

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