public class CryptoUtils {
private static final String SHA_256 = "SHA-256";
private static final String HMAC_SHA_256 = "HmacSHA256";
private CryptoUtils() {
}
/**
* SHA-256 加密算法
*/
public static String sha256(String message) {
String res;
try {
MessageDigest messageDigest = MessageDigest.getInstance(SHA_256);
byte[] hash = messageDigest.digest(message.getBytes(StandardCharsets.UTF_8));
res = Hex.encodeHexString(hash);
} catch (NoSuchAlgorithmException e) {
return null;
}
return res;
}
/**
* HMAC-SHA256 签名算法
*/
public static String hmacSha256(String secret, String message) {
String res;
try {
Mac mac = Mac.getInstance(HMAC_SHA_256);
SecretKey secretKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA_256);
mac.init(secretKey);
byte[] hash = mac.doFinal(message.getBytes());
res = Hex.encodeHexString(hash);
} catch (Exception e) {
return null;
}
return res;
}
}
SHA-256、HMAC-SHA256加密算法工具类
最新推荐文章于 2024-05-15 23:10:33 发布