2013-02-14 75 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();