1. 程式人生 > >Android中AES加密解密。解決密文不唯一、解密不出明文問題

Android中AES加密解密。解決密文不唯一、解密不出明文問題

AES加密方式是目前來看值得選擇的加密方式,但是在Android中使用AES加密時,有些坑看似不大,卻讓很多人栽了跟頭。
Android 4.2之後SHA1PRNG強隨意種子演算法呼叫不同,需要區別呼叫,這個你造嗎。
下面貼出部分關鍵程式碼,程式碼與網路上普遍存在的AES加密程式碼大同小異,不做過多解釋。但是解決了那些大部分程式碼中存在的密文不唯一、解密不出明文的問題。

AESCrypt.java中關鍵程式碼

public byte[] getRawKey(byte[] seed) throws Exception {     
        KeyGenerator kgen = KeyGenerator.getInstance("AES"
); // SHA1PRNG 強隨機種子演算法, 要區別4.2以上版本的呼叫方法 SecureRandom sr = null; if (android.os.Build.VERSION.SDK_INT >= 17) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } sr.setSeed(seed); kgen.init(AESUtil.ENCRYPT_BITS, sr); //256 bits or 128 bits,192 bits
SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } public byte[] encrypting(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"
); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } public byte[] decrypting(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; }

對外封裝的AESUtil.java

    /**
     * 設定編碼位數。可選值為:256、192、128
     * @param encryptBits
     */
    public void setEncryptBits(int encryptBits){
        if(encryptBits==256||encryptBits==192||encryptBits==128){
            ENCRYPT_BITS = encryptBits;
        }
    }

    public String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = mAESCrypt.getRawKey(seed.getBytes());
        byte[] result = mAESCrypt.encrypting(rawKey, cleartext.getBytes());
        return mAESCrypt.toHex(result);
    }

    public String decrypt(String seed, String encrypted) throws Exception {
        byte[] rawKey = mAESCrypt.getRawKey(seed.getBytes());
        byte[] encryptedstr = mAESCrypt.toByte(encrypted);
        byte[] result = mAESCrypt.decrypting(rawKey, encryptedstr);
        return new String(result);
    }

更多Android開發技術一起探討學習,點我

更多Android開發資源直接下載,點我