天天看點

AES 加密 解密

package com.curiousby.util;

import java.security.Key;
import java.security.NoSuchAlgorithmException;

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

import org.apache.commons.codec.binary.Hex;

/**
 * AES Coder<br/>
 * secret key length:    128bit, default:    128 bit<br/>
 * mode:    ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128<br/>
 * padding:    Nopadding/PKCS5Padding/ISO10126Padding/
 * @author [email protected] baoyou
 *
 */
public class AESUtil {

    /**
     * 密鑰算法
     */
    private static final String KEY_ALGORITHM = "AES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 初始化密鑰
     *
     * @return byte[] 密鑰
     * @throws Exception
     */
    public static byte[] initSecretKey() {
        //傳回生成指定算法的秘密密鑰的 KeyGenerator 對象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new byte[0];
        }
        //初始化此密鑰生成器,使其具有确定的密鑰大小
        //AES 要求密鑰長度為 128
        kg.init(128);
        //生成一個密鑰
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    /**
     * 轉換密鑰
     *
     * @param key    二進制密鑰
     * @return 密鑰
     */
    private static Key toKey(byte[] key) {
        //生成密鑰
        return new SecretKeySpec(key, KEY_ALGORITHM);
    }

    /**
     * 加密
     *
     * @param data    待加密資料
     * @param key    密鑰
     * @return byte[]    加密資料
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, Key key) throws Exception {
        return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 加密
     *
     * @param data    待加密資料
     * @param key    二進制密鑰
     * @return byte[]    加密資料
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 加密
     *
     * @param data    待加密資料
     * @param key    二進制密鑰
     * @param cipherAlgorithm    加密算法/工作模式/填充方式
     * @return byte[]    加密資料
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
        //還原密鑰
        Key k = toKey(key);
        return encrypt(data, k, cipherAlgorithm);
    }

    /**
     * 加密
     *
     * @param data    待加密資料
     * @param key    密鑰
     * @param cipherAlgorithm    加密算法/工作模式/填充方式
     * @return byte[]    加密資料
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
        //執行個體化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        //使用密鑰初始化,設定為加密模式
        cipher.init(Cipher.ENCRYPT_MODE, key);
        //執行操作
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param data    待解密資料
     * @param key    二進制密鑰
     * @return byte[]    解密資料
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 解密
     *
     * @param data    待解密資料
     * @param key    密鑰
     * @return byte[]    解密資料
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, Key key) throws Exception {
        return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 解密
     *
     * @param data    待解密資料
     * @param key    二進制密鑰
     * @param cipherAlgorithm    加密算法/工作模式/填充方式
     * @return byte[]    解密資料
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
        //還原密鑰
        Key k = toKey(key);
        return decrypt(data, k, cipherAlgorithm);
    }

    /**
     * 解密
     *
     * @param data    待解密資料
     * @param key    密鑰
     * @param cipherAlgorithm    加密算法/工作模式/填充方式
     * @return byte[]    解密資料
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
        //執行個體化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        //使用密鑰初始化,設定為解密模式
        cipher.init(Cipher.DECRYPT_MODE, key);
        //執行操作
        return cipher.doFinal(data);
    }

    /**
     * @return
     */
    public static String encrypt(byte[] data, String key) throws Exception {
        byte[] bKey = key.getBytes();
        return Hex.encodeHexString(encrypt(data, bKey, DEFAULT_CIPHER_ALGORITHM));
    }

    /**
     * @return
     */
    public static String decrypt(String data, String key) throws Exception {
        byte[] bKey = key.getBytes();
        byte[] dBytes = decrypt(Hex.decodeHex(data.toCharArray()), bKey, DEFAULT_CIPHER_ALGORITHM);
        return new String(dBytes);
    }

    /**
     * @return
     */
    public static String encrypt(String data, String key) {
        try {
            byte[] encr = encrypt(data.getBytes(), hexStringToByte(key));
            return byteToHexString(encr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 
     * 二進制byte[]轉十六進制string 
     */
    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();
    }

    /** 
     * 十六進制string轉二進制byte[] 
     */
    public static byte[] hexStringToByte(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                System.out.println("十六進制轉byte發生錯誤!!!");
                e.printStackTrace();
            }
        }
        return baKeyword;
    }

    //    public static void main(String[] args) {
    //        try {
    //            String data = "test aes !";
    //            String str = "20ac7f405c1811089ed981e6454b1d37";
    //            byte[] encr = encrypt(data.getBytes(), hexStringToByte(str));
    //            System.out.println(byteToHexString(encr));
    //            //解密
    //            byte[] decr = decrypt(encr, hexStringToByte(str));
    //
    //            System.out.println(new String(decr));
    //
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //
    //    }
}
      

捐助開發者

在興趣的驅動下,寫一個

免費

的東西,有欣喜,也還有汗水,希望你喜歡我的作品,同時也能支援一下。 當然,有錢捧個錢場(右上角的愛心标志,支援支付寶和微信捐助),沒錢捧個人場,謝謝各位。

AES 加密 解密
AES 加密 解密
AES 加密 解密

 謝謝您的贊助,我會做的更好!

繼續閱讀