【发布时间】:2011-01-04 21:57:20
【问题描述】:
我有一个简单的类来尝试包装加密以在我的程序的其他地方使用。
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“解密中的最后一个块不完整”。这是堆栈跟踪:
位置:com.xxxxxx.android.StupidSimpleEncrypter.decrypt ln:49 最后一个块解密不完整 javax.crypto.IllegalBlockSizeException:最后一个块在解密中不完整 在 org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:711) 在 javax.crypto.Cipher.doFinal(Cipher.java:1090) 在 com.xxxxxx.android.StupidSimpleEncrypter.decrypt(StupidSimpleEncrypter.java:44) 在 com.xxxxxx.android.StupidSimpleEncrypter.decrypt(StupidSimpleEncrypter.java:34)我已经多次将头撞在桌子上以试图弄清楚这一点,但如果我得到任何结果,它最终会成为一个不同的例外。我似乎也无法通过搜索找到很多东西。
我错过了什么?我将不胜感激。
【问题讨论】:
标签: android encryption aes