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);
    }
}

 

發佈了135 篇原創文章 · 獲贊 76 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章