2013-02-14 77 views
2

我在Android和Java servlet環境中都使用了AES加密和充氣城堡實現。兩種情況下的加密部分均可用。但是,一旦我使用相同的密鑰對相同的文本進行加密,對於這兩個平臺我會得到不同的結果AES密文不同

我的意圖是在Android中進行加密並在Web環境中進行解密。

這是我爲Android AES實現完成的唯一更改。

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
    SecureRandom sr = null; 
    if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) { 
     sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); 
    } else { 
     sr = SecureRandom.getInstance("SHA1PRNG"); 
    } 
    sr.setSeed(key); 
    kgen.init(128, sr); 
    SecretKey skey = kgen.generateKey(); 
    byte[] raw = skey.getEncoded(); 

上面我只是將Crypto添加到get實例中。

我使用海綿城堡實現以及我是否可以完成此操作。儘管如此,它給了我和Android一樣的結果。不知道我是否已經正確加載它。我在API級別14和17上對此進行了測試。

這導致javax.crypto.BadPaddingException:pad block損壞。

+1

不要使用SecureRandom的做到這一點。這是錯誤的。 – kroot 2013-02-15 04:17:34

+0

那我應該怎麼用呢? – Dilshan 2013-02-15 05:48:50

+0

除非您發佈Android部分的加密代碼和servlet部分的解密代碼,否則我們無法看到您的錯誤。您提供的密鑰生成代碼是無關緊要的。 – 2013-02-15 08:05:22

回答

4

對於任何引用此線程的人來說,這是我對我的代碼所作的更改。現在它在Android和服務器環境中運行良好。

的回答是從採取

Android 4.2 broke my encrypt/decrypt code and the provided solutions don't work

感謝@kroot

/* Store these things on disk used to derive key later: */ 
    int iterationCount = 1000; 
    int saltLength = 32; // bytes; should be the same size as the output 
          // (256/8 = 32) 
    int keyLength = 256; // 256-bits for AES-256, 128-bits for AES-128, etc 
    byte[] salt = new byte[saltLength]; // Should be of saltLength 

    /* When first creating the key, obtain a salt with this: */ 
    SecureRandom random = new SecureRandom(); 
    random.nextBytes(salt); 

    /* Use this to derive the key from the password: */ 
    KeySpec keySpec = new PBEKeySpec(new String(key, 
      Constants.CHAR_ENCODING).toCharArray(), key, iterationCount, 
      keyLength); 
    SecretKeyFactory keyFactory = SecretKeyFactory 
      .getInstance("PBEWithSHA256And256BitAES-CBC-BC"); 
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); 
    SecretKey secretKey = new SecretKeySpec(keyBytes, "AES"); 

    return secretKey.getEncoded();