问题描述
我创建一个加密
类在我的Android项目encryt /解密的二进制数据,通过这种link.
I create an Encryption
class to encryt/decrypt binary data in my Android project, by this link.
package com.my.package;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
// TODO Incomplete class
public class Encryption {
private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
(byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };
private static int BLOCKS = 128;
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;
}
private static byte[] getKey() throws Exception {
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
}
public static void test() {
String test = "My Name Is Dragon Warrior";
byte[] e = null;
try {
e = encrypt(getKey(), test.getBytes());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] d = null;
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(new String(d));
}
}
然后我运行的主要活动code:
Then I run the code in main activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
Encryption.test();
// ...
}
然后我得到一个 BadPaddingException
时,在执行以下code测试()
:
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
有趣的是,我比创建Android项目以外的Java项目。而code运行得很好,没有任何例外。
The funny thing is that I created a Java project other than Android project. And the code is running just fine without any exception.
这有什么错我的code?
What's wrong with my code?
推荐答案
SHA1PRNG是的不的密钥导出功能,并实施可跨供应商有所不同。请使用正确的KDF如PBKDF2的密码。 这是一个关键的是的不的一个关键,它是一个字符串。
"SHA1PRNG" is not a key derivation function, and the implementation may differ across providers. Please use a correct KDF such as PBKDF2 for passwords. "This is a key" is not a key, it is a string.
这篇关于为什么试图加密字符串时,我得到BadPaddingException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!