JDK安全算法包装(MD5 、RSA、 AES、国密SM系列)
前言
目前jdk支持主流的安全算法包括但不限于:md5、rsa、aes、……
程序实现
这里主要提供了MD5 、RSA、 AES的程序实现
- md5摘要
- rsa加解密(hex),及密钥生成(base64)
- aes加解密,及密钥生成
- 后续支持国密 SM2、SM3、SM4实现
SecurityUtil工具包封装
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityUtil {private static final String MD5 = "MD5";private static final String saltValue = "MASTER";private static final String RSA = "RSA";private static final String AES = "AES";public static final Base64.Encoder encoderBase64 = Base64.getEncoder();public static final Base64.Decoder decoderBase64 = Base64.getDecoder();public static String MD5EncryptAsHex(String plainText) {try {MessageDigest alg = MessageDigest.getInstance(MD5);String message = String.join("_", saltValue, plainText);byte[] encryptBytes = alg.digest(message.getBytes(StandardCharsets.UTF_8));return Hex.encodeHexString(encryptBytes);} catch (NoSuchAlgorithmException e) {return null;}}public static String RSAPublicKeyEncryptAsHex(String plainText, String publicKey) {try {PublicKey rsaPublicKey = Objects.requireNonNull(toRSAPublicKey(publicKey), "无效密钥");Cipher cipher = Cipher.getInstance(RSA);cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);byte[] bytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));return Hex.encodeHexString(bytes);} catch (Exception ignore) {return null;}}public static String RSAPrivateKeyEncryptAsHex(String plainText
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
