本文主要讲解关于Java17标准库实现md5/base64/sha256加密解密代码相关内容,让我们来一起学习下吧!
一时兴起,好奇 Java 中常用的加解密是如何实现的,今天就 常见的 bas64编码解码、MD5、SHA256、HmacSHA256 做个简单小结,希望对各位有用。
环境:JDK17
以下内容基于 JDK 17 的自带工具库 实现,示例如下:
package com.example.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class MyCrypto {
// base64 加解密
public static String encodeBase64(String val) {
return Base64.getEncoder().encodeToString(val.getBytes());
}
public static String decodeBase64(String b64Str) {
return new String(Base64.getDecoder().decode(b64Str));
}
// md5 or sha256 加密
public static String md5OrSha256(String val, String algorithm) {
if (val == null) {
val = "";
}
String Str = "";
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(val.getBytes());
byte[] b = md.digest();
int i;
StringBuilder builder = new StringBuilder(32);
for (int j = 0; j < b.length; j++) {
i = b[j];
if (i < 0) {
i += 256;
}
if (i < 16) {
builder.append("0");
}
builder.append(Integer.toHexString(i));
}
Str = builder.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// md5 -> 128 bits, sha256 -> 256 bits
return Str;
}
private static String byteArrayToHexString(byte[] b) {
StringBuilder builder = new StringBuilder();
String stmp;
for (int i = 0; i < b.length; i++) {
stmp = Integer.toHexString(b[i] & 0XFF);
if (stmp.length() == 1) builder.append('0');
builder.append(stmp);
}
return builder.toString().toLowerCase();
}
public static String hmacSha256(String msg, String secret) {
String hash = "";
String algorithm = "HmacSHA256";
try {
Mac instance = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), algorithm);
instance.init(secretKey);
byte[] bytes = instance.doFinal(msg.getBytes());
hash = byteArrayToHexString(bytes);
} catch (NoSuchAlgorithmException| InvalidKeyException e) {
e.printStackTrace();
}
return hash;
}
public static void main(String[] args) {
String str = "hello, world";
System.out.println(encodeBase64(str));
System.out.println(decodeBase64(encodeBase64(str)));
System.out.println(md5OrSha256(str, "MD5"));
System.out.println(md5OrSha256(str, "SHA-256"));
System.out.println(hmacSha256("hello, world", "secret"));
}
}
以上就是关于Java17标准库实现md5/base64/sha256加密解密代码相关的全部内容,希望对你有帮助。欢迎持续关注潘子夜个人博客(www.panziye.com),学习愉快哦!