压缩是在加密之后发生的吗?

Is the compression happening after the encryption?

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


    @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;
    }

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

谢谢

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

new ZipOutputStream(cos) CipherOutputStreamZOS 包装,因此数据首先被压缩,然后传递到包装流,它将加密数据,然后通过它到下一个包装流,依此类推。

最外层的流首先访问数据,如果启用了压缩,则调用 return zipOutputStream;,zipstream 是最外层的流。这是 FilterOutputStream.

的惯用用法