侧边栏壁纸
  • 累计撰写 29 篇文章
  • 累计创建 18 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

Aes加解密

bsdlzg
2023-01-28 / 0 评论 / 1 点赞 / 82 阅读 / 197 字

Aes加解密工具

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Slf4j
public class AesUtil {

    public static String encrypt(String plainText, String secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            cipher.init(1, skeySpec);
            byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(encrypted);
        } catch (Exception e) {
            log.error("[AES加密异常]",e);
            return null;
        }

    }

    public static String decrypt(String cliperText, String secretKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            cipher.init(2, skeySpec);
            byte[] encrypted = Base64.getDecoder().decode(cliperText);
            byte[] original = cipher.doFinal(encrypted);
            String originalString = new String(original, "UTF-8");
            return originalString;
        } catch (Exception e) {
            log.error("[AES解密异常]",e);
            return null;
        }
    }


    public static void main(String[] args) {
    	// 加密
        System.out.println(encrypt("13575475155","2f39473f6ba28f71"));
       // 解密 
       System.out.println(decrypt("DyVzFMSU6wE7uECSg4Mcjg==","652246400e0badab"));
    }
}
1

评论区