Android 4.2 破坏了我的加密/解密代码,提供的解决方案不起作用



首先,我已经看到安卓4.2破解了我的AES加密/解密代码和Android 4.2上的加密错误以及所提供的解决方案:

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,我得到:

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

我的猜测是,默认提供商并不是安卓4.2中唯一发生变化的地方,否则我的代码将与提议的解决方案一起工作。

我的代码是基于很久以前在StackOverflow上发现的一些帖子;我发现它与前面提到的帖子不同,因为它只是对字节数组进行加密和解密,而其他解决方案则对字符串进行加密和解码(我认为是HEX字符串)。

这和种子有关吗?它有最小/最大长度、字符限制等吗?

有什么想法/解决方案吗?

编辑:经过大量测试,我发现有两个问题:

  1. 供应商在Android 4.2(API 17)中更改->这个很容易修复,只需应用我在文章顶部提到的解决方案

  2. BouncyCastle在Android2.2(API 8)->Android2.3(API 9)中从1.34变为1.45,所以我之前告诉的解密问题与这里描述的相同:BouncyCCastle升级到1.45 时出现AES错误

所以现在的问题是:有什么方法可以在BouncyCastle 1.45+中恢复BouncyCCastle 1.34中加密的数据吗

首先是免责声明:

切勿使用SecureRandom派生密钥!这个坏了,没有意义

下面这个问题的代码块试图从密码中确定地导出一个密钥,称为"种子",因为密码用于"种子"随机数生成器。

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

然而,"SHA1PRNG"算法没有得到很好的定义,因此"SHA1PRNG"的实现可能返回不同的甚至完全随机的密钥


如果你正在从磁盘上读取AES密钥,只需存储实际密钥,不要经历这种奇怪的舞蹈。您可以通过执行以下操作从字节中获得用于AES使用的SecretKey

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

如果你使用密码来派生密钥,请遵循Nelenkov的优秀教程,并注意一个好的经验法则是盐的大小应该与密钥输出的大小相同。

iterationCount(功因数)当然会发生变化,应该随着CPU功率的增长而变化——通常建议自2018年起不要低于40至100K。注意PBKDF2只会给猜测密码增加一个恒定的时间延迟;它不能取代真正弱的密码。

它看起来像这样:

/* 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");

就是这样。任何其他你不该用的东西。

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

问题是对于新的提供程序,以下代码片段

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。因此,您试图使用与用于加密数据的密钥不同的密钥进行解密,结果会出现异常当密钥或数据以这种方式生成时,您将无法恢复,并且只有种子被保存

修复它的方法(正如@Giorgio所建议的)只是替换这个

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

与此

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

我无法回答您提出的问题,但我只想解决这个问题>-如果您在设备/OS版本中遇到一些关于bouncycastle的问题,您应该完全放弃内置版本,而是将bouncyccastle作为jar添加到您的项目中,将import更改为指向该jar,重建并假设一切正常,从现在起你将不受安卓内置版本更改的影响。

因为所有这些都不能帮助我生成在所有android设备上具有确定性的加密密码(>=2.1),所以我搜索了另一个AES实现。我找到了一个在所有设备上都适用的。我不是安全专家,我不确定这项技术是否没有达到应有的安全性。我只是为那些遇到过我以前遇到的同样问题的人发布代码。

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

来源:HERE

它确实与种子有关,它还应该使用8的倍数(如8、16、24或32),尝试用A和B或1和0来完成种子(必须是类似于ABAB…的东西,因为AAA...或BBB..也不起作用。)直到达到8的倍数。还有一件事,如果你只读取和加密字节(而不是像我那样将其转换为Char64),那么你需要一个合适的PKCS5或PKCS7填充,然而在你的情况下(由于只有128位,它是用旧版本的Android创建的)PKCS5就足够了,尽管你也应该把它放在你的SecretKeySpec中,比如"AES/CCB/PKCS5Padding">"AES/EBC/PKCS5Padding">,而不仅仅是"AES",因为Android 4.2使用PKCS7Padding作为默认值,如果它只有字节,你真的需要以前默认的算法。尝试使用早于4.2版本的Android设备,检查">keygen.init(128,secrand);"上的对象树,如果我没有弄错,它有cipher标签,然后使用它。试试看。

相关内容

最新更新