You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中WAV音频文件加密解密异常问题求助

解决WAV音频文件加密解密后损坏的问题

你的代码处理文本文件正常,但WAV是二进制文件,解密时的两个核心错误导致文件损坏:

  • 将解密后的二进制字节数组转为UTF-8字符串:二进制数据中包含大量非UTF-8兼容的字节,转字符串时会发生编码损失,直接破坏原始数据结构。
  • 使用BufferedWriter/FileWriter字符流写入文件:字符流会自动处理编码转换,进一步篡改二进制数据,最终导致文件大小异常、元数据丢失。

修正后的解密函数

直接使用字节流处理二进制数据,完全避免编码转换:

public void decrypt(File file) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException {
    try (FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath())) {
        byte[] fileInitializationVector = new byte[16];
        // 确保读取完整的16字节IV
        int bytesRead = fileInputStream.read(fileInitializationVector);
        if (bytesRead != 16) {
            throw new IOException("Failed to read complete initialization vector");
        }
        
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileInitializationVector));
        
        try (CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
             FileOutputStream outputStream = new FileOutputStream("testout.wav")) {
            // 用缓冲区分块读写,避免内存溢出同时保证数据完整
            byte[] buffer = new byte[4096];
            int read;
            while ((read = cipherInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
        }
    }
}

加密函数的优化建议(避免资源泄漏)

原加密函数中的FileInputStream未用try-with-resources管理,可能导致资源泄漏,优化后:

public void encrypt(File file) throws InvalidKeyException, IOException {
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] initializationVector = cipher.getIV();
    
    try (FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath() + ".enc");
         CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, cipher);
         FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath())) {
        fileOutputStream.write(initializationVector);
        
        // 分块读写,适配大文件场景
        byte[] buffer = new byte[4096];
        int read;
        while ((read = fileInputStream.read(buffer)) != -1) {
            cipherOutputStream.write(buffer, 0, read);
        }
    }
}

关键验证要点

  • 二进制文件(音频、图片、视频等)必须始终用字节流处理,绝对不能转为字符串或用字符流操作,否则会彻底破坏数据完整性。
  • 解密完成后,可以对比原文件和解密后文件的MD5/SHA哈希值,确认两者完全一致,验证完整性。

内容的提问来源于stack exchange,提问作者Yamen Nassif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:42:48