AES加解密代码

package com.albedo.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES 加密
 */
public class AESUtils {
    //字符编码
    public static final String CHARSET_UTF8 = "UTF-8";
    //加密算法DES
    public static final String AES = "AES";


    /**
     * 生成key
     *
     * @param password
     * @return
     * @throws Exception
     */
    private static Key generateKey(String password) throws Exception {
        // 创建AES的Key生产者
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        //由于SecureRandom在不同操作系统底层生成机制不同,所以,为统一化,使用seed方法,
        // 这样能保证每次相同的password能够生成相同的随机数
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes(CHARSET_UTF8));
        // 利用用户密码作为随机数初始化出
        kgen.init(128, random);
        // 根据用户密码,生成一个密钥
        SecretKey secretKey = kgen.generateKey();
        // 返回基本编码格式的密钥,如果此密钥不支持编码,则返回
        byte[] enCodeFormat = secretKey.getEncoded();
        // 转换为AES专用密钥
        return new SecretKeySpec(enCodeFormat, AES);
    }

    /**
     * AES加密字符串
     *
     * @param content  需要被加密的字符串
     * @param password 加密需要的密码
     * @return 密文
     */
    public static String encrypt(String content, String password) throws Exception {

        // 创建密码器
        Cipher cipher = Cipher.getInstance(AES);
        byte[] byteContent = content.getBytes(CHARSET_UTF8);
        Key key = generateKey(password);
        // 初始化为加密模式的密码器
        cipher.init(Cipher.ENCRYPT_MODE, key);
        // 加密
        byte[] result = cipher.doFinal(byteContent);
        return new String(Base64.getEncoder().encode(result));

    }

    /**
     * 解密AES加密过的字符串
     *
     * @param content  AES加密过过的内容
     * @param password 加密时的密码
     * @return 明文
     */
    public static String decrypt(String content, String password) throws Exception {
        Key key = generateKey(password);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(Base64.getDecoder().decode(content.getBytes(CHARSET_UTF8))), CHARSET_UTF8);
    }


}
原文地址:https://www.cnblogs.com/wangzxblog/p/13651882.html