MD5使用(密码加密和文件加密)
import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * MD5加密工具 * @Author ChenWenChao */ public final class Md5Utils { private final static String MD5 ="MD5"; private final static char[] HEX_DIGITS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; /** * 密码加密工具 * @param username 用户名 * @param password 密码 * @return 返回密文 */ public static String getPassword(String username, String password) { String passwordMd5 = encode(MD5, password); return encode(MD5, passwordMd5 + username); } /** * 加密方式 * @param algorithm 加密方式 MD5 * @param str 加密数据 * @return */ public static String encode(String algorithm, String str) { if (str ==null) { return null; } try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.update(str.getBytes()); return getFormattedText(messageDigest.digest()); }catch (Exception e) { throw new RuntimeException(e); } } private static String getFormattedText(byte[] bytes) { int len = bytes.length; StringBuilder buf =new StringBuilder(len *2); // 把密文转换成十六进制的字符串形式 for (int j =0; j < len; j++) { buf.append(HEX_DIGITS[(bytes[j] <<4) &0x0f]); buf.append(HEX_DIGITS[bytes[j] &0x0f]); } return buf.toString(); } /** * 文件md5加密 * @param file * @return 返回文件校验码 */ public static String getFileMd5Code(MultipartFile file) { byte[] fileBytes =new byte[0]; try { fileBytes = file.getBytes(); }catch (IOException e) { e.printStackTrace(); } MessageDigest md5 =null; try { md5 = MessageDigest.getInstance(MD5); }catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] digest = md5.digest(fileBytes); return new BigInteger(1, digest).toString(16); } }