Android 4.2打破了我的encryption/解密代码,提供的解决scheme无法正常工作

首先,我已经看到Android 4.2打破了我的AESencryption/解密代码和encryption错误在Android 4.2和提供的解决scheme:

SecureRandom sr = null; if (android.os.Build.VERSION.SDK_INT >= JELLY_BEAN_4_2) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } 

对我不起作用,因为在解码Android 4.2中的Android 4.2中encryption的数据时,我得到:

 javax.crypto.BadPaddingException: pad block corrupted at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:709) 

我的代码很简单,直到Android 4.2:

 public static byte[] encrypt(byte[] data, String seed) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG"); secrand.setSeed(seed.getBytes()); keygen.init(128, secrand); SecretKey seckey = keygen.generateKey(); byte[] rawKey = seckey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, String seed) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG"); secrand.setSeed(seed.getBytes()); keygen.init(128, secrand); SecretKey seckey = keygen.generateKey(); byte[] rawKey = seckey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); return cipher.doFinal(data); } 

我的猜测是默认的提供者并不是Android 4.2中唯一改变的东西,否则我的代码就可以使用所提出的解决scheme。

我的代码是基于我在StackOverflow很久以前发现的一些post; 我看到,它不同于提到的职位,因为它只是隐藏和解密字节数组,而其他解决scheme隐藏和解密string(hexstring,我认为)。

这是否与种子有关? 它有一个最小/最大长度,限制字符等?

任何想法/解决scheme?

编辑 :经过大量的testing,我看到有2个问题:

  1. 供应商在Android 4.2(API 17)中更改 – >这个很容易解决,只是应用我在post顶部提到的解决scheme

  2. 在Android 2.2(API 8) – > Android2.3(API 9)中,BouncyCastle从1.34更改为1.45,所以我之前告诉的解密问题与此处所述的相同: BouncyCastle AES错误升级到1.45

所以现在的问题是: 有没有办法恢复在BouncyCastle 1.45 + BouncyCastle 1.34encryption的数据?

首先声明:

永远不要使用“SecureRandom”来派生一把钥匙! 这是打破,没有任何意义!

如果你从磁盘读取AES密钥,只需存储实际的密钥,不要通过这个奇怪的舞蹈。 您可以从字节中获取AES密钥的SecretKey:

  SecretKey key = new SecretKeySpec(keyBytes, "AES"); 

如果您使用密码来派生密钥,请遵循Nelenkov的优秀教程 ,但要注意的一点是,盐的大小应与密钥输出的大小相同。 它看起来像这样:

  /* User types in their password: */ String password = "password"; /* 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; // Should be of saltLength /* When first creating the key, obtain a salt with this: */ SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltLength]; random.nextBytes(salt); /* Use this to derive the key from the password: */ KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength); SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("PBKDF2WithHmacSHA1"); byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); SecretKey key = new SecretKeySpec(keyBytes, "AES"); 

而已。 别的什么,你不应该使用。

问题是, 新的提供者 ,下面的代码片段

 KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG"); secrand.setSeed(seed.getBytes()); keygen.init(128, secrand); SecretKey seckey = keygen.generateKey(); byte[] rawKey = seckey.getEncoded(); 

每次执行时会生成一个不同的,真正随机的rawKey 。 所以,你试图用与用于encryption数据的密钥不同的密钥进行解密,你会得到exception。 生成这种方式后,您将无法恢复密钥或数据,只保存种子

对我来说,固定的东西(就像@Giorgio build议的那样 )只是取代了这个

 SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG"); 

与此

 SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG", "Crypto"); 
 private static final int ITERATION_COUNT = 1000; private static final int KEY_LENGTH = 256; private static final String PBKDF2_DERIVATION_ALGORITHM = "PBKDF2WithHmacSHA1"; private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final int PKCS5_SALT_LENGTH = 32; private static final String DELIMITER = "]"; private static final SecureRandom random = new SecureRandom(); public static String encrypt(String plaintext, String password) { byte[] salt = generateSalt(); SecretKey key = deriveKey(password, salt); try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); byte[] iv = generateIv(cipher.getBlockSize()); IvParameterSpec ivParams = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivParams); byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8")); if(salt != null) { return String.format("%s%s%s%s%s", toBase64(salt), DELIMITER, toBase64(iv), DELIMITER, toBase64(cipherText)); } return String.format("%s%s%s", toBase64(iv), DELIMITER, toBase64(cipherText)); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static String decrypt(String ciphertext, String password) { String[] fields = ciphertext.split(DELIMITER); if(fields.length != 3) { throw new IllegalArgumentException("Invalid encypted text format"); } byte[] salt = fromBase64(fields[0]); byte[] iv = fromBase64(fields[1]); byte[] cipherBytes = fromBase64(fields[2]); SecretKey key = deriveKey(password, salt); try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); IvParameterSpec ivParams = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, key, ivParams); byte[] plaintext = cipher.doFinal(cipherBytes); return new String(plaintext, "UTF-8"); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static byte[] generateSalt() { byte[] b = new byte[PKCS5_SALT_LENGTH]; random.nextBytes(b); return b; } private static byte[] generateIv(int length) { byte[] b = new byte[length]; random.nextBytes(b); return b; } private static SecretKey deriveKey(String password, byte[] salt) { try { KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBKDF2_DERIVATION_ALGORITHM); byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); return new SecretKeySpec(keyBytes, "AES"); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } private static String toBase64(byte[] bytes) { return Base64.encodeToString(bytes, Base64.NO_WRAP); } private static byte[] fromBase64(String base64) { return Base64.decode(base64, Base64.NO_WRAP); } 

资源

我无法给你回答你所问的问题,但我只是试着去解决这个问题。 – 如果你在跨设备/操作系统版本时遇到一些问题,你应该彻底抛弃内置的版本,而不是将弹簧城添加为jar到你的项目,改变你的import指向该jar,重build和假设它的一切作品,你将不受android内置版本的变化从现在开始。

因为所有这些都不能帮助我生成一个在所有的android设备上都是确定的encryption密码(> = 2.1),所以我search了另一个AES实现。 我find了一款适用于所有设备的我。 我不是安全专家,因此,如果技术不够安全,请不要低估我的答案。 我只发布那些曾经遇到同样问题的人的代码。

 import java.security.GeneralSecurityException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Log; public class EncodeDecodeAES { private static final String TAG_DEBUG = "TAG"; private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!) private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!) public EncodeDecodeAES() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (GeneralSecurityException e) { Log.d(TAG_DEBUG, e.getMessage()); } } public byte[] encrypt(String text) throws Exception { if (text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { Log.d(TAG_DEBUG, e.getMessage()); throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if (code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { Log.d(TAG_DEBUG, e.getMessage()); throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data == null) { return null; } int len = data.length; String str = ""; for (int i = 0; i < len; i++) { if ((data[i] & 0xFF) < 16) str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF); else str = str + java.lang.Integer.toHexString(data[i] & 0xFF); } return str; } public static byte[] hexToBytes(String str) { if (str == null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i = 0; i < len; i++) { buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16); } return buffer; } } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } } 

你可以像这样使用它:

 EncodeDecodeAES aes = new EncodeDecodeAES (); /* Encrypt */ String encrypted = EncodeDecodeAES.bytesToHex(aes.encrypt("Text to Encrypt")); /* Decrypt */ String decrypted = new String(aes.decrypt(encrypted)); 

来源: 这里

这确实与种子有关,也应该使用8的倍数(如8,16,24或32),尝试用A和B或1和0完成种子(必须是这样的ABAB ..因为AAA ..或者BBB ..也不行。)达到8的倍数。 还有一个其他的东西,如果你正在阅读和encryption只有字节,(不像它那样把它转换成Char64),那么你需要一个适当的PKCS5或PKCS7填充,但是在你的情况下(只有128位,而且是用较旧的Android版本)PKCS5就足够了,尽pipe你也应该把它放在你的SecreteKeySpec里,比如“AES / CBC / PKCS5Padding”或者“AES / ECB / PKCS5Padding”而不是“AES”,因为Android 4.2使用PKCS7Padding作为默认如果只有字节,你真的需要使用与之前默认相同的algorithm。 尝试使用早于4.2的Android设备检查“ keygen.init(128,secrand); ”上的对象树;如果我没有弄错它有标签密码 ,则使用它。 试一试。