我想在 Android 上加密/解密一个 pdf 文件(但这是一个 java 常见问题)
我有这个代码来生成我的密钥:
public static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
我编写加密文件的代码:
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(path + fileName);
outStream = new BufferedOutputStream(new FileOutputStream(outFile), 4096);
byte[] data = new byte[4096];
String seed = "password";
byte[] rawKey = Utils.getRawKey(seed.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
int bytesRead = 0;
while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(cipher.doFinal(data),0, bytesRead);
}
outStream.flush();
outStream.close();
inStream.close();
以及我的解密代码(并将其保存到新的解密文件中):
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(tmp_file);
String seed = "password";
byte[] rawKey = Utils.getRawKey(seed.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
int b;
byte[] data = new byte[4096];
while((b = fis.read(data)) != -1) {
fos.write(cipher.doFinal(data), 0, b);
}
fos.flush();
fos.close();
fis.close();
我在stackoverflow上阅读了很多,并尝试按照说明进行操作,但这不起作用,我收到了这个错误:
javax.crypto.BadPaddingException: pad block corrupted at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCi
我究竟做错了什么 ?是否有任何与 pdf 文件相关的特殊性?