AES加、解密

Android端

public class EncryptUtil {
    static Boolean b = true;

    // 注意: 這里的password(秘鑰必須是16位的)
    public static final String keyBytes = "3epj7jhny345mwe2";
    //    public static final String keyBytes = "test7jhny345mwe2";

    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;

    private static void init() {
        try {
            /**
             * 為指定算法生成一個(gè) KeyGenerator 對(duì)象。 此類提供(對(duì)稱)密鑰生成器的功能。 密鑰生成器是使用此類的某個(gè)
             * getInstance 類方法構(gòu)造的。 KeyGenerator 對(duì)象可重復(fù)使用,也就是說,在生成密鑰后, 可以重復(fù)使用同一
             * KeyGenerator 對(duì)象來生成進(jìn)一步的密鑰。 生成密鑰的方式有兩種:與算法無(wú)關(guān)的方式,以及特定于算法的方式。
             * 兩者之間的惟一不同是對(duì)象的初始化: 與算法無(wú)關(guān)的初始化 所有密鑰生成器都具有密鑰長(zhǎng)度 和隨機(jī)源 的概念。 此
             * KeyGenerator 類中有一個(gè) init 方法,它可采用這兩個(gè)通用概念的參數(shù)。 還有一個(gè)只帶 keysize 參數(shù)的
             * init 方法, 它使用具有最高優(yōu)先級(jí)的提供程序的 SecureRandom 實(shí)現(xiàn)作為隨機(jī)源 (如果安裝的提供程序都不提供
             * SecureRandom 實(shí)現(xiàn),則使用系統(tǒng)提供的隨機(jī)源)。 此 KeyGenerator 類還提供一個(gè)只帶隨機(jī)源參數(shù)的 inti
             * 方法。 因?yàn)檎{(diào)用上述與算法無(wú)關(guān)的 init 方法時(shí)未指定其他參數(shù),
             * 所以由提供程序決定如何處理將與每個(gè)密鑰相關(guān)的特定于算法的參數(shù)(如果有)。 特定于算法的初始化
             * 在已經(jīng)存在特定于算法的參數(shù)集的情況下, 有兩個(gè)具有 AlgorithmParameterSpec 參數(shù)的 init 方法。
             * 其中一個(gè)方法還有一個(gè) SecureRandom 參數(shù), 而另一個(gè)方法將已安裝的高優(yōu)先級(jí)提供程序的 SecureRandom
             * 實(shí)現(xiàn)用作隨機(jī)源 (或者作為系統(tǒng)提供的隨機(jī)源,如果安裝的提供程序都不提供 SecureRandom 實(shí)現(xiàn))。
             * 如果客戶端沒有顯式地初始化 KeyGenerator(通過調(diào)用 init 方法), 每個(gè)提供程序必須提供(和記錄)默認(rèn)初始化。
             */
            keyGen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 初始化此密鑰生成器,使其具有確定的密鑰長(zhǎng)度。
        keyGen.init(128); // 128位的AES加密
        try {
            // 生成一個(gè)實(shí)現(xiàn)指定轉(zhuǎn)換的 Cipher 對(duì)象。
            cipher = Cipher.getInstance(algorithmStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        // 標(biāo)識(shí)已經(jīng)初始化過了的字段
        isInited = true;
    }

    private static byte[] genKey() {
        if (!isInited) {
            init();
        }
        // 首先 生成一個(gè)密鑰(SecretKey),
        // 然后,通過這個(gè)秘鑰,返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回 null。
        return keyGen.generateKey().getEncoded();
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) {
        byte[] encryptedText = null;
        if (!isInited) {
            init();
        }
        /**
         * 類 SecretKeySpec 可以使用此類來根據(jù)一個(gè)字節(jié)數(shù)組構(gòu)造一個(gè) SecretKey, 而無(wú)須通過一個(gè)(基于 provider
         * 的)SecretKeyFactory。 此類僅對(duì)能表示為一個(gè)字節(jié)數(shù)組并且沒有任何與之相關(guān)聯(lián)的鑰參數(shù)的原始密鑰有用
         * 構(gòu)造方法根據(jù)給定的字節(jié)數(shù)組構(gòu)造一個(gè)密鑰。 此構(gòu)造方法不檢查給定的字節(jié)數(shù)組是否指定了一個(gè)算法的密鑰。
         */
        Key key = new SecretKeySpec(keyBytes, "AES");
        try {
            // 用密鑰初始化此 cipher。
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        try {
            // 按單部分操作加密或解密數(shù)據(jù),或者結(jié)束一個(gè)多部分操作。(不知道神馬意思)
            encryptedText = cipher.doFinal(content);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password != null) {
            rByte = password.getBytes();
        } else {
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 將二進(jìn)制轉(zhuǎn)換成16進(jìn)制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 將16進(jìn)制轉(zhuǎn)換為二進(jìn)制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密
     */
    public static String encode(String content) {
        // 加密之后的字節(jié)數(shù)組,轉(zhuǎn)成16進(jìn)制的字符串形式輸出
        if (!b) {
            return content;
        }
        return parseByte2HexStr(encrypt(content, keyBytes));
    /*    String str=parseByte2HexStr(encrypt(content, keyBytes));
        try {
            return MD5.MD5_16bit(str)+parseByte2HexStr(encrypt(content, keyBytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }*/
        //  return null;
    }

    /**
     * 解密
     */
    public static String decode(String content) {
        if (!b) {
            return content;
        }
        // 解密之前,先將輸入的字符串按照16進(jìn)制轉(zhuǎn)成二進(jìn)制的字節(jié)數(shù)組,作為待解密的內(nèi)容輸入
        byte[] b = decrypt(parseHexStr2Byte(content), keyBytes);
        return new String(b);
    }

    // 測(cè)試用例
    public static void test1() {
        String content = "hello abcdefggsdfasdfasdf";
        String pStr = encode(content);
        System.out.println("加密前:" + content);
        System.out.println("加密后:" + pStr);

        String postStr = decode(pStr);
        System.out.println("解密后:" + postStr);
    }

    public static void main(String[] args) {
        test1();
    }
}

JAVA端

public class A {

    // private static final Log log = LogFactory.getLog(HttpClientUtil.class);
    // private static final Propertie pe=new Propertie();
    /*private static String aeskey=pe.getAeskey();
    private static String edswitch=pe.getEdswitch();*/
    
    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;
    
    // 注意: 這里的password(秘鑰必須是16位的)
    private static final String keyBytes = "1234567890abcdef";

    private static void init() {
        try {
            /**
             * 為指定算法生成一個(gè) KeyGenerator 對(duì)象。 此類提供(對(duì)稱)密鑰生成器的功能。 密鑰生成器是使用此類的某個(gè)
             * getInstance 類方法構(gòu)造的。 KeyGenerator 對(duì)象可重復(fù)使用,也就是說,在生成密鑰后, 可以重復(fù)使用同一
             * KeyGenerator 對(duì)象來生成進(jìn)一步的密鑰。 生成密鑰的方式有兩種:與算法無(wú)關(guān)的方式,以及特定于算法的方式。
             * 兩者之間的惟一不同是對(duì)象的初始化: 與算法無(wú)關(guān)的初始化 所有密鑰生成器都具有密鑰長(zhǎng)度 和隨機(jī)源 的概念。 此
             * KeyGenerator 類中有一個(gè) init 方法,它可采用這兩個(gè)通用概念的參數(shù)。 還有一個(gè)只帶 keysize 參數(shù)的
             * init 方法, 它使用具有最高優(yōu)先級(jí)的提供程序的 SecureRandom 實(shí)現(xiàn)作為隨機(jī)源 (如果安裝的提供程序都不提供
             * SecureRandom 實(shí)現(xiàn),則使用系統(tǒng)提供的隨機(jī)源)。 此 KeyGenerator 類還提供一個(gè)只帶隨機(jī)源參數(shù)的 inti
             * 方法。 因?yàn)檎{(diào)用上述與算法無(wú)關(guān)的 init 方法時(shí)未指定其他參數(shù),
             * 所以由提供程序決定如何處理將與每個(gè)密鑰相關(guān)的特定于算法的參數(shù)(如果有)。 特定于算法的初始化
             * 在已經(jīng)存在特定于算法的參數(shù)集的情況下, 有兩個(gè)具有 AlgorithmParameterSpec 參數(shù)的 init 方法。
             * 其中一個(gè)方法還有一個(gè) SecureRandom 參數(shù), 而另一個(gè)方法將已安裝的高優(yōu)先級(jí)提供程序的 SecureRandom
             * 實(shí)現(xiàn)用作隨機(jī)源 (或者作為系統(tǒng)提供的隨機(jī)源,如果安裝的提供程序都不提供 SecureRandom 實(shí)現(xiàn))。
             * 如果客戶端沒有顯式地初始化 KeyGenerator(通過調(diào)用 init 方法), 每個(gè)提供程序必須提供(和記錄)默認(rèn)初始化。
             */
            keyGen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 初始化此密鑰生成器,使其具有確定的密鑰長(zhǎng)度。
        keyGen.init(128); // 128位的AES加密
        try {
            // 生成一個(gè)實(shí)現(xiàn)指定轉(zhuǎn)換的 Cipher 對(duì)象。
            cipher = Cipher.getInstance(algorithmStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        // 標(biāo)識(shí)已經(jīng)初始化過了的字段
        isInited = true;
    }

    private static byte[] genKey() {
        if (!isInited) {
            init();
        }
        // 首先 生成一個(gè)密鑰(SecretKey),
        // 然后,通過這個(gè)秘鑰,返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回 null。
        return keyGen.generateKey().getEncoded();
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) {
        byte[] encryptedText = null;
        if (!isInited) {
            init();
        }
        /**
         * 類 SecretKeySpec 可以使用此類來根據(jù)一個(gè)字節(jié)數(shù)組構(gòu)造一個(gè) SecretKey, 而無(wú)須通過一個(gè)(基于 provider
         * 的)SecretKeyFactory。 此類僅對(duì)能表示為一個(gè)字節(jié)數(shù)組并且沒有任何與之相關(guān)聯(lián)的鑰參數(shù)的原始密鑰有用
         * 構(gòu)造方法根據(jù)給定的字節(jié)數(shù)組構(gòu)造一個(gè)密鑰。 此構(gòu)造方法不檢查給定的字節(jié)數(shù)組是否指定了一個(gè)算法的密鑰。
         */
        Key key = new SecretKeySpec(keyBytes, "AES");
        try {
            // 用密鑰初始化此 cipher。
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        try {
            // 按單部分操作加密或解密數(shù)據(jù),或者結(jié)束一個(gè)多部分操作。(不知道神馬意思)
            encryptedText = cipher.doFinal(content);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);// algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key);// ?
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password != null) {
            rByte = password.getBytes();
        } else {
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 將二進(jìn)制轉(zhuǎn)換成16進(jìn)制
     * 
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 將16進(jìn)制轉(zhuǎn)換為二進(jìn)制
     * 
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    

    /**
     * 加密
     */
    public static String encode(String content) {
        // 加密之后的字節(jié)數(shù)組,轉(zhuǎn)成16進(jìn)制的字符串形式輸出
        return parseByte2HexStr(encrypt(content, keyBytes));
    }

    /**
     * 解密
     */
    public static String decode(String content) {
        // 解密之前,先將輸入的字符串按照16進(jìn)制轉(zhuǎn)成二進(jìn)制的字節(jié)數(shù)組,作為待解密的內(nèi)容輸入
        byte[] b = decrypt(parseHexStr2Byte(content), keyBytes);
        return new String(b);
    }

    // 測(cè)試用例
    public static void test1() {
        String content = "hengks和人們";
    
        String pStr = encode(content);
        System.out.println("加密前:" + content);
        System.out.println("加密后:" + pStr);

        String postStr = decode(pStr);
        System.out.println("解密后:" + postStr);
    }

    public static void main(String[] args) {
        test1();
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容