Android:Java:使用密钥而不是密码解密AES
问题描述:
我正在使用代码段解密AES文件。Android:Java:使用密钥而不是密码解密AES
但是,我想使用密钥文件而不是密码来解密文件。
我需要在下面的代码中做出什么改变才能实现?
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return Converters.toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = Converters.toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
public static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
try {
kgen.init(256, sr);
} catch (Exception e) {
// Log.w(LOG, "This device doesn't support 256 bits, trying 192 bits.");
try {
kgen.init(192, sr);
} catch (Exception e1) {
// Log.w(LOG, "This device doesn't support 192 bits, trying 128 bits.");
kgen.init(128, sr);
}
}
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
}
答
AES密钥略多于16,24或32个字节的随机生成的数据。因此,要创建密钥文件,请将该数量的随机数据保存在其中,并使用它来实例化SecretKeySpec(byte[] data, "AES")
。
请注意,为了您的方便SecretKeySpec
也是一个SecretKey
。
学习加密并且不要使用随机片段。这段代码可能会使您无法再解密密文。即使你能解密它,它也是不安全的。 – 2014-10-01 23:24:31
我看到它列为Android的标准加密代码?为什么这个代码有问题? – R0b0tn1k 2014-10-04 10:22:11
*你能否指明**你在哪里可以找到上述代码“作为Android的默认加密代码?”*。问题出现在'getRawKey'这个使用随机数发生器的'getRawKey'中,这个随机数发生器*不确定或者没有定义好*,实现依赖于提供者,并且它可以 - 并且已经 - 在没有警告的情况下被改变。此外,您只需要使用'Cipher.getInstance(“AES”)',就可以使用提供者默认的操作模式和填充。这也不是确定性的,它通常默认为不安全的ECB加密模式。 – 2014-10-04 11:00:23