Android aes encryption pad block corrupted

匿名 (未验证) 提交于 2019-12-03 01:17:01

问题:

I am using the methods below and if I enter the right key everything works fine. But if I enter a wrong key I am receiving a BadPaddingException:pad block corrupted... Am I doing something wrong?

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); } 

回答1:

You're not doing anything wrong. It's expected. This is technically a duplicate of Java Encryption issue (which doesn't seem to be easy to find). See this answer for a good explanation. You can consider adding a MAC (Message Authentication Code) to safely accomplish something more like a checksum.



回答2:

Other than supplying the wrong key, I don't think so :)

A stack trace would help, so we can see which function is throwing the BadPaddingException.

This may well be because the 'bad' key is a different length to the 'good' key - does the 'bad' key come out of initKey() or somewhere else?

Best wishes,

Phil Lello



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!