JAVA加解密之AES

 

 

 <!--AES加密-->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-ext-jdk16</artifactId>
            <version>1.45</version>
        </dependency>

 

 

 

 

 工具类

AesUtil.java 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

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

/**
 * @author 。
 * @description AesUtil工具类
 **/
@Slf4j
public class AesUtil {


    /**
     * 初始化PKCS7Padding使用
     */
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密类型
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * 密码器设置
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

/**
     * AES加密
     *
     * @param content 需要加密的字符串
     * @param key     字符长度必须为16, 24, 32
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) throws Exception {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);

        // 初始化为加密模式的密码器
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM));

        // 加密
        byte[] result = cipher.doFinal(byteContent);

        //通过Base64转码返回
        String s = Base64.encodeBase64String(result);
        return s;

    }

    /**
     * AES解密
     *
     * @param encrypted 已加密的密文
     * @param key       字符长度必须为16, 24, 32
     * @return 返回解密后的数据
     */
    public static String decrypt(String encrypted, String key) throws Exception {

        //实例化
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

        //使用密钥初始化,设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM));

        //执行操作
        byte[] result = cipher.doFinal(Base64.decodeBase64(encrypted));

        String s = new String(result, StandardCharsets.UTF_8);
        return s;
    }


}

 

 

 使用 示例

  public static void main(String[] args) throws Exception {
        String content = "你好啊";

        System.out.println("加密前: " + content);
        String encryptContent = AesUtil.encrypt(content, "111");
        System.out.println("加密后:" + encryptContent);
        String decryptContent = AesUtil.decrypt(encryptContent, "111");
        ;
        System.out.println("解密后:" + decryptContent);


    }

 

 

 JS加解密之AES:https://www.cnblogs.com/pxblog/p/17070480.html

 

posted @ 2023-01-28 16:55  yvioo  阅读(503)  评论(0编辑  收藏  举报