【发布时间】:2014-05-14 19:01:53
【问题描述】:
我正在创建一个程序,该程序允许用户上传和下载加密文件,并在他们拥有正确权限的情况下对其进行解密。加密和上传都很好,下载也很好,但是当我尝试解密时,我得到“pad block损坏”错误。
我要做的是获取加密文件,然后制作一个未加密的副本
我尽可能地缩短了,所以请不要评论它看起来不完整。
密钥生成:
public static SecretKey genGroupSecretKey() {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES", "BC");
keyGen.init(128);
return keyGen.generateKey();
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
return null;
}
加密:
try (FileInputStream fis = new FileInputStream(sourceFile)) {
response = Utils.decryptEnv((byte[]) tempResponse.getObjContents().get(0), fsSecretKey, ivSpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
do {
byte[] buf = new byte[4096];
int n = fis.read(buf); // can throw an IOException
else if (n < 0) {
System.out.println("Read error");
fis.close();
return false;
}
byte[] cipherBuf = cipher.doFinal(buf);
// send through socket blah blah blah
} while (fis.available() > 0);
解密:
...
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, secKey, ivSpec);
File file = new File("D_" + filename); // D_ for decrypted
FileOutputStream fos = null;
if (!file.exists()) {
file.createNewFile();
fos = new FileOutputStream(file);
}
try (FileInputStream fis = new FileInputStream(filename)) {
do {
byte[] buf = new byte[4096];
int n = fis.read(buf);
if (n < 0) {
System.out.println("Read error");
fis.close();
return false;
}
byte[] cipherBuf = cipher.doFinal(buf); // ERROR HERE
System.out.println("IS THIS WORKING WTF: " + new String(cipherBuf));
fos.write(cipherBuf, 0, n);
} while (fis.available() > 0);
fis.close();
fos.close();
return true;
【问题讨论】:
标签: java encryption aes bouncycastle