AESUtil:

import com.xxx.common.BssException;
import com.xxx.common.constants.CommonConstants;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;

/**
 * AES 加密工具,密钥长度为128bit
 *
 * @author yangyongjie
 * @date 2019/10/23
 * @desc
 */

public class AESUtil {
    private AESUtil() {
    }

    private static final String AES_ALG = "AES";

    /**
     * AES算法
     */
    private static final String AES_CBC_PCK_ALG = "AES/CBC/PKCS5Padding";

    private static final byte[] AES_IV = initIv(AES_CBC_PCK_ALG);

    /**
     * 加密
     *
     * @param content
     * @param encryptType
     * @param encryptKey
     * @param charset
     * @return
     * @throws BssException
     */
    public static String encryptContent(String content, String encryptType, String encryptKey,
                                        String charset) throws BssException {

        if (AES_ALG.equals(encryptType)) {

            return aesEncrypt(content, encryptKey, charset);

        } else {

            throw new BssException("当前不支持该算法类型:encrypeType=" + encryptType);
        }

    }

    /**
     * 解密
     *
     * @param content
     * @param encryptType
     * @param encryptKey
     * @param charset
     * @return
     * @throws BssException
     */
    public static String decryptContent(String content, String encryptType, String encryptKey,
                                        String charset) throws BssException {

        if (AES_ALG.equals(encryptType)) {

            return aesDecrypt(content, encryptKey, charset);

        } else {

            throw new BssException("当前不支持该算法类型:encrypeType=" + encryptType);
        }

    }

    /**
     * AES加密,编码默认为UTF-8
     *
     * @param content
     * @param aesKey
     * @return
     * @throws BssException
     */
    public static String aesEncrypt(String content, String aesKey) throws BssException {
        return aesEncrypt(content, aesKey, CommonConstants.CHARSET_UTF8);
    }

    /**
     * AES加密
     *
     * @param content
     * @param aesKey
     * @param charset
     * @return
     * @throws BssException
     */
    private static String aesEncrypt(String content, String aesKey, String charset)
            throws BssException {

        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

            IvParameterSpec iv = new IvParameterSpec(AES_IV);
            cipher.init(Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(Base64.decodeBase64(aesKey.getBytes()), AES_ALG), iv);

            byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return new String(Base64.encodeBase64(encryptBytes));
        } catch (Exception e) {
            throw new BssException("AES加密失败:Aescontent = " + content + "; charset = "
                    + charset, e);
        }

    }

    /**
     * AES解密,编码默认为UTF-8
     *
     * @param content
     * @param key
     * @return
     * @throws BssException
     */
    public static String aesDecrypt(String content, String key) throws BssException {
        return aesDecrypt(content, key, CommonConstants.CHARSET_UTF8);
    }


    /**
     * AES解密
     *
     * @param content
     * @param key
     * @param charset
     * @return
     * @throws BssException
     */
    private static String aesDecrypt(String content, String key, String charset)
            throws BssException {
        try {
            Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);
            IvParameterSpec iv = new IvParameterSpec(initIv(AES_CBC_PCK_ALG));
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(key.getBytes()),
                    AES_ALG), iv);

            byte[] cleanBytes = cipher.doFinal(Base64.decodeBase64(content.getBytes()));
            return new String(cleanBytes, charset);
        } catch (Exception e) {
            throw new BssException("AES解密失败:Aescontent = " + content + "; charset = "
                    + charset, e);
        }
    }

    /**
     * 初始向量的方法, 全部为0. 这里的写法适合于其它算法,针对AES算法的话,IV值一定是128位的(16字节).
     *
     * @param fullAlg
     * @return
     * @throws GeneralSecurityException
     */
    private static byte[] initIv(String fullAlg) {

        try {
            Cipher cipher = Cipher.getInstance(fullAlg);
            int blockSize = cipher.getBlockSize();
            byte[] iv = new byte[blockSize];
            for (int i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }
            return iv;
        } catch (Exception e) {

            int blockSize = 16;
            byte[] iv = new byte[blockSize];
            for (int i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }
            return iv;
        }
    }

    /**
     * 生成AES密钥
     * AES分组长度固定为128bit,密钥长度只有128、192和256bit三种
     *
     * @param length 密钥的长度
     * @return
     * @throws Exception
     */
    public static String generateDesKey(int length) throws Exception {
        //实例化
        KeyGenerator kgen;
        kgen = KeyGenerator.getInstance("AES");
        //设置密钥长度
        kgen.init(length);
        //生成密钥
        SecretKey skey = kgen.generateKey();
        //返回密钥的二进制编码
        byte[] bytes = skey.getEncoded();
        // 字节数组转字符串用二进制转16进制的方式
//        return byteToHexString(bytes);
        // 使用base64转成字符串
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * byte数组转化为16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String byteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String strHex = Integer.toHexString(bytes[i]);
            if (strHex.length() > 3) {
                sb.append(strHex.substring(6));
            } else {
                if (strHex.length() < 2) {
                    sb.append("0" + strHex);
                } else {
                    sb.append(strHex);
                }
            }
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
        String key = generateDesKey(128);
        String cipher = aesEncrypt("xiaominiubi", key);
        String plain = aesDecrypt(cipher, key);

    }

}
View Code

相关文章:

  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2021-12-05
  • 2022-02-02
  • 2021-11-14
  • 2021-11-24
  • 2021-06-06
猜你喜欢
  • 2021-11-13
  • 2021-08-01
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案