내 프로그램의 다른 곳에서 사용하기 위해 암호화를 시도하고 래핑하는 간단한 클래스가 있습니다."마지막 블록 불완전한 암호화"처리 방법
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
public final class StupidSimpleEncrypter
{
public static String encrypt(String key, String plaintext)
{
byte[] keyBytes = key.getBytes();
byte[] plaintextBytes = plaintext.getBytes();
byte[] ciphertextBytes = encrypt(keyBytes, plaintextBytes);
return new String(ciphertextBytes);
}
public static byte[] encrypt(byte[] key, byte[] plaintext)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec spec = new SecretKeySpec(getRawKey(key), "AES");
cipher.init(Cipher.ENCRYPT_MODE, spec);
return cipher.doFinal(plaintext);
}
catch(Exception e)
{
// some sort of problem, return null because we can't encrypt it.
Utility.writeError(e);
return null;
}
}
public static String decrypt(String key, String ciphertext)
{
byte[] keyBytes = key.getBytes();
byte[] ciphertextBytes = ciphertext.getBytes();
byte[] plaintextBytes = decrypt(keyBytes, ciphertextBytes);
return new String(plaintextBytes);
}
public static byte[] decrypt(byte[] key, byte[] ciphertext)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec spec = new SecretKeySpec(getRawKey(key), "AES");
cipher.init(Cipher.DECRYPT_MODE, spec);
return cipher.doFinal(ciphertext);
}
catch(Exception e)
{
// some sort of problem, return null because we can't encrypt it.
Utility.writeError(e);
return null;
}
}
private static byte[] getRawKey(byte[] key)
{
try
{
KeyGenerator gen = KeyGenerator.getInstance("AES");
SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
rand.setSeed(key);
gen.init(256, rand);
return gen.generateKey().getEncoded();
}
catch(Exception e)
{
return null;
}
}
}
하지만 너무 많이 강조 표시된 라인에 javax.crypto.IllegalBlockSizeException를 "해독 불완전 마지막 블록을"던지는, 해독 때, 제대로 암호화를 처리 할 것으로 보인다. 여기에 스택 추적입니다 : 나는 시도하고 이것을 알아낼 내 책상에 내 머리를 두드리는의 좋은 금액을했을
Location:com.xxxxxx.android.StupidSimpleEncrypter.decrypt ln:49 last block incomplete in decryption javax.crypto.IllegalBlockSizeException: last block incomplete in decryption at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:711) at javax.crypto.Cipher.doFinal(Cipher.java:1090) at com.xxxxxx.android.StupidSimpleEncrypter.decrypt(StupidSimpleEncrypter.java:44) at com.xxxxxx.android.StupidSimpleEncrypter.decrypt(StupidSimpleEncrypter.java:34)
,하지만 난 전혀 어디서나 얻을 경우, 그것은 다른 예외가 될 수있을 테니까요. 나 또한 검색을 통해 많은 것을 찾지 못하는 것 같습니다.
무엇이 누락 되었습니까? 나는 어떤 도움을 주셔서 감사합니다.
이 내 문제의 근본 원인이었다,하지만 그것은 페이로드이고있는하지 않습니다 키 내 경우에는 항상 표준 문자열이되어야합니다.나는 문자열 암호화 방법에서 그것을 바꿨다. 반환 된 암호문은 바이트 배열에서 Base64로 인코딩되고 해독 방법에서는 암호문 문자열이 Base64로 바뀌어 바이트 배열로 바뀐다. 즉, 데이터가 더 이상 손실되지 않고 코드가 작동합니다. –
암호화 된 String 자체와 동일합니다. byte []로 저장해야합니다. – user1666456