Java中MD5加密一般寫法: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public final static String MD5(String s) {
try {
byte [] btInput = s.getBytes();
MessageDigest mdInst = MessageDigest.getInstance( "MD5" );
mdInst.update(btInput);
byte [] md = mdInst.digest();
StringBuffer sb = new StringBuffer();
for ( int i = 0 ; i < md.length; i++) {
int val = (( int ) md[i]) & 0xff ;
if (val < 16 )
sb.append( "0" );
sb.append(Integer.toHexString(val));
}
return sb.toString();
} catch (Exception e) {
return null ;
}
}
|
如果是給utf-8格式的字符串加密,上面的代碼就會有問題,。因為Java默認編碼是unicode,, byte[] btInput = s.getBytes();獲得的是默認的unicode的byte數(shù)組。需要將這句改為byte[] btInput = s.getBytes("utf-8");就OK啦,。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public final static String MD5Encoder(String s, String charset) {
try {
byte [] btInput = s.getBytes(charset);
MessageDigest mdInst = MessageDigest.getInstance( "MD5" );
mdInst.update(btInput);
byte [] md = mdInst.digest();
StringBuffer sb = new StringBuffer();
for ( int i = 0 ; i < md.length; i++) {
int val = (( int ) md[i]) & 0xff ;
if (val < 16 ){
sb.append( "0" );
}
sb.append(Integer.toHexString(val));
}
return sb.toString();
} catch (Exception e) {
return null ;
}
}
|
|