加密后是否进行压缩?

phi*_*hil 1 java security encryption zipoutputstream

在审查加密方案时,我遇到了以下代码:


    @Override
    public OutputStream encrypt(OutputStream outputStream) throws Exception {

        // generate the IV for encryption
        final byte[] encryptionIV = KeyFileUtil.randomBytes(16);
        outputStream.write(encryptionIV);

        // now create the encryption cipher
        final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, getKey(), new GCMParameterSpec(128, encryptionIV));

        // The CipherOutputStream shouldn't close the underlying stream
        outputStream = new FilterOutputStream(outputStream) {
            @Override
            public void close() throws IOException {
                // Do nothing
            }
        };
        final CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);

        if (useZip) {
            final ZipOutputStream zipOutputStream = new ZipOutputStream(cos) {
                @Override
                public void finish() throws IOException {
                    super.finish();
                    def.end();
                }

                @Override
                public void flush() {
                    // Do nothing.
                }

                @Override
                public void close() throws IOException {
                    try {
                        super.flush();
                    } catch (final IOException exception) {
                        // Continue and try to close.
                    }
                    super.close();
                }
            };
            zipOutputStream.putNextEntry(new ZipEntry("ResourceContents"));
            return zipOutputStream;
        }
        return cos;
    }
Run Code Online (Sandbox Code Playgroud)

据我了解,流的顺序是先加密数据,然后(无用地)压缩数据。这是正确的还是我误解了 OutputStreams 上的排序方式?

谢谢

Kay*_*man 5

是的,您误解(或阅读)了排序的工作原理。

由于new ZipOutputStream(cos)CipherOutputStream包装ZOS,因此数据首先被压缩,然后传递到包装流,该流将加密数据,然后将其传递到下一个包装流,依此类推。

最外层的流首先获取数据,如果启用了压缩,return zipOutputStream;则调用 zipstream,其中 zipstream 是最外层的流。这是FilterOutputStream的惯用用法。