1,MD5簡(jiǎn)介
1)Message Digist Algorithm 5(消息摘要算法); SHA(Secure hash algorithm)安全hash算法。
2)Java已經(jīng)實(shí)現(xiàn)了MD5、SHA1算法。java.security.MessageDigest,String和文件的MD5以及SHA1結(jié)果。the array of bytes for the resulting hash value.
3)md5是一個(gè)固定長(zhǎng)度128比特(bit)的串1和0的組合,md5的32位表示使用16進(jìn)制表示二進(jìn)制,md5的16位表示32位表示去掉前8位和后8位。
2,MD5加密字符串
private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String md5String(String input) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] inputBytes = input.getBytes();
byte[] resultByte = md.digest(inputBytes);
int length = resultByte.length;
char[] result = new char[length * 2];
int index = 0;
for(int i = 0; i < length; i++){
int val = resultByte[i];//轉(zhuǎn)換成int類型
if(val < 0){
val = val + 256;//負(fù)數(shù)使用補(bǔ)碼表示,eg: -1 + 256,等效于只取負(fù)數(shù)補(bǔ)碼的低8位(原byte類型)。
}
result[index++] = HEX[val/16];//使用除k取整法轉(zhuǎn)成16
result[index++] = HEX[val % 16];
}
return result.toString();
}
3,MD5加密文件
public static String md5File(String path) throws Exception{
MessageDigest md = MessageDigest.getInstance("md5");
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
DigestInputStream digestInputStream = new DigestInputStream(inputStream, md);
byte[] buffer =new byte[256 * 1024];
while (digestInputStream.read(buffer) > 0){
md = digestInputStream.getMessageDigest();
}
byte[] resultByte = md.digest();
int length = resultByte.length;
char[] result = new char[length * 2];
int index = 0;
for(int i = 0; i < length; i++){
result[index++] = HEX[resultByte[i] >>> 4 & 0xf];//使用位運(yùn)算來進(jìn)行16進(jìn)制轉(zhuǎn)換
result[index++] = HEX[resultByte[i] & 0xf];
}
return result.toString();
}