0%

消息摘要算法

消息摘要算法

消息摘要算法包含有MD(Message Digest,消息摘要算法)、SHA(Secure Hash Algorithm,安全散列算法)和MAC(Message Authentication Code,消息认证码算法)三大系列,常用于验证数据的完整性

MD算法

MD算法的主要代表为MD5。

MD5是一种单向加密算法,只能加密不能解密,所以一般是用来做数据一致性验证而不是作为数据加密。其原理是将信息产生一个128位的信息摘要,然后将128位的二进制转为十六进制,得到一个32位的字符串

1
2
3
4
5
6
String inputText = "123456";
MessageDigest m = MessageDigest.getInstance("md5");
// 摘要处理
byte[] s = m.digest(inputText.getBytes(StandardCharsets.UTF_8));

return new String(Hex.encodeHex(s,false));

SHA算法

SHA算法包括SHA-1、SHA-2(包含SHA-224、SHA-256、SHA-384、SHA-512)。SHA算法是在MD4基础上演进而来的,同样可以获得一个固定长度的摘要信息

1
2
3
4
5
6
String inputText = "123456";
MessageDigest m = getInstance("SHA-1");
// 摘要处理
byte[] s = m.digest(inputText.getBytes(StandardCharsets.UTF_8));

return new String(Hex.encodeHex(s,false));

MAC算法

MAC算法主要包括HmacMD5、HmacSHA1、HmacSHA256、HmacSHA384、HmacSHA512算法,其整合了MD5和SHA的优势,并加入了密钥的支持,是一种更安全的消息摘要算法

1
2
3
4
5
6
7
8
9
10
11
12
13
String data = "123456";

KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
// 产生密钥
SecretKey secretKey = keyGenerator.generateKey();
// 获得密钥
byte[] key = secretKey.getEncoded();
// 实例化Mac
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
// 初始化Mac
mac.init(secretKey);
byte[] bytes = mac.doFinal(data.getBytes());
System.out.println(new String(Hex.encodeHex(bytes, false)));

欢迎关注我的其它发布渠道