对称加密算法之Java AES算法应用 附可用工具类

欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!!

  AES算法简介

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

  上面摘抄自的一段文字描述,关于AES如果想了解更多的理论支持,自行百度即可。

  从本人的观点整理出几个重点:

  · 没有任何一种加密算法是绝对安全的,安全都是相对性的行为。

  · 随着计算机算力的提升,原本较为安全的DES,可以在通过普通机器短时间内破解。

  · 为了解决DES安全性的困扰,在DES的基础上发展出来3DES加密算法,通过对DES的反复应用,达到提高安全性的目的。

  · AES是下一代对称加密算法,安全性在DES和3DES之上,可以更加全面的保证传输过程中的安全性。

  · AES分组和秘钥大小可以为128位、192位和256位,然而AES只要求分组大小为128版本。、

  · 算法的循环:128位循环10轮、192位循环12轮、256位循环14轮。

  Maven

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

  工具类

  AESUtil提供了针对文本内容、字节数组内容的加解密实现,AESUtil工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.aes;

import java.security.SecureRandom;

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

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 * @author Securitit.
 * @note AES加密算法实现.
 */
public class AESUtil {
    
    

    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(AESUtil.class);

    /**
     * UTF-8字符集.
     */
    public final static String CHARSET_UTF8 = "UTF-8";

    /**
     * 对文本内容进行加密.
     * @param plainText 待加密明文内容.
     * @param aseKey AES秘钥.
     * @return 加密的密文.
     */
    public static String encodeText(String plainText, String aseKey) throws Exception {
    
    
        Cipher cipher = null;
        byte[] cipherBts = null;

        try {
    
    
            // 初始化加密组件.
            cipher = initAESCipher(aseKey, Cipher.ENCRYPT_MODE);
            // 字节数组加密.
            cipherBts = cipher.doFinal(plainText.getBytes(CHARSET_UTF8));
            return Base64.encodeBase64URLSafeString(cipherBts);
        } catch (Exception ex) {
    
    
            logger.error("AESUtil.encodeText.", ex);
            return "";
        }
    }

    /**
     * 对文本密文进行解密.
     * @param cipherText 待解密密文.
     * @param aseKey AES秘钥.
     * @return 解密的明文.
     */
    public static String decodeText(String cipherText, String aseKey) {
    
    
        Cipher cipher = null;
        byte[] result = null;

        try {
    
    
            // 初始化解密组件.
            cipher = initAESCipher(aseKey, Cipher.DECRYPT_MODE);
            // 字节数组解密.
            result = cipher.doFinal(Base64.decodeBase64(cipherText));
            return new String(result, CHARSET_UTF8);
        } catch (Exception ex) {
    
    
            logger.error("AESUtil.decodeText.", ex);
            return "";
        }
    }
    
    /**
     * 对字节数组内容进行加密.
     * @param plainText 待加密明文内容.
     * @param aseKey AES秘钥.
     * @return 加密的密文.
     */
    public static byte[] encodeBytes(byte[] plainBytes, String aseKey) throws Exception {
    
    
        Cipher cipher = null;
        byte[] cipherBts = null;

        try {
    
    
            // 初始化加密组件.
            cipher = initAESCipher(aseKey, Cipher.ENCRYPT_MODE);
            // 字节数组加密.
            cipherBts = cipher.doFinal(plainBytes);
            return cipherBts;
        } catch (Exception ex) {
    
    
            logger.error("AESUtil.encodeBytes.", ex);
            return null;
        }
    }

    /**
     * 对字节数组密文进行解密.
     * @param cipherText 待解密密文.
     * @param aseKey AES秘钥.
     * @return 解密的明文.
     */
    public static byte[] decodeBytes(byte[] cipherBytes, String aseKey) {
    
    
        Cipher cipher = null;
        byte[] result = null;

        try {
    
    
            // 初始化解密组件.
            cipher = initAESCipher(aseKey, Cipher.DECRYPT_MODE);
            // 字节数组解密.
            result = cipher.doFinal(cipherBytes);
            return result;
        } catch (Exception ex) {
    
    
            logger.error("AESUtil.decodeBytes.", ex);
            return null;
        }
    }

    /**
     * 初始化 AES Cipher.
     * @param aesKey 密钥.
     * @param cipherMode 密码模式.
     * @return Cipher .
     */
    private static Cipher initAESCipher(String aesKey, int cipherMode) throws Exception {
    
    
        Cipher cipher = null;
        SecretKey secretKey = null;
        SecureRandom secureRandom = null;
        KeyGenerator keyGenerator = null;
        SecretKeySpec secretKeySpec = null;

        keyGenerator = KeyGenerator.getInstance("AES");
        // 根据传入的随机源sKey初始128位的密钥.
        secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(aesKey.getBytes());
        keyGenerator.init(128, secureRandom);
        // 生成密钥.
        secretKey = keyGenerator.generateKey();
        // 获取密钥数组.
        secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
        cipher = Cipher.getInstance("AES");
        // 初始化加密后的密码.
        cipher.init(cipherMode, secretKeySpec);
        return cipher;
    }

}

  工具类测试

  在Maven依赖引入正确的情况下,复制上面的代码到项目中,修改package,可以直接使用,下面我们对工具类进行简单测试。测试类代码如下:

package com.arhorchin.securitit.enordecryption.aes;

import java.util.Arrays;

/**
 * @author Securitit.
 * @note ASEUtil测试类.
 */
public class ASEUtilTester {
    
    

    /**
     * AES测试秘钥.
     */
    private static String AES_KEY = "ABCDEFGHIJKLMNOP";
    
    public static void main(String[] args) throws Exception {
    
    
        String plainText = "This is 一段明文内容!";
        String cipherText = null;
        // 文本加解密测试.
        System.out.println("----------------------- 文本加解密测试 -------------------------");
        System.out.println("明文:" + plainText);
        cipherText = AESUtil.encodeText(plainText, AES_KEY);
        System.out.println("密文:" + cipherText);
        plainText = AESUtil.decodeText(cipherText, AES_KEY);
        System.out.println("解密明文:" + plainText);
        System.out.println();
        System.out.println("----------------------- 字节数组加解密测试 -------------------------");
        byte[] plainBytes = plainText.getBytes("UTF-8");
        byte[] cipherBytes = null;
        System.out.println("明文:" + Arrays.toString(plainBytes));
        cipherBytes = AESUtil.encodeBytes(plainBytes, AES_KEY);
        System.out.println("密文:" + Arrays.toString(cipherBytes));
        plainBytes = AESUtil.decodeBytes(cipherBytes, AES_KEY);
        System.out.println("解密明文:" + Arrays.toString(plainBytes));
        System.out.println();
    }
    
}

  控制台输出

  查看Console中的控制台内容,明文和解密后明文对比,可以确认AESUtil可以正常工作,控制台如下图:

----------------------- 文本加解密测试 -------------------------
明文:This is 一段明文内容!
密文:zMveVvAPvWzYkxAJfjOHy1KJ_XVG3fk38MTp-aWxq54
解密明文:This is 一段明文内容!

----------------------- 字节数组加解密测试 -------------------------
明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]
密文:[-52, -53, -34, 86, -16, 15, -67, 108, -40, -109, 16, 9, 126, 51, -121, -53, 82, -119, -3, 117, 70, -35, -7, 55, -16, -60, -23, -7, -91, -79, -85, -98]
解密明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]

  总结

  AES是DES、3DES的后续产物,是随着计算机的发展而发展来的,计算机算力的提升正在考验着所有的密码算法。在过去需要估算需要几十年或者上百年时间才能破解的算法,在今时今日,单计算节点甚至于计算节点集群,只需要很快的时间就可以还原出原文。在这样的环境下,算法安全不再是空谈,需要我们选择密码算法方案时,一定要慎重,以保证业务的安全性。

  若文中存在错误和不足,欢迎指正!

本博微信公众号“超哥说码”,欢迎大家订阅,公众号正在完善中,会及时将更优质的博文推送于您!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/securitit/article/details/108162699