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数组。需要将这句改为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 ;
}
}
|
|