用Java實現AES加密


參考內容來自:http://blog.csdn.net/hbcui1984/article/details/5201247

 

一)什么是AES?

高級加密標准(英語:Advanced Encryption Standard,縮寫:AES),是一種區塊加密標准。這個標准用來替代原先的DES,已經被多方分析且廣為全世界所使用。

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

目前世界上還有組織在研究如何攻破AES這堵堅厚的牆,但是因為破解時間太長,AES得到保障,但是所用的時間不斷縮小。隨着計算機計算速度的增快,新算法的出現,AES遭到的攻擊只會越來越猛烈,不會停止的。

AES現在廣泛用於金融財務、在線交易、無線通信、數字存儲等領域,經受了最嚴格的考驗,但說不定哪天就會步DES的后塵。

 

二)JAES加密

先來一段加密代碼,說明請看注釋:

    /**
     * AES加密字符串
     * 
     * @param content
     *            需要被加密的字符串
     * @param password
     *            加密需要的密碼
     * @return 密文
     */
    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者

            kgen.init(128, new SecureRandom(password.getBytes()));// 利用用戶密碼作為隨機數初始化出
                                                                    // 128位的key生產者
            //加密沒關系,SecureRandom是生成安全隨機數序列,password.getBytes()是種子,只要種子相同,序列就一樣,所以解密只要有password就行

            SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰

            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回
                                                            // null。

            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰

            Cipher cipher = Cipher.getInstance("AES");// 創建密碼器

            byte[] byteContent = content.getBytes("utf-8");

            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化為加密模式的密碼器

            byte[] result = cipher.doFinal(byteContent);// 加密

            return result;

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

 

三)AES解密

    /**
     * 解密AES加密過的字符串
     * 
     * @param content
     *            AES加密過過的內容
     * @param password
     *            加密時的密碼
     * @return 明文
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
            Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
            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;
    }

 

四)測試

    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));
        
        // 解密
        byte[] decrypt = AesTest.decrypt(encrypt, password);
        System.out.println("解密后的內容:" + new String(decrypt));        
    }

 

輸出結果:

加密之前:美女,約嗎?
加密后的內容:P�d�g�K�3�g�����,Ꝏ?U納�
解密后的內容:美女,約嗎?

 

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

 

五)進制轉換

進制轉換的工具類:

/**
 * 進制轉換工具類
 * @author tanjierong
 *
 */
public class ParseSystemUtil {

    /**將二進制轉換成16進制 
     * @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進制轉換為二進制 
     * @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 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進制的密文:50FE6401E867A34BD533FE67BB85EDABFED62CEA9D8E3F5516E7B48D01F21A5F
解密后的內容:美女,約嗎?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM