gpt4 book ai didi

java - 字符串不相等?测试我一直在做的 md5 散列操作,是的,我正在使用 .equals

转载 作者:行者123 更新时间:2023-12-04 05:28:44 25 4
gpt4 key购买 nike

这是我类(class)的代码:

        public class Md5tester {
private String licenseMd5 = "?jZ2$??f???%?";

public Md5tester(){
System.out.println(isLicensed());
}
public static void main(String[] args){
new Md5tester();
}
public boolean isLicensed(){
File f = new File("C:\\Some\\Random\\Path\\toHash.txt");
if (!f.exists()) {
return false;
}
try {
BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
//get line from txt
String line = read.readLine();
//output what line is
System.out.println("Line read: " + line);
//get utf-8 bytes from line
byte[] lineBytes = line.getBytes("UTF-8");
//declare messagedigest for hashing
MessageDigest md = MessageDigest.getInstance("MD5");
//hash the bytes of the line read
String hashed = new String(md.digest(lineBytes), "UTF-8");
System.out.println("Hashed as string: " + hashed);
System.out.println("LicenseMd5: " + licenseMd5);
System.out.println("Hashed as bytes: " + hashed.getBytes("UTF-8"));
System.out.println("LicenseMd5 as bytes: " + licenseMd5.getBytes("UTF-8"));
if (hashed.equalsIgnoreCase(licenseMd5)){
return true;
}
else{
return false;
}
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} catch (NoSuchAlgorithmException e) {
return false;
}
}

}
这是我得到的输出:

Line read: Testing

Hashed as string: ?jZ2$??f???%?

LicenseMd5: ?jZ2$??f???%?

Hashed as bytes: [B@5fd1acd3

LicenseMd5 as bytes: [B@3ea981ca

false


我希望有人能帮我解决这个问题,因为我不知道问题是什么。

最佳答案

一个 byte[] MD5 转换返回的任意值 byte[] ,因此您不能将其视为 String 的有效表示在某种编码中。

特别是? s 在 ?jZ2$??f???%?对应于无法在输出编码中表示的字节。这意味着您的 licenseMd5 的内容已经损坏,因此您无法将您的 MD5 哈希与它进行比较。

如果您想代表您的byte[]String为了进一步比较,您需要为任意 byte[] 选择合适的表示。 s。例如,您可以使用 Base64或十六进制字符串。

您可以转换 byte[]成十六进制字符串如下:

public static String toHex(byte[] in) {
StringBuilder out = new StringBuilder(in.length * 2);
for (byte b: in) {
out.append(String.format("%02X", (byte) b));
}
return out.toString();
}

另请注意 byte[]使用 toString() 的默认实现.其结果(如 [B@5fd1acd3 )与 byte[] 的内容无关,因此在您的情况下毫无意义。

关于java - 字符串不相等?测试我一直在做的 md5 散列操作,是的,我正在使用 .equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884324/

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