SHA1 returns different Digest
import java.security.MessageDigest;
class Enc{
public String encryptPassword(String password) throws Exception{
by开发者_开发百科te[] 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
*/
You're just printing out byte[].toString
which isn't the contents of the hash.
System.out.println(encoded.toString());
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:
byte[] bArray=password.getBytes()
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.
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
private static String getMD5Digest(File file) {
BufferedInputStream reader = null;
String hexDigest = new String();
try {
reader = new BufferedInputStream( new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] buffer = new byte[4096];
long fileLength = file.length();
long bytesLeft = fileLength;
int read = 0;
//Read our file into the md buffer
while(bytesLeft > 0){
try {
read = reader.read(buffer,0, bytesLeft < buffer.length ? (int)bytesLeft : buffer.length);
} catch (IOException e) {
e.printStackTrace();
}
md.update(buffer,0,read);
bytesLeft -= read;
}
byte[] digest = md.digest();
for (int i = 0; i < digest.length;i++) {
hexDigest += String.format("%02x" ,0xFF & digest[i]);
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return hexDigest;
}
精彩评论