我正在对 java 中的数据(使用 AES 的 Java 项目)进行加密,并希望在 android 中解密数据,但我遇到了坏的 pad 损坏错误。如果在 java 项目上运行相同的程序,它的 woking.Java 项目和 android 代码如下:
Java 端代码(Java 项目):
enter code here
public static void main(String[] args) {
//Same password used in android
String masterpassword ="test";
String crypto = encrypt(masterpassword, "XYZ");
}
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
System.out.println(rawKey);
byte[] result = encrypt(rawKey, cleartext.getBytes());
return Base64.encode(result);
// return toHex(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
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;
}
安卓端代码: *
public void onDecrypt(View view){
System.out.println("onDecrypt ");
String param = "w7ayjByx5I0yrX2tT8gj4w==";//Encrypted data
String masterpassword ="test";
try {
String res = decrypt(masterpassword, param);
}
}
*
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
System.out.println(rawKey);
// byte[] enc = toByte(encrypted);
byte[] enc = Base64.decode(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
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;
}
请帮忙。