Android AES 加密和解密

AES:高級加密標準(英語:Advanced Encryption Standard,縮寫:AES),在密碼學中又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣爲全世界所使用。

那麼爲什麼原來的DES會被取代呢?原因就在於其使用56位密鑰,比較容易被破解。而AES可以使用128、192、和256位密鑰,並且用128位分組加密和解密數據,相對來說安全很多。完善的加密算法在理論上是無法破解的,除非使用窮盡法。使用窮盡法破解密鑰長度在128位以上的加密數據是不現實的,僅存在理論上的可能性。統計顯示,即使使用目前世界上運算速度最快的計算機,窮盡128位密鑰也要花上幾十億年的時間,更不用說去破解採用256位密鑰長度的AES算法了。

目前世界上還有組織在研究如何攻破AES這堵堅厚的牆,但是因爲破解時間太長,AES得到保障,但是所用的時間不斷縮小。隨着計算機計算速度的增快,新算法的出現,AES遭到的攻擊只會越來越猛烈,不會停止的。AES現在廣泛用於金融財務、在線交易、無線通信、數字存儲等領域,經受了最嚴格的考驗,但說不定哪天就會步DES的後塵。

 

AES加密和解密

/**
 * @author Evloution_
 * @date 2018/9/5
 * @explain AES 的加密和解密
 */
public class AESEncryptUtil {

    /**
     * AES加密字符串
     * @param content  需要被加密的字符串
     * @param password  加密需要的密碼
     * @return  密文
     */
    public static byte[] encrypt(String content, String password) {
        try {
            // 創建 AES 的 key 生產者
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            // 利用用戶密碼作爲隨機數初始化出128位的key生產者。SecureRandom 是生產安全隨機數序列,password.getBytes()是種子
            // 只要種子相同,序列就一樣,所以解密只要有password就行
            keyGenerator.init(128, new SecureRandom(password.getBytes()));
            // 根據用戶密碼生成一個密鑰
            SecretKey secretKey = keyGenerator.generateKey();
            // 返回基本編碼格式的密鑰。如果此密鑰不支持編碼,則返回null
            byte[] enCodeFormat = secretKey.getEncoded();
            // 轉換爲 AES 專用密鑰
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat,"AES");
            // 創建密碼器
            Cipher cipher = Cipher.getInstance("AES");

            byte[] byteContent = content.getBytes("UTF-8");
            // 初始化爲加密模式的密碼器
            cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
            // 加密
            byte[] result = cipher.doFinal(byteContent);

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  解密AES加密過的字符串
     * @param content  AES加密過過的內容
     * @param password  加密時的密碼
     * @return  明文
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            // 創建 AES 的 key 生產者
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            // 利用用戶密碼作爲隨機數初始化出128位的key生產者。SecureRandom 是生產安全隨機數序列,password.getBytes()是種子
            // 只要種子相同,序列就一樣,所以解密只要有password就行
            keyGenerator.init(128, new SecureRandom(password.getBytes()));
            // 根據用戶密碼生成一個密鑰
            SecretKey secretKey = keyGenerator.generateKey();
            // 返回基本編碼格式的密鑰。如果此密鑰不支持編碼,則返回null
            byte[] enCodeFormat = secretKey.getEncoded();
            // 轉換爲 AES 專用密鑰
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat,"AES");
            // 創建密碼器
            Cipher cipher = Cipher.getInstance("AES");

            // 初始化爲加密模式的密碼器
            cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
            // 加密
            byte[] result = cipher.doFinal(content);
            // 返回明文
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }  catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
}

詳解見註釋。

 

如果直接輸出加密後的內容是一個亂碼。我們需要把它的進制轉換一下。

16進制和二進制的相互轉換

/**
 * @author Evloution_
 * @date 2018/9/5
 * @explain 進制轉換工具類
 */
public class ParseSystemUtil {

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

    /**
     * 將16進制轉換爲二進制
     * @param hexStr
     * @return
     */
    public static byte[] hexParseByte2(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 void main(String[] args) {
        String content = "你好,未來!";
        String password = "123";
        System.out.println("加密之前:" + content);
        // 加密
        byte[] encrypt = AesTest.encrypt(content, password);
        System.out.println("加密後的內容:" + new String(encrypt));
        
        //如果想要加密內容不顯示亂碼,可以先將密文轉換爲16進制
        String hexStrResult = ParseSystemUtil.parseByte2HexStr(encrypt);
        System.out.println("16進制的密文:"  + hexStrResult);
        
        //如果的到的是16進制密文,別忘了先轉爲2進制再解密
        byte[] twoStrResult = ParseSystemUtil.parseHexStr2Byte(hexStrResult);
                
        // 解密
        byte[] decrypt = AesTest.decrypt(encrypt, password);
        System.out.println("解密後的內容:" + new String(decrypt));    
    }

輸出內容:

加密之前:你好,未來!
加密後的內容:P�d�g�K�3�g�����,Ꝏ?U納�
16進制的密文:50FE6401E867A34BD533FE67BB85EDABFED62CEA9C8E3F5516E7B48D01F21A5F
解密後的內容:你好,未來!

 

參考:https://www.cnblogs.com/vmax-tam/p/4624032.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章