0
点赞
收藏
分享

微信扫一扫

AESPKCS7加解密

拾杨梅记 2天前 阅读 1

AESPKCS7 工具类

package com.nasc.base.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.util.Base64;

/**
 * @description: AES/ECB/PKCS7Padding
 * @project: nasc
 * @className: AESPkcs7Util.java
 * @software: IntelliJ IDEA
 * @author: hanleng
 * @date: 2023/7/13 22:20
 **/
public class AESPkcs7Util {

    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    /**
     * 加密
     *
     * @param encryptText
     * @param key
     * @return
     */
    public static String encrypt(String encryptText, String key) {
        if (encryptText == null || key == null) {
            throw new IllegalArgumentException("加密文本不能为空!");
        }
        try {
            byte[] srcBytes = encryptText.getBytes(StandardCharsets.UTF_8);
            byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
            SecretKey desKey = new SecretKeySpec(keyBytes, "AES");
            Cipher c1 = Cipher.getInstance("AES/ECB/PKCS7Padding");
            c1.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] bytes = c1.doFinal(srcBytes);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (GeneralSecurityException e) {
            LogUtil.error("encrypt", e);
            return null;
        }
    }

    /**
     * 解密
     *
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.getDecoder().decode(input));
        } catch (Exception e) {
            LogUtil.error("decrypt", e);
        }
        String decryptContent = new String(output);
        return decryptContent;
    }

    public static void main(String[] args) {
        System.out.println(decrypt("Di9T9m4aTA/IOVPn66Q5zQ==", "44516cd0e584493ba92fdd4e16dcb24e"));

    }

}

举报

相关推荐

0 条评论