AES算法进行加密解密--工具类

AES介绍:

密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES(Data Encryption Standard),已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院 (NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

比较普遍的密码加密算法是MD5算法,但还有一种很常见的加密算法-AES算法,AES算法需要对加密的字符串进行加“盐”,也就是要增加自己一个自定义的字符串,结合要加密的字符串进行加密,而且AES算法规定要加的“盐”必须是16位字符。

AES工具类:

package com.chen.mykinthtest.util;

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

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

/**
 * AES加密/解密
 *
 * @author chen
 */
public class AESUtil {

    // 定义加密算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    // 自定义的盐,即自己设置的秘钥
    private static final String salt = "chenweisheng_aes";

    /**
     * AES加密并转为 Base64 编码
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] encryptBytes = cipher.doFinal(content.getBytes("utf-8"));
        return Base64.encodeBase64String(encryptBytes);
    }

    /**
     * 对 Base64 编码的密文进行AES解密
     *
     * @param encryptStr 待解密的密文
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        if (StringUtils.isBlank(encryptStr)) {
            return null;
        }

        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static void main(String[] args) throws Exception {
        String content = "123456";
        System.out.println();
        System.out.println("加密前:" + content);
        String encrypt = aesEncrypt(content, salt);
        System.out.println("加密后:" + encrypt);
        String decrypt = aesDecrypt(encrypt, salt);
        System.out.println("解密后:" + decrypt);
    }
}
发布了133 篇原创文章 · 获赞 75 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_42109746/article/details/104095350