Java加密解密算法世界( 三 )

2、MD5
说明:严格意义上不属于加密算法 , 属于信息摘要算法 。
例子:
package com.yx.encryption;import java.security.MessageDigest;/** * MD5使用例子 * 生成消息摘要 * * @author yx */public class MD5Demo {private static final char[] HEXES = {'0', '1', '2', '3','4', '5', '6', '7','8', '9', 'a', 'b','c', 'd', 'e', 'f'};/*** byte数组 转换成 16进制小写字符串*/public static String bytes2Hex(byte[] bytes) {if (bytes == null || bytes.length == 0) {return null;}StringBuilder hex = new StringBuilder();for (byte b : bytes) {hex.append(HEXES[(b >> 4) & 0x0F]);hex.append(HEXES[b & 0x0F]);}return hex.toString();}public static void main(String[] args) throws Exception {// 加密字符String src = https://www.isolves.com/it/cxkf/sf/2021-07-30/"EasyJava";// 获取摘要MessageDigest messageDigest = MessageDigest.getInstance("MD5");byte[] md5Result = messageDigest.digest(src.getBytes("utf-8"));System.out.println("摘要信息:" + bytes2Hex(md5Result));}}执行结果:摘要信息:0d50d2ea5aece0b7bc10643a3f72159c3、SHA
说明:SHA家族的五个算法 , 分别是SHA-1、SHA-224、SHA-256、SHA-384 , 和 SHA-512 , 后四者有时并称为SHA-2 。SHA-1在许多安全协定中广为使用 。MD5与SHA1都是Hash算法 , MD5输出是128位的(转换为16进制则为32个字符) , SHA1输出是160位的(转换为16进制则为40个字符) , MD5比SHA1快 , SHA1比MD5强度高 。
例子:
package com.yx.encryption;import java.security.MessageDigest;/** * SHA使用例子 * 生成消息摘要 * * @author yx */public class SHADemo {private static final char[] HEXES = {'0', '1', '2', '3','4', '5', '6', '7','8', '9', 'a', 'b','c', 'd', 'e', 'f'};/*** byte数组 转换成 16进制小写字符串*/public static String bytes2Hex(byte[] bytes) {if (bytes == null || bytes.length == 0) {return null;}StringBuilder hex = new StringBuilder();for (byte b : bytes) {hex.append(HEXES[(b >> 4) & 0x0F]);hex.append(HEXES[b & 0x0F]);}return hex.toString();}public static void main(String[] args) throws Exception {// 加密字符String src = https://www.isolves.com/it/cxkf/sf/2021-07-30/"EasyJava";// 获取摘要MessageDigest messageDigest = MessageDigest.getInstance("SHA");messageDigest.update(src.getBytes("utf-8"));byte[] md5Result = messageDigest.digest();System.out.println("摘要信息:" + bytes2Hex(md5Result));}}执行结果:摘要信息:a59bcc9c6c15610a8fc0dc75a1551903f5583a90



推荐阅读