Java 字符串不相等?测试md5哈希工具I';我一直在做,是的,我在用
以下是我的课程代码:Java 字符串不相等?测试md5哈希工具I';我一直在做,是的,我在用,java,string,hash,md5,equals,Java,String,Hash,Md5,Equals,以下是我的课程代码: 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()
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;
}
}
}
以下是我得到的输出:
行读取:测试
散列为字符串:?jZ2$?f???%
许可证持有人5:jZ2美元f%
散列为字节:[B@5fd1acd3
LicenseMd5作为字节:[B@3ea981ca
假的
我希望有人能帮我澄清这一点,因为我不知道问题是什么。散列的
的打印表示中的符号不是文字问号,它们是不可打印的字符。MD5转换返回的字节[]
是任意的字节[]
,因此在某些编码中不能将其视为字符串的有效表示形式
特别是,?
中的?
与输出编码中无法表示的字节相对应。这意味着您的许可证MD5
的内容已经损坏,因此您无法将MD5哈希与之进行比较
如果要将字节[]
表示为字符串
,以便进一步比较,则需要为任意字节[]
选择正确的表示形式。例如,可以使用或十六进制字符串
您可以将字节[]
转换为十六进制字符串,如下所示:
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
)与字节[]的内容无关
,因此在您的情况下没有意义。如果您的java文件格式不是UTF-8编码,则会出现此错误。当您使用UTF-8编码字符串时,请尝试删除UTF-8,md5将输出另一个结果,您可以复制到该字符串并看到结果为真。
另一种方法是将文件编码设置为UTF-8,字符串encode也不同getBytes()
返回无法正常打印的byte[]
,因为它将调用对象的默认toString()
方法。您需要数组。toString(byte[])
打印数组。BufferedReader read=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
是将文件读入字符串的一种非常常见但不可靠的方法。您应该指定文件编码。如果您使用的是Java 7,请使用文件。readAllLines
。旁白:想想这段代码调试有多容易或难,以及您处理选中异常的方式。它返回false
,没有其他指示如果发生了什么,在非常不同的情况下,FileNotFoundException
,IOException
,和NoSuchAlgorithmException
.Upvote。为了说明一点,我强烈推荐具体的方法。它是一个一行代码,取代了大部分操作代码。没有必要重新发明轮子。非常感谢。问号是d当我把它们打印到记事本上时,id会变成可读字符,所以我认为这是eclipse的一个问题。@AnthonyAccioly,我写这段代码是为了学习,而不是为了实际的效率。感谢链接到库,如果我将来不得不使用md5,我一定会使用它。