私のプログラムのどこかで使用するために暗号化を試みる簡単なクラスがあります。"最後のブロックが不完全な暗号化"を扱う方法
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