Android加密“pad block corrupted”exception
在此代码中,此行导致exception:
clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT));
javax.crypto.BadPaddingException: pad block corrupted
我从以下代码获得了代码: http : //www.techrepublic.com/blog/software-engineer/attention-android-developers-keep-user-data-safe/
有任何想法吗?
private String decrypt (String encryptedText) { byte[] clearText = null; try { SecretKeySpec ks = new SecretKeySpec(getKey(), "AES"); Cipher c = Cipher.getInstance("AES"); c.init(Cipher.DECRYPT_MODE, ks); clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT)); return new String(clearText, "UTF-8"); } catch (Exception e) { return null; } }
细节:我也在android上加密它
owlstead的建议很有帮助,但在这种情况下使用代码时
注意Android开发人员:保持用户数据安全http://www.techrepublic.com/blog/software-engineer/attention-android-developers-keep-user-data-safe/
我对代码做了一些更改,可能对将来的其他人有所帮助。 我完全删除了getkey方法。
private static String seed; /** * Encrypts the text. * @param clearText The text you want to encrypt * @return Encrypted data if successful, or null if unsucessful */ protected String encrypt(String clearText) { byte[] encryptedText = null; try { byte[] keyData = seed.getBytes(); SecretKey ks = new SecretKeySpec(keyData, "AES"); Cipher c = Cipher.getInstance("AES"); c.init(Cipher.ENCRYPT_MODE, ks); encryptedText = c.doFinal(clearText.getBytes("UTF-8")); return Base64.encodeToString(encryptedText, Base64.DEFAULT); } catch (Exception e) { return null; } } /** * Decrypts the text * @param encryptedText The text you want to encrypt * @return Decrypted data if successful, or null if unsucessful */ protected String decrypt (String encryptedText) { byte[] clearText = null; try { byte[] keyData = seed.getBytes(); SecretKey ks = new SecretKeySpec(keyData, "AES"); Cipher c = Cipher.getInstance("AES"); c.init(Cipher.DECRYPT_MODE, ks); clearText = c.doFinal(Base64.decode(encryptedText, Base64.DEFAULT)); return new String(clearText, "UTF-8"); } catch (Exception e) { return null; } }
Java + Android + Encryption + Exception通常意味着一件事,有人再次使用SecureRandom
类作为密钥派生函数。 当"SHA1PRNG"
的SecureRandom
实现与Sun在Java SE中的实现不同时,这会失败。 特别是如果将种子添加到随机数发生器的状态而不是将种子用作PRNG的起始点。
基本上,只需使用SecretKey aesKey = new SecretKeySpec(byte[] keyData, "AES")
,或者 – 如果你从密码开始 – 尝试使用PBKDF2生成密钥。
对我来说,问题在于getKey()
确保两次调用getKey()
返回相同的值。
我使用new SecureRandom(password.getBytes())
来生成密钥。 它适用于Windows,但在Android上,它为不同的调用返回了不同的值。
我反驳了这个: https ://androidfreetutorial.wordpress.com/2017/03/14/android-encryptiondecryption-with-aes-algorithm/
从“ AES / ECB / PKCS7Padding ”更改为“ AES ”;