在java程序中实现MD5摘要方法,生成16进制的字符串
public static String string2MD5(String inStr){
String result = null;
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance(ENCRYPT_ALGORITHM);
byte[] outByteArray = messageDigest.digest(inStr.getBytes());
result = HexUtils.toHexString(outByteArray);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}
public static String file2MD5(String filePath){
String result = null;
MessageDigest messageDigest;
File file = new File(filePath);
try {
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,0,file.length());
messageDigest = MessageDigest.getInstance(ENCRYPT_ALGORITHM);
messageDigest.update(byteBuffer);
byte[] outByteArray = messageDigest.digest();
result = HexUtils.toHexString(outByteArray);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
// 1aabac6d068eef6a7bad3fdf50a05cc8
String xxx = "dd";
String s = string2MD5(xxx);
System.out.printf(s);
}
2、linux使用md5sum生成摘要
使用md5sum生成字符串的摘要值
// 使用echo默认情况,在字符串末尾自动添加换行符 [root@localhost ~]# echo 'dd' | md5sum b064a020db8018f18ff5ae367d01b212 - // echo -n,表示不在字符串末尾自动添加换行符 [root@localhost ~]# echo -n 'dd' | md5sum 1aabac6d068eef6a7bad3fdf50a05cc8 - // echo -n -e,表示不在字符串末尾自动添加换行符,-e表示支持以''作为转义字符进行转义;手动添加换行符后md5值与echo不加参数的情况一致 [root@localhost ~]# echo -n -e 'ddn' | md5sum b064a020db8018f18ff5ae367d01b212 -
- 从上面两种生成方式不同可以获取结论,java程序和md5sum的算法是一致,导致md5不一致的原因是echo输出字符串时会在字符串末尾添加’n’换行符。
- echo -n ‘字符串’,将字符串转为输出流,在字符串末尾不添加‘n’
- echo -e ‘字符串’,在字符串中可以使用反斜杠作为转移字符
Windows 系统自带工具 certutil,具体命令 certutil -hashfile 文件地址 MD5
D:logs>certutil -hashfile aa.txt MD5 MD5 的 aa.txt 哈希: b064a020db8018f18ff5ae367d01b212 CertUtil: -hashfile 命令成功完成。



