SHA1 返回不同的摘要
import java.security.MessageDigest;
class Enc{
public String encryptPassword(String password) throws Exception{
byte[] bArray=password.getBytes();
MessageDigest md=MessageDigest.getInstance("SHA-1");
md.reset();
md.update(bArray);
byte[] encoded=md.digest();
System.out.println(encoded.toString());
return "";
}
public static void main(String args[]){
try{
Enc e=new Enc();
e.encryptPassword("secret");
}catch(Exception e){e.printStackTrace();}
}
}
/*
jabira-whosechild-lm.local 12:40:35 % while (true); do java Enc; done
[B@77df38fd
[B@77df38fd
[B@60072ffb
[B@77df38fd
[B@6016a786
[B@60072ffb
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@6016a786
[B@6f507fb2
[B@77df38fd
[B@6016a786
[B@77df38fd
[B@77df38fd
[B@6016a786
*/
import java.security.MessageDigest;
class Enc{
public String encryptPassword(String password) throws Exception{
byte[] bArray=password.getBytes();
MessageDigest md=MessageDigest.getInstance("SHA-1");
md.reset();
md.update(bArray);
byte[] encoded=md.digest();
System.out.println(encoded.toString());
return "";
}
public static void main(String args[]){
try{
Enc e=new Enc();
e.encryptPassword("secret");
}catch(Exception e){e.printStackTrace();}
}
}
/*
jabira-whosechild-lm.local 12:40:35 % while (true); do java Enc; done
[B@77df38fd
[B@77df38fd
[B@60072ffb
[B@77df38fd
[B@6016a786
[B@60072ffb
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@77df38fd
[B@6016a786
[B@6f507fb2
[B@77df38fd
[B@6016a786
[B@77df38fd
[B@77df38fd
[B@6016a786
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只是打印出
byte[].toString
,这不是哈希的内容。要将哈希显示为文本,您应该将字节数组转换为十六进制或 base64 - Stack Overflow 上有大量片段可以实现此目的(例如使用 Apache Commons 编解码器)。如果您不需要将哈希值作为文本,则可以将其保留为字节数组。
另请注意,您不应该使用此代码:
它将使用系统默认字符编码,该编码可能因系统而异,并且可能无法对所有 Unicode 进行编码。使用固定编码(例如 UTF-8),无论系统默认设置如何,对于相同的输入,它始终会给出相同的结果,并且可以对所有 Unicode 进行编码。
You're just printing out
byte[].toString
which isn't the contents of the hash.To display the hash as text, you should convert the byte array to hex or base64 - there are loads of snippets on Stack Overflow to accomplish that (e.g. using Apache Commons Codec). If you don't need the hash as text, you can just leave it as a byte array though.
Also note that you shouldn't use this code:
That will use the system default character encoding, which can vary from system to system, and may not be able to encode all of Unicode. Use a fixed encoding such as UTF-8, which will always give the same results for the same input regardless of system defaults, and which can encode all of Unicode.
这是我对整个文件进行 MD5 的代码片段。当我对要发送的文件进行 MD5 处理以查看他们的客户是否已经拥有相同的文件时,它对我有用。如果需要,可以在 Github 上找到完整源代码< /a>
Here is a code snippet I to MD5 an entire file. It worked for me when I MD5ed a file I wanted to sent to see if they client already had the same file. Complete source if needed can be found here on Github