dingqianwen / my-blog

本站用来记录自己日常等,非商业化站点,无盈利性质,为博主个人博客,任何打赏均捐出公益事业。
https://apidocs.cn
Apache License 2.0
4 stars 0 forks source link

AES在线加解密 | My-Blog #167

Open dingqianwen opened 2 years ago

dingqianwen commented 2 years ago

https://apidocs.cn/blog/tools/AES.html

丁乾文的博客,希望能够帮助到你!

dingqianwen commented 1 week ago

JAVA版本AES-CBC工具

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

@Slf4j
public class Aes128Util {

    /**
     * AES加密
     *
     * @param enStr 明文
     * @return 密文 base64
     */
    public static String encrypt(String enStr, String secretKey, String iv) {
        try {
            if (StringUtils.isEmpty(enStr)) {
                return enStr;
            }
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec sks = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, sks, ivParameterSpec);

            byte[] encrypted = cipher.doFinal(enStr.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            log.error("AES加密失败", ex);
            throw new RuntimeException("AES加密失败!");
        }
    }

    /**
     * 解密
     *
     * @param encrypted 密文
     * @return 明文
     */
    public static String decrypt(String encrypted, String secretKey, String iv) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec sks = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, sks, ivParameterSpec);
            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
            return new String(original);
        } catch (Exception ex) {
            log.error("AES解密失败", ex);
            throw new RuntimeException("AES解密失败!");
        }
    }

}