【发布时间】:2020-07-14 06:17:43
【问题描述】:
如何修改此 AES 加密代码,使其可以加密和解密任何类型的文件(pdf、docx ......),因为当我解密 pdf 文件或其他文件时,我没有得到原始文件。
public EncryptData(File originalFile, File encrypted, SecretKeySpec secretKey, String cipherAlgorithm) throws IOException, GeneralSecurityException{
this.cipher = Cipher.getInstance(cipherAlgorithm);
encryptFile(getFileInBytes(originalFile), encrypted, secretKey);
}
public void encryptFile(byte[] input, File output, SecretKeySpec key) throws IOException, GeneralSecurityException {
this.cipher.init(Cipher.ENCRYPT_MODE, key);
writeToFile(output, this.cipher.doFinal(input));
}
public SecretKeySpec getSecretKey(String filename, String algorithm) throws IOException{
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
return new SecretKeySpec(keyBytes, algorithm);
}
public static void main(String[] args) throws IOException, GeneralSecurityException, Exception{
StartEncryption startEnc = new StartEncryption();
File originalFile = new File("file.docx");
File encryptedFile = new File("EncryptedFiles/encryptedFile");
new EncryptData(originalFile, encryptedFile, startEnc.getSecretKey("OneKey/secretKey", "AES"), "AES");
}
public DecryptData(File encryptedFileReceived, File decryptedFile, SecretKeySpec secretKey, String algorithm) throws IOException, GeneralSecurityException {
this.cipher = Cipher.getInstance(algorithm);
decryptFile(getFileInBytes(encryptedFileReceived), decryptedFile, secretKey);
}
public void decryptFile(byte[] input, File output, SecretKeySpec key) throws IOException, GeneralSecurityException {
this.cipher.init(Cipher.DECRYPT_MODE, key);
writeToFile(output, this.cipher.doFinal(input));
}
public SecretKeySpec getSecretKey(String filename, String algorithm) throws IOException{
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
return new SecretKeySpec(keyBytes, algorithm);
}
public static void main(String[] args) throws IOException, GeneralSecurityException, Exception{
StartDecryption startEnc = new StartDecryption();
File encryptedFileReceived = new File("EncryptedFiles/encryptedFile");
File decryptedFile = new File("DecryptedFiles/decryptedFile");
new DecryptData(encryptedFileReceived, decryptedFile, startEnc.getSecretKey("DecryptedFiles/SecretKey", "AES"), "AES");
}
【问题讨论】:
-
像 AES 这样的通用加密算法并不关心它们加密的文档类型;他们只是对字节流进行操作。如果解密后没有得到原始文档,则可能是加密/解密代码中存在错误。
标签: java encryption aes