使用场景 : MD5/SHA1算法为不可逆的加密算法 , 适用于比较敏感的数据 , 如 登录密码,支付密码等
使用情况 : 对敏感数据加密后, 存入关系型数据库 , 校验时 , 使用相同的加密算法加密 , 进行校验 , 加密数据相同时 , 加密后的数据也相同 , 对于敏感的数据来说是不安全的 , MD5可以使用加盐的方式来提高数据的安全性.
java实现MD5
public class MD5Utils {
private static String hex(byte[] arr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; ++i) { sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } public static String md5Hex(String password, String salt) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest((password+salt).getBytes()); return hex(digest); } catch (Exception e) { e.printStackTrace(); System.out.println(e.toString()); return ""; } }
}
或者
public final class MD5 {
public static String encrypt(String strSrc) { try { char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; byte[] bytes = strSrc.getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes); bytes = md.digest(); int j = bytes.length; char[] chars = new char[j * 2]; int k = 0; for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; chars[k++] = hexChars[b >>> 4 & 0xf]; chars[k++] = hexChars[b & 0xf]; } return new String(chars); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("MD5加密出错!!+" + e); } }
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)