BouncyCastleProvider类需要下载jar包
https://repo1.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/bcprov-jdk16-1.46.jar

package com.cz.mylibrary.aes;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @ author chen zhang.
 * @ 创建日期 2022/7/12 14:29
 * @ 功能:AES加解密
 * AES-ECB-PKCS7Padding
 */
public class AesCipher {
    /**
     * 加密方法
     *
     * @param key 秘钥
     * @param byteContent 待加密数据
     */
    public static byte[] encryptAes(byte[] key,byte[] byteContent) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        // 指定加密的算法、工作模式和填充方式
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        return cipher.doFinal(byteContent);
    }

    /**
     * 解密方法
     *
     * @param key 秘钥
     * @param encryptedBytes 待解密数据
     */
    public static byte[] decryptAes(byte[] key,byte[] encryptedBytes) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(encryptedBytes);
    }
}
分类: 加解密

0 条评论

发表回复

您的电子邮箱地址不会被公开。