首先,我已经看过了 Android 4.2 broke my AES encrypt/decrypt code 和 Encryption error on 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中加密的数据时,我得到:
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中唯一改变的,否则我的代码将与提议的解决方案一起使用。
我的代码基于我很久以前在StackOverflow找到的一些帖子;我发现它与上面提到的帖子不同,因为它只是对字节数组进行加密和解密,而其他解决方案则加密和解密字符串(HEX Strings,我认为)。
是否与种子有关?它是否有最小/最大长度,字符限制等?
任何想法/解决方案?
修改: 经过大量的测试,我发现有两个问题:
在Android 4.2(API 17)中更改了提供程序 - >这个很容易修复,只需应用我在帖子顶部提到的解决方案
BouncyCastle在Android 2.2(API 8) - > Android2.3(API 9)中从1.34更改为1.45,因此我之前说过的解密问题与此处描述的相同:BouncyCastle AES error when upgrading to 1.45 < / p>
所以现在问题是:有没有办法恢复BouncyCastle 1.34 +中BouncyCastle 1.34中加密的数据?
答案 0 :(得分:45)
首先是免责声明:
不要使用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密钥,只需存储实际密钥,不要经历这种奇怪的舞蹈。您可以通过执行以下操作从字节中获取SecretKey
AES使用情况:
SecretKey key = new SecretKeySpec(keyBytes, "AES");
如果您使用密码来获取密钥,请遵循Nelenkov's excellent tutorial,但需要注意的是,经验法则是盐的大小应与密钥输出的大小相同。
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");
就是这样。你不应该使用的任何其他东西。
答案 1 :(得分:11)
问题是使用新的提供商,以下代码片段
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
。因此,您尝试使用与用于加密数据的密钥不同的密钥进行解密,并获得异常。 当以这种方式生成密钥或数据时,您将无法恢复密钥或数据,并且只保存了种子。
答案 2 :(得分:5)
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);
}
答案 3 :(得分:4)
为我修复的内容(如@Giorgio suggested)只是替换:
SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG");
使用此:
SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG", "Crypto");
答案 4 :(得分:0)
我无法回答您提出的问题,但我只是尝试解决这个问题&gt; - 如果您遇到跨设备/操作系统版本的bouncycastle的一些问题,您应该完全抛弃内置版本而不是将bouncycastle作为jar添加到你的项目中,将import
更改为指向该jar,重建并假设它一切正常,从现在开始你将不受android内置版本的影响。
答案 5 :(得分:0)
因为所有这些都无法帮助我生成在所有Android设备上确定性的加密密码(&gt; = 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
答案 6 :(得分:-1)
它确实与种子有关,它也应该使用8的倍数(如8,16,24或32),尝试使用A和B或1和0来完成种子(必须是这样的ABAB ...,因为AAA ..或BBB ..也不起作用。)最多达到8的倍数。如果你只读取和加密字节,还有其他的东西,(不像我那样将其转换为Char64),那么你需要一个合适的PKCS5或PKCS7填充,但是在你的情况下(由于只有128位而且它是用较旧的创建的) Android版本的PKCS5就足够了,不过你也应该把它放在你的SecreteKeySpec中,比如“AES / CBC / PKCS5Padding”或“AES / ECB / PKCS5Padding”而不只是“AES”,因为Android 4.2它使用PKCS7Padding作为默认值,如果它只是字节,你真的需要相同的算法,这是以前的默认。尝试使用早于4.2的Android设备检查“ keygen.init(128,secrand); ”上的对象树,如果我没弄错,它的标签为 cipher ,而不是使用它。 试一试。