Android aes加密垫块损坏

时间:2011-04-12 14:05:42

标签: android encryption aes

我正在使用下面的方法,如果我输入正确的密钥,一切正常。 但是,如果我输入错误的密钥,我收到BadPaddingException:pad block corrupted ... 难道我做错了什么?

public  void initKey(String passwd, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{

    byte[] localsalt = salt; 
   PBEKeySpec password = new PBEKeySpec(passwd.toCharArray(),localsalt, 1024,128);//, localsalt, 1000, 128);  //128bit enc aes
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5And128BitAES-CBC-OpenSSL","BC");  
   PBEKey key = (PBEKey) factory.generateSecret(password);  
   encKey = new SecretKeySpec(key.getEncoded(), "AES");
}


public   String txt2enc(String etxt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

       final Cipher cipher = Cipher.getInstance("AES");//AES       
       cipher.init(Cipher.ENCRYPT_MODE, encKey);      

       byte[] encrypted = cipher.doFinal((etxt).getBytes("UTF-8"));
       return Base64.encodeToString(encrypted, 0);
}

//decryption
public  String txt2dec(String dtxt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{

    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, encKey);
    byte[] decrypt = cipher.doFinal(Base64.decode(dtxt, 0));
    return new String(decrypt);//return Base64.encodeToString(decrypt, 0);
}

2 个答案:

答案 0 :(得分:5)

你没有做错任何事。这是预期的。这在技术上是Java Encryption issue的副本(似乎不容易找到)。有关详细说明,请参阅此answer。您可以考虑添加MAC(消息验证代码)以安全地完成更像校验和的操作。

答案 1 :(得分:0)

除了提供错误的密钥外,我不这么认为:)

堆栈跟踪会有所帮助,因此我们可以看到哪个函数抛出BadPaddingException。

这很可能是因为“坏”和“坏”。密钥与“好”的长度不同。关键 - “坏”' key来自initKey()还是其他地方?

祝福,

Phil Lello