java - 部分文件加密

标签 java encryption filestream

我有一堆视频文件需要作为我们应用程序的数据放到 Android 平板电脑上。因为我们不想轻易访问,所以我们决定对视频进行加密。我正在通过默默无闻的方法来确保安全。我首先对整个视频进行加密,然后在播放前对其进行解密,但很快我就发现加载视频是保真度的一大 killer 。拍摄用户体验和应用程序流程。

考虑到我们所有的视频都超过 1MB,我想也许我可以加密视频的第一个 MB。如果小偷拿到了视频,至少这不是全部,而且有点没用。

下面是加密和解密文件的代码。它适用于视频,因为我正在尝试将文件的两个部分修补在一起。加密文件看起来很好。解密的文件在一处关闭。我想到了,但是通过差异测试运行它们。

 public void encrypt(InputStream in, OutputStream out) {
    try {
        // Bytes written to out will be encrypted
       OutputStream out_c = new CipherOutputStream(out, ecipher);

        // Read in the cleartext bytes and write to out to encrypt
        int numRead = 0;
        int count = 0;
        boolean first = true;

        while ((numRead = in.read(buf)) >= 0) {

            if(count <= 1048576){
                count += numRead;
                out_c.write(buf, 0, numRead);
            }else{

                out.write(buf, 0, numRead);

            }
        }
        out.close();
        out_c.close();


    } catch (java.io.IOException e) {
    }
}

// Movies encrypt only 1 MB.

public void decrypt(InputStream in, OutputStream out) {
    try {
        // Bytes read from in will be decrypted
        InputStream in_c = new CipherInputStream(in, dcipher);

        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        int count = 0;

        while ((numRead = in_c.read(buf)) >= 0 && count <= 1048576) {
            count += numRead;
            out.write(buf, 0, numRead);
        }

        //in.skip(count); This removed 1MB from the final file. No need to skip.

        while((numRead = in.read(buf)) >= 0){

            out.write(buf,0,numRead);

        }

        out.close();
    } catch (java.io.IOException e) {
    }
}

我想知道是否有人能发现加密或解密的问题。我知道这不是一个理想的解决方案,但它适用于我们的情况。

谢谢。

最佳答案

您不会在恰好 1048576 字节处停止读取或写入,您读取/写入缓冲区的任何部分超过该阈值。在读/写情况下,不能保证 over 的大小相同,因此不一致。

解决方案是准确读取 1048576 字节的明文,通过加密例程将其写出,然后继续文件的其余部分。同样在解密情况下。

当然你还必须确保size(cleartext) == size(ciphertext)

关于java - 部分文件加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9879320/

相关文章:

c# - 使用 C# 将结构中的字节写入文件

java - 初始化本地数据存储异常 : No API environment is registered for this thread

security - 你如何锁定一个dll?

linux - GnuPG - 如何在不解密的情况下编辑文件并先保存到本地磁盘?

c# - 即使在 using 语句中,FileStream 也不会关闭

c++ - 使用文件流从文件读取/写入无符号字符数组

java - 使用 SendGrid 的 AppEngine 未找到类异常

java - 向 Eureka 休息服务端点发送多部分文件请求时出现异常

java - org.apache.kafka.connect.errors.DataException : Struct schemas do not match

c# - 如何在 .Net 服务器中支持不加密的 SSL?