【发布时间】:2016-06-07 18:33:30
【问题描述】:
我正在编写一个简单的自定义加密器/解密器。
基本上,我只取一个大文件的前 1024 个字节并对其进行加密。
我使用了 RandomAccessFile,这样我就可以快速加密和解密前 1024 字节。
现在,我面临的问题是,即使我使用相同的算法进行加密和解密。
加密工作正常,但解密抛出 javax.crypto.BadPaddingException:Given final block not proper padded。
无论我搜索多少,我都无法找出问题所在。对此的一些研究告诉我,由于 UTF 和 base64 等不同的格式,填充不正确。但是我不确定如果我读取如此大文件的前 1024 个字节并且加密不会引发异常,填充会如何不正确。我也没有转换成字符串。
我提供了简单的注释,代码如下
public class Encryptor {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES";
public void encrypt(String key, File inputFile, File outputFile) throws CryptoException {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public void decrypt(String key, File inputFile, File outputFile) throws CryptoException {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws CryptoException {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);
byte[] inputBytes = new byte[16];
byte[] outputBytes = new byte[16];
//Open the file in read write mode
RandomAccessFile fileStore = new RandomAccessFile(inputFile, "rw");
fileStore.seek(0);
//encrypt first 1024bytes
int bytesRead = 0;
for(int ctr=0;bytesRead!= -1 && ctr<64 ;ctr++){
//get file pointer position
long prevPosition = fileStore.getFilePointer();
//read 16 bytes to array
bytesRead = fileStore.read(inputBytes);
//if successful, go move back pointer and overwrite these 16 bytes with encrypted bytes
if(bytesRead != 1){
outputBytes = cipher.doFinal(inputBytes);
fileStore.seek(prevPosition);
fileStore.write(outputBytes);
}
}
fileStore.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException(ex);
}
}
【问题讨论】:
标签: java algorithm encryption cryptography