我有一个程序必须加密音频文件,然后在需要时对其进行解密。我在一些其他类型的文件上测试了我的程序,比如 .bin 或 .txt。我得到的问题是解密文件在实际内容之前有一些奇怪的字符,比如源文件包含“010101”,加密解密后它有“¬íw0w 010101”。
我的加密方法代码在这里:
public void cipherTheAudioFile(String fileDir, String fileToCipher) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException {
File audioSourceFile = new File(fileDir + "\\" + fileToCipher);
ObjectOutputStream oos = new ObjectOutputStream(
new CipherOutputStream(new FileOutputStream(
new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToCipher + ".sky"), cipher));
byte[] audioFileInBytes = FileUtils.readFileToByteArray(audioSourceFile);
oos.write(audioFileInBytes);
fos = new FileOutputStream(KEY_FILE);
SecretKeyFactory skf = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
DESKeySpec keyspec = (DESKeySpec) skf.getKeySpec(key, DESKeySpec.class);
fos.write(keyspec.getKey());
fos.close();
oos.close();
}
我的解密方法代码在这里:
public void decryptTheAudioFile(String fileDir, String fileToDecipher) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, ClassNotFoundException, InvalidKeySpecException, InvalidKeyException {
fis = new FileInputStream(keyFile);
byte[] keyspecbytes = new byte[fis.available()];
File fileToWriteIn = createFileToWriteIn(fileDir, fileToDecipher);
fis.read(keyspecbytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec keyspec = new DESKeySpec(keyspecbytes);
SecretKey key = skf.generateSecret(keyspec);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
ObjectInputStream ois = new ObjectInputStream(
new CipherInputStream(
new FileInputStream(new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToDecipher + ".sky"), cipher));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileToWriteIn));
byte[] audioFileInBytes = new byte[1024];
int numRead = 0;
while ((numRead = ois.read(audioFileInBytes)) >= 0) {
oos.write(audioFileInBytes, 0, numRead);
}
oos.close();
fis.close();
ois.close();
}
PS这可能与编码有关,但我不确定。
已编辑
好的,我已更改为 FileWriters,但仍然没有更改。代码如下:
OutputStream os = new FileOutputStream(new java.io.File("").getAbsolutePath().toString() + "/encrypted/" + fileToCipher + ".sky");
CipherInputStream cis = new CipherInputStream(new FileInputStream(audioSourceFile), cipher);
byte[] audioFileInBytes = new byte[1024];
int numRead = 0;
while ((numRead = cis.read(audioFileInBytes)) >= 0) {
os.write(audioFileInBytes, 0, numRead);
}
解密器也是如此。