에 의해 안드로이드 프로젝트에서 이진 데이터를 암호화/해독하기 위해 Encryption
클래스를 만듭니다.문자열을 암호화하려고 할 때 왜 BadPaddingException이 발생합니까?
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
재미있는 것은이 때문이다 : 다음 코드는 test()
에서 실행되고있을 때 나는 BadPaddingException
를 얻을 다음
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
Encryption.test();
// ...
}
: 다음
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));
}
}
나는 주요 활동에서 코드를 실행 Android 프로젝트가 아닌 Java 프로젝트를 만들었습니다. 그리고 코드는 예외없이 잘 실행됩니다.
내 코드에 어떤 문제가 있습니까?
저는 그것에 대해 전혀 몰라요. 그러나 나는이 인터넷을 검색하여 다음 링크를 찾으십시오. http://stackoverflow.com/questions/4874311/badpaddingexception-in-android-encrypt 희망이 있으면 도움이 될 것입니다. 이 링크는 http://stackoverflow.com/questions/8387345/badpaddingexception-pad-block-corrupted-in-android – Maulik
코드가 Android (Java 7) 외부에서 올바르게 실행되는지 확인할 수 있습니다. –
'BadPaddingException'은 일반적으로 잘못된 키가 데이터를 해독하는 데 사용됨을 의미합니다. 이것은, getKey()가 각 호출마다 다른 값을 돌려주는 경우에 발생할 가능성이 있습니다. Android에서 getKey()를 한 번만 호출하고 결과를 저장하는 테스트를 해봤습니까? * 결과가 다른 이유는 없지만 흥미로운 테스트입니다 * –