aes加密解密原始碼,含 128、192、256位,cbc、cfb、ecb、ofb、pcbc模式

陳守印發表於2018-05-25


AES加解密總共有以下這些

演算法/模式/填充                 位元組加密後資料長度       不滿16位元組加密後長度  
AES/CBC/NoPadding                   16                          不支援  
AES/CBC/PKCS5Padding                32                          16  
AES/CBC/ISO10126Padding             32                          16  
AES/CFB/NoPadding                   16                          原始資料長度  
AES/CFB/PKCS5Padding                32                          16  
AES/CFB/ISO10126Padding             32                          16  
AES/ECB/NoPadding                   16                          不支援  
AES/ECB/PKCS5Padding                32                          16  
AES/ECB/ISO10126Padding             32                          16  
AES/OFB/NoPadding                   16                          原始資料長度  
AES/OFB/PKCS5Padding                32                          16  
AES/OFB/ISO10126Padding             32                          16  
AES/PCBC/NoPadding                  16                          不支援  
AES/PCBC/PKCS5Padding               32                          16  
AES/PCBC/ISO10126Padding            32                          16  


一、不帶模式和填充來獲取AES演算法的時候,其預設使用AES/ECB/PKCS5Padding(輸入可以不是16位元組,也不需要填充向量)

Cipher cipher = Cipher.getInstance("AES");

下面是 AES/ECB/PKCS5Padding 128位、192位、256加解密 檢視完整程式碼

        String content = "線上助手";
        // 生成金鑰需要的密碼值
        String key = "";
        /**
         * AES加密方式一:AES不指定模式和填充,預設為 ECB/PKCS5Padding
         *
         * 不能使用填充向量
         * java.security.InvalidAlgorithmParameterException: ECB mode cannot use IV
         */
        System.out.println("【0】AES不指定模式和填充,預設為 ECB/PKCS5Padding,輸入可以不是16位元組,也不需要填充向量\n");
        //128
        byte[] encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_DEFAULT);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_DEFAULT);
        //192
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_DEFAULT);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_DEFAULT);
        //256
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_DEFAULT);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_DEFAULT);

結果如下:

【0】AES不指定模式和填充,預設為 ECB/PKCS5Padding,輸入可以不是16位元組,也不需要填充向量

秘鑰長度,128,加密方式: AES,加密結果:09942AC3BB18703E2BAF29EC18E69BCC
秘鑰長度,128,解密方式: AES,解密結果:線上助手

秘鑰長度,192,加密方式: AES,加密結果:B9F574EF92836DFD2CC0EE03E7A0E717
秘鑰長度,192,解密方式: AES,解密結果:線上助手

秘鑰長度,256,加密方式: AES,加密結果:118CD83850A220EFD791FF6B1FF180F8
秘鑰長度,256,解密方式: AES,解密結果:線上助手

二、AES/CBC 加密方式

2.1 AES/CBC/NoPadding
 輸入必須是16位元組,不然報錯 **javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
CBC模式必須提供初始向量IvParameterSpec,不然報錯 **java.security.InvalidKeyException: Parameters missing


content: 線上助手
key: 111
javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1041)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:1009)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at com.csy.spring.it399.controller.encode.aes.AESUtil.encrypt(AESUtil.java:80)
    at com.csy.spring.it399.controller.encode.aes.AESUtil.main(AESUtil.java:200)
java.security.InvalidKeyException: Parameters missing
    at com.sun.crypto.provider.CipherCore.init(CipherCore.java:470)
    at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
    at javax.crypto.Cipher.implInit(Cipher.java:802)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1249)
    at javax.crypto.Cipher.init(Cipher.java:1186)
    at com.csy.spring.it399.controller.encode.aes.AESUtil.decrypt(AESUtil.java:117)
    at com.csy.spring.it399.controller.encode.aes.AESUtil.main(AESUtil.java:202)
encode: null
decode: null


初始化加密模式的時改成

 Cipher cipher = Cipher.getInstance(“AES/CBC/NoPadding”);


java.security.InvalidKeyException: Parameters missing解決辦法:

 if (modeAndPadding.equals(EncodeType.AES_CBC_NoPadding)) {
         //指定一個初始化向量 (Initialization vector,IV), IV 必須是16位
         cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(getIV()));
   } else {
         cipher.init(Cipher.ENCRYPT_MODE, keySpec);
}

下面是 AES/CBC/NoPadding,AES/CBC/PKCS5Padding,AES/CBC/ISO10126Padding 128位,192位,256加密解密(文末附完整程式碼,

       /**
         * 1.1 AES/CBC
         * AES/CBC/NoPadding
         * AES/CBC/PKCS5Padding
         * AES/CBC/ISO10126Padding
         */
        System.out.println("【1.1】AES_CBC_NoPadding模式");
        content = "線上助手線上助手線上助手線上助手";
        key = "";
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);



秘鑰長度,128,加密方式: AES/CBC/NoPadding,加密結果:81C094D454913311113FA1E5B5A3B6778DC81026A19A52C51FAF54B82E48448A813E1FDE3F97E8ACE13FE37C550023DA
秘鑰長度,128,解密方式: AES/CBC/NoPadding,解密結果:線上助手線上助手線上助手線上助手

秘鑰長度,192,加密方式: AES/CBC/PKCS5Padding,加密結果:5BCD216A00741AB48668742393A8F995C63B4A875F6BD460BFB04DBCF5BF35E429C0C177A54D0DAFF7E38DD83EA11B0C434B836B8EAAE015666987377AF8C9D0
秘鑰長度,192,解密方式: AES/CBC/PKCS5Padding,解密結果:線上助手線上助手線上助手線上助手

秘鑰長度,256,加密方式: AES/CBC/ISO10126Padding,加密結果:1A45746F4E488AB13752033C21F9EE9C64417ECAA3A8FA08326D76DD1A052445218AA6D5408AC1D2F52998437C0786EEBC3990098DC36E6B7E6701474BA737D4
秘鑰長度,256,解密方式: AES/CBC/ISO10126Padding,解密結果:線上助手線上助手線上助手線上助手

三、AES/CFB 加密方式

需要填充變數,不然報如下錯誤

Exception in thread "main" java.security.InvalidKeyException:
Parameters missing

下面是AES/CFB/NoPadding,AES/CFB/PKCS5Padding,AES/CFB/ISO10126Padding 128位,192位,256位加加密解密

       /**
         * 1.2 AES/CFB
         * AES/CBC/NoPadding
         * AES/CBC/PKCS5Padding
         * AES/CBC/ISO10126Padding
         */
        System.out.println("【1.2】AES_CFB_NoPadding模式\n");
        content = "線上助手";
        // 生成金鑰需要的密碼值
        key = "http://";
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);



四、AES/ECB 加密方式

AES/ECB不要填充變數,不然會報如下錯誤

Exception in thread "main" java.security.InvalidAlgorithmParameterException: ECB mode
cannot use IV

下面是AES/ECB/NoPadding,AES/ECB/PKCS5Padding,AES/ECB/ISO10126Padding 128位,192位,256位加加密解密
```java
        /**
         * 1.3 AES/ECB
         * AES/ECB/NoPadding
         * AES/ECB/PKCS5Padding
         * AES/ECB/ISO10126Padding
         */
        System.out.println("【1.3】AES_ECB模式");
        content = "線上助手";
        // 生成金鑰需要的密碼值
        key = "http://";
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_ECB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_ECB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_ECB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_ECB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_ECB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_ECB_PKCS5Padding);

```
####五、AES/OFB 加密方式
下面是AES/OFB/NoPadding,AES/OFB/PKCS5Padding,AES/OFB/ISO10126Padding 128位,192位,256位加加密解密
* 需要填充向量
```java
        /**
         * 1.4 AES/OFB
         * AES/OFB/NoPadding
         * AES/OFB/PKCS5Padding
         * AES/OFB/ISO10126Padding
         */
        System.out.println("【1.4】AES_OFB模式");
        content = "線上助手";
        // 生成金鑰需要的密碼值
        key = "http://";
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_OFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_OFB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_OFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_OFB_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_OFB_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_OFB_PKCS5Padding);

```
####六、AES/PCBC 加密方式
下面是AES/PCBC/NoPadding,AES/PCBC/PKCS5Padding,AES/PCBC/ISO10126Padding 128位,192位,256位加加密解密
* 需要填充向量
```java
       /**
         * 1.5 AES/PCBC
         * AES/PCBC/NoPadding
         * AES/PCBC/PKCS5Padding
         * AES/PCBC/ISO10126Padding
         */
        System.out.println("【1.5】AES_PCBC模式");
        content = "線上助手";
        // 生成金鑰需要的密碼值
        key = "http://";
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_PCBC_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_PCBC_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_PCBC_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_PCBC_PKCS5Padding);
        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_PCBC_PKCS5Padding);
        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_PCBC_PKCS5Padding);
```

####七、完整程式碼
AESUtil .java

```java
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    /**
     * 線上助手|線上工具|線上生成|線上製作
     * http:///
     * 線上助手部落格
     * http:///blog/index
     */
    public class AESUtil {
        public static final String CHARSET = "UTF-8";
        private static byte[] encryptOrDecrypt(int mode,byte[] byteContent, String key,byte[] iv, AESType type, String modeAndPadding) throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            //此處解決mac,linux報錯
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            kgen.init(type.value, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance(modeAndPadding);// 建立密碼器
            if ( null !=iv ) {
                //指定一個初始化向量 (Initialization vector,IV), IV 必須是16位
                cipher.init(mode, keySpec, new IvParameterSpec(iv));
            } else {
                cipher.init(mode, keySpec);
            }
            byte[] result = cipher.doFinal(byteContent);
            return result;
        }
        public static void main(String[] args) throws Exception {
    //        System.out.println("【1】AES不指定模式和填充,預設為 ECB/PKCS5Padding,輸入可以不是16位元組,也不需要填充向量\n");
    //        // 需要加密的內容
    //        String content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        String key = "111";
    //        System.out.println("content: " + content + "\nkey: " + key);
    //        byte[] encodeByte;
    //        byte[] decodeByte;
    //        //預設方式  每次加密都不一樣,但是秘鑰是一樣的,所以解密還是一樣的
    //        // 內容加密後的值
    //        encodeByte = encrypt(content.getBytes(CHARSET), key, AESType.AES_128, EncodeType.AES_DEFAULT);
    //        String encodeStr = TypeConvert.bytesToHexString(encodeByte);
    //        // 被加密的內容解密後的值
    //        decodeByte = decrypt(encodeByte, key, AESType.AES_128, EncodeType.AES_DEFAULT);
    //        String decodeStr = new String(decodeByte,CHARSET);
    //        System.out.println("encode: " + encodeStr + "\ndecode: " + decodeStr);
    //
    //
    //        System.out.println("【2】AES_CBC_NoPadding模式,輸入必須是16*n位元組,需要填充向量\n");
    //        // 內容加密後的值
    //        //待加密內容不足16*n位 報錯javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    //        //需要填充向量,不然報錯java.security.InvalidKeyException: Parameters missing
    //        //得到加密後的內容先base64編碼再解碼再傳給解碼,不然直接轉回亂碼
    //        content = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈";
    //        encodeByte = encrypt(content.getBytes(CHARSET), key, AESType.AES_256, EncodeType.AES_CBC_NoPadding);
    //        encodeStr = TypeConvert.bytesToHexString(encodeByte);
    //        decodeByte = decrypt(TypeConvert.hexStringToBytes(encodeStr), key, AESType.AES_256, EncodeType.AES_CBC_NoPadding);
    //        decodeStr = new String(decodeByte,CHARSET);
    //        System.out.println("encode: " + encodeStr + "\ndecode: " + decodeStr);
            String content = "線上助手";
            // 生成金鑰需要的密碼值
            String key = "";
            byte[] encrypt;
            /**
             * AES加密方式一:AES不指定模式和填充,預設為 ECB/PKCS5Padding
             */
    //        System.out.println("【0】AES不指定模式和填充,預設為 ECB/PKCS5Padding,輸入可以不是16位元組,也不需要填充向量\n");
    //        //128
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_DEFAULT);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_DEFAULT);
    //        //192
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_DEFAULT);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_DEFAULT);
    //        //256
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_DEFAULT);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_DEFAULT);
    //        /**
    //         * 1.1 AES/CBC (需要填充向量16*n)
    //         * AES/CBC/NoPadding
    //         * AES/CBC/PKCS5Padding
    //         * AES/CBC/ISO10126Padding
    //         */
    //        System.out.println("【1.1】AES_CBC_NoPadding模式,需要填充向量,待加密必須是16*n");
    //        content = "線上助手線上助手線上助手線上助手";
    //        key = "";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);
    //        /**
    //         * 1.2 AES/CFB
    //         * AES/CBC/NoPadding
    //         * AES/CBC/PKCS5Padding
    //         * AES/CBC/ISO10126Padding
    //         */
    //        System.out.println("【1.2】AES_CFB_NoPadding模式\n");
    //        content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        key = "http://";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);
    //        /**
    //         * 1.2 AES/ECB
    //         * AES/ECB/NoPadding
    //         * AES/ECB/PKCS5Padding
    //         * AES/ECB/ISO10126Padding
    //         */
    //        System.out.println("【1.3】AES_ECB模式");
    //        content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        key = "http://";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_ECB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_ECB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_ECB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_ECB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_ECB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_ECB_PKCS5Padding);
            /**
             * 1.4 AES/OFB
             * AES/OFB/NoPadding
             * AES/OFB/PKCS5Padding
             * AES/OFB/ISO10126Padding
             */
            System.out.println("【1.4】AES_OFB模式");
            content = "線上助手";
            // 生成金鑰需要的密碼值
            key = "http://";
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_OFB_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_OFB_PKCS5Padding);
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_OFB_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_OFB_PKCS5Padding);
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_OFB_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_OFB_PKCS5Padding);
            /**
             * 1.5 AES/PCBC
             * AES/PCBC/NoPadding
             * AES/PCBC/PKCS5Padding
             * AES/PCBC/ISO10126Padding
             */
            System.out.println("【1.5】AES_PCBC模式");
            content = "線上助手";
            // 生成金鑰需要的密碼值
            key = "http://";
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_PCBC_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_PCBC_PKCS5Padding);
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_PCBC_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_PCBC_PKCS5Padding);
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_PCBC_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_PCBC_PKCS5Padding);
            //
    //        /**1.3 AES/CBC
    //         * AES_CBC_NoPadding模式(填充向量可選)
    //         */
            System.out.println("【1.3】AES_CBC_NoPadding模式");
            content = "線上助手線上助手線上助手線上助手";
            // 生成金鑰需要的密碼值
            key = "";
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_128,EncodeType.AES_CBC_NoPadding);
            content = "線上助手";
            // 生成金鑰需要的密碼值
            key = "";
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_192,EncodeType.AES_CBC_PKCS5Padding);
            encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);
            encryptOrdecrypt(false,encrypt,key,getIV(),AESType.AES_256,EncodeType.AES_CBC_ISO10126Padding);
    //
    //
    //
    //        /**
    //         * 2.1 AES/CFB 128/192/256位加解密
    //         * AES_CFB_NoPadding模式(填充向量可選)
    //         */
    //        System.out.println("【2.1】AES_CFB_NoPadding模式,需要填充向量\n");
    //        content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        key = "";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_CFB_NoPadding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_CFB_NoPadding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_CFB_NoPadding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_CFB_NoPadding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_CFB_NoPadding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_CFB_NoPadding);
    //
    //        /**
    //         * 2.2 AES/CFB
    //         * AES_CFB_NoPadding模式(填充向量可選)
    //         */
    //        System.out.println("【2.2】AES_CFB_NoPadding模式\n");
    //        content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        key = "";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_CFB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_CFB_PKCS5Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_CFB_PKCS5Padding);
    //
    //        /**2.3 AES/CFB
    //         * AES_CFB_NoPadding模式(填充向量可選)
    //         */
    //        System.out.println("【2.3】AES_CFB_NoPadding模式\n");
    //        content = "線上助手";
    //        // 生成金鑰需要的密碼值
    //        key = "";
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_128,EncodeType.AES_CFB_ISO10126Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_128,EncodeType.AES_CFB_ISO10126Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_192,EncodeType.AES_CFB_ISO10126Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_192,EncodeType.AES_CFB_ISO10126Padding);
    //        encrypt = encryptOrdecrypt(true,content.getBytes(CHARSET),key,null,AESType.AES_256,EncodeType.AES_CFB_ISO10126Padding);
    //        encryptOrdecrypt(false,encrypt,key,null,AESType.AES_256,EncodeType.AES_CFB_ISO10126Padding);
        }
        /**
         *
         * @param isEncrypt
         * @param source
         * @param key
         * @param type
         * @param encodeType
         */
        public static byte[] encryptOrdecrypt(boolean isEncrypt,byte[] source,String key,byte[] iv,AESType type,String encodeType) throws UnsupportedEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
            if (isEncrypt){
                byte[] encodeByte = encryptOrDecrypt(Cipher.ENCRYPT_MODE,source,key,iv,type,encodeType);
                String encodeStr = TypeConvert.bytesToHexString(encodeByte);
                return encodeByte;
            }else{
                byte[] decodeByte = encryptOrDecrypt(Cipher.DECRYPT_MODE,source, key,iv,type, encodeType);
                String decodeStr = new String(decodeByte,CHARSET);
                return decodeByte;
            }
        }
        /**
         * 指定一個初始化向量 (Initialization vector,IV),IV 必須是16位
         */
        public static final byte[] getIV() throws Exception {
            return "1234567812345678".getBytes(CHARSET);
        }
```

EncodeType

```java
/**
 * 線上助手|線上工具|線上生成|線上製作
 * http:///
 * 線上助手部落格
 * http:///blog/index
 */
public class EncodeType {
//    演算法/模式/填充                 16位元組加密後資料長度       不滿16位元組加密後長度
//    AES/CBC/NoPadding                   16                          不支援
//    AES/CBC/PKCS5Padding                32                          16
//    AES/CBC/ISO10126Padding             32                          16
//    AES/CFB/NoPadding                   16                          原始資料長度
//    AES/CFB/PKCS5Padding                32                          16
//    AES/CFB/ISO10126Padding             32                          16
//    AES/ECB/NoPadding                   16                          不支援
//    AES/ECB/PKCS5Padding                32                          16
//    AES/ECB/ISO10126Padding             32                          16
//    AES/OFB/NoPadding                   16                          原始資料長度
//    AES/OFB/PKCS5Padding                32                          16
//    AES/OFB/ISO10126Padding             32                          16
//    AES/PCBC/NoPadding                  16                          不支援
//    AES/PCBC/PKCS5Padding               32                          16
//    AES/PCBC/ISO10126Padding            32                          16
    //預設為 ECB/PKCS5Padding
    public final static String AES_DEFAULT = "AES";
    public final static String AES_CBC_NoPadding = "AES/CBC/NoPadding";
    public final static String AES_CBC_PKCS5Padding = "AES/CBC/PKCS5Padding";
    public final static String AES_CBC_ISO10126Padding = "AES/CBC/ISO10126Padding";
    public final static String AES_CFB_NoPadding = "AES/CFB/NoPadding";
    public final static String AES_CFB_PKCS5Padding = "AES/CFB/PKCS5Padding";
    public final static String AES_CFB_ISO10126Padding = "AES/CFB/ISO10126Padding";
    public final static String AES_ECB_NoPadding = "AES/ECB/NoPadding";
    public final static String AES_ECB_PKCS5Padding = "AES/ECB/PKCS5Padding";
    public final static String AES_ECB_ISO10126Padding = "AES/ECB/ISO10126Padding";
    public final static String AES_OFB_NoPadding = "AES/OFB/NoPadding";
    public final static String AES_OFB_PKCS5Padding = "AES/OFB/PKCS5Padding";
    public final static String AES_OFB_ISO10126Padding = "AES/OFB/ISO10126Padding";
    public final static String AES_PCBC_NoPadding = "AES/PCBC/NoPadding";
    public final static String AES_PCBC_PKCS5Padding = "AES/PCBC/PKCS5Padding";
    public final static String AES_PCBC_ISO10126Padding = "AES/PCBC/ISO10126Padding";
}
```

TypeConvert

```java
    /**
     * 線上助手|線上工具|線上生成|線上製作
     * http:///
     * 線上助手部落格
     * http:///blog/index
     */
    public class TypeConvert {
        /**
         * 字串轉換成十六進位制字串
         */
        public static String str2HexStr(String str) {
            char[] chars = "0123456789ABCDEF".toCharArray();
            StringBuilder sb = new StringBuilder("");
            byte[] bs = str.getBytes();
            int bit;
            for (int i = 0; i < bs.length; i++) {
                bit = (bs[i] & 0x0f0) >> 4;
                sb.append(chars[bit]);
                bit = bs[i] & 0x0f;
                sb.append(chars[bit]);
            }
            return sb.toString();
        }
        /**
         * Convert hex string to byte[]
         *
         * @param hexString the hex string
         * @return byte[]
         */
        public static byte[] hexStringToBytes(String hexString) {
            if (hexString == null || hexString.equals("")) {
                return null;
            }
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];
            for (int i = 0; i < length; i++) {
                int pos = i * 2;
                d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
            return d;
        }
        /**
         * Convert char to byte
         *
         * @param c char
         * @return byte
         */
        private static byte charToByte(char c) {
            return (byte) "0123456789ABCDEF".indexOf(c);
        }
        /**
         * 陣列轉換成十六進位制字串
         * @param bArray byte[]
         * @return HexString
         */
        public static final String bytesToHexString(byte[] bArray) {
            if (bArray == null || bArray.length==0){
                return null;
            }
            StringBuffer sb = new StringBuffer(bArray.length);
            String sTemp;
            for (int i = 0; i < bArray.length; i++) {
                sTemp = Integer.toHexString(0xFF & bArray[i]);
                if (sTemp.length() < 2){
                    sb.append(0);
                }
                sb.append(sTemp.toUpperCase());
            }
            return sb.toString();
        }
        /**
         * 十六進位制字串轉換成字串
         * @param hexStr
         * @return String
         */
        public static String hexStr2Str(String hexStr) {
            String str = "0123456789ABCDEF";
            char[] hexs = hexStr.toCharArray();
            byte[] bytes = new byte[hexStr.length() / 2];
            int n;
            for (int i = 0; i < bytes.length; i++) {
                n = str.indexOf(hexs[2 * i]) * 16;
                n += str.indexOf(hexs[2 * i + 1]);
                bytes[i] = (byte) (n & 0xff);
            }
            return new String(bytes);
        }
        /**
         * @param hexString String str = "000AB"
         * @return
         */
        public static int hexString2Int(String hexString){
            Integer num = Integer.valueOf(hexString,16);
            return num;
        }
        /**
         * 把byte轉為字串的bit
         */
        public static String byteToBitString(byte b) {
            return ""
                    + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                    + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                    + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                    + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
        }
        /**
         * 把byte轉為字串陣列的bit
         */
        public static String[] byteToBitStrings(byte b) {
            String[] bit = new String[8];
            bit[0] = ""+ (byte) ((b >> 7) & 0x1);
            bit[1] = ""+ (byte) ((b >> 6) & 0x1);
            bit[2] = ""+ (byte) ((b >> 5) & 0x1);
            bit[3] = ""+ (byte) ((b >> 4) & 0x1);
            bit[4] = ""+ (byte) ((b >> 3) & 0x1);
            bit[5] = ""+ (byte) ((b >> 2) & 0x1);
            bit[6] = ""+ (byte) ((b >> 1) & 0x1);
            bit[7] = ""+ (byte) ((b >> 0) & 0x1);
            return bit;
        }
        public static void main(String[] args){
            String hexString = "3A60432A5C01211F291E0F4E0C132825";
            byte[] result = hexStringToBytes(hexString);
            System.out.println(new String(result));
            System.out.println(bytesToHexString(result));
        }
        //base64字串轉byte[]
        public static byte[] base64String2ByteFun(String base64Str){
            return Base64.decodeBase64(base64Str);
        }
        //byte[]轉base64
        public static String byte2Base64StringFun(byte[] b){
            return Base64.encodeBase64String(b);
        }
    }
```

AESType

```java
    /**
     * 線上助手|線上工具|線上生成|線上製作
     * http:///
     * 線上助手部落格
     * http:///blog/index
     */
    enum AESType {
        AES_128(128), AES_192(192), AES_256(256);
        public int value;
        private AESType(int value) {
            this.value = value;
        }
        public int getValue() {
            return value;
        }
        public void setValue(int value) {
            this.value = value;
        }
    }
```

轉載請註明來自 ,原文連結:http:///blog/web/201805211243

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28470105/viewspace-2155129/,如需轉載,請註明出處,否則將追究法律責任。

相關文章