MD5和SHA算法可以生成一串字符串摘要(digest),可用于加密及文件内容对比。
1 package com.drz.proxy.internetProxy.util; 2 3 import java.io.File; 4 import java.io.UnsupportedEncodingException; 5 import java.security.MessageDigest; 6 import java.security.NoSuchAlgorithmException; 7 8 import org.apache.commons.codec.digest.DigestUtils; 9 import org.apache.commons.codec.digest.MessageDigestAlgorithms; 10 11 /** 12 * MD5算法可以用来对密码加密、比较文件内容 13 * MD5 用16进制数表示128位,生成的字符是32个(4个二进制位表示一个十六进制数) 14 * SHA1 是 160 位 ,SHA256 是 256 位,SHA512 是512 位 15 * @author os-dingrz 16 * 17 */ 18 public class VerifyFile { 19 20 public static void main(String[] args) throws Exception { 21 String password = "123456789"; 22 String salt = "zrd"; 23 24 String hexByMD5 = new DigestUtils(MessageDigestAlgorithms.MD5).digestAsHex(password);//不加盐 25 System.out.println(hexByMD5); 26 String secuHexByMD5 = getSecurePassword(password, salt, MessageDigestAlgorithms.MD5); 27 System.out.println(secuHexByMD5); 28 29 String hexBySHA256 = new DigestUtils(MessageDigestAlgorithms.SHA_256).digestAsHex(password);//不加盐 30 System.out.println(hexBySHA256); 31 String hexBySHA256ByMD5 = getSecurePassword(password, salt, MessageDigestAlgorithms.SHA_256); 32 System.out.println(hexBySHA256ByMD5); 33 34 //比较文件内容是否相同,与此文件名无关 35 File file2 = new File("D:/ztest.zip"); 36 String hex2 = new DigestUtils(MessageDigestAlgorithms.SHA_512).digestAsHex(file2); 37 System.out.println(hex2); 38 File file3 = new File("D:/ztest2.zip"); 39 String hex3 = new DigestUtils(MessageDigestAlgorithms.SHA_512).digestAsHex(file3); 40 System.out.println(hex3); 41 } 42 43 public static String getSecurePassword(String passwordToHash, String salt, String algtype) 44 throws UnsupportedEncodingException { 45 String generatedPassword = null; 46 try { 47 MessageDigest md = MessageDigest.getInstance(algtype); 48 md.update(salt.getBytes("UTF-8")); 49 byte[] bytes = md.digest(passwordToHash.getBytes("UTF-8")); 50 StringBuilder sb = new StringBuilder(); 51 for (int i = 0; i < bytes.length; i++) { 52 sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); 53 } 54 generatedPassword = sb.toString(); 55 } catch (NoSuchAlgorithmException e) { 56 e.printStackTrace(); 57 } 58 return generatedPassword; 59 } 60 }
执行结果:
25f9e794323b453885f5181f1b624d0b d79f0f80e4ac19c784c95727a101715e 15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225 476a9e9395799fb7a03bec9137c9761bf9144d48ecdfe059ac8be6df25cc8d98 cfd9a55957a2e5b5f7908db88451e1e1495089a57a7fdb1e7b24388ce239535d0d9c42082c8a156094e9db484913458dbf5acfa48c50023975c7a1489f340bdc cfd9a55957a2e5b5f7908db88451e1e1495089a57a7fdb1e7b24388ce239535d0d9c42082c8a156094e9db484913458dbf5acfa48c50023975c7a1489f340bdc