首页 > 解决方案 > CipherOutputStream 和 ZipOutputStream

问题描述

我正在尝试创建包含该文件的加密文件和加密密钥的 zip 文件。这是我的代码:

压缩

 ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("zip.zip"));

连接的流

 PipedInputStream pis = new PipedInputStream();
 PipedOutputStream pos = new PipedOutputStream(pis);

获取秘钥

 KeyGenerator keygen=KeyGenerator.getInstance(storageSettings.getFileEncryptAlgorithm());
 SecretKey key = keygen.generateKey();

得到密码

 Сipher cipher = Cipher.getInstance("DESede");
 cipher.init(Cipher.ENCRYPT_MODE, key);

现在我将密码输出到 pipedOutputStream

 CipherOutputStream cos = new CipherOutputStream(pos,cipher);
 byte[] m = new byte[1024];
 int position;
 while ((position = someInputData.read(m, 0, 1024)) >= 0)
 {
  cos.write(m, 0, position);
 }

添加到 zip 并在那里,但下一个文件将为空

 addFileToZip(zout, pis, backup.getFilename());
 cos.flush();

现在我想通过 rsa 加密 SecretKey 密钥,并且我有来自文件的密钥对

 String publicKeyContent = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource(storageSettings.getPublicKeyFile()).toURI())));
 publicKeyContent = publicKeyContent.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
 KeyFactory keyfactory = KeyFactory.getInstance(storageSettings.getKeyEnryptAlgorithm());
 X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));
 RSAPublicKey publicKey = (RSAPublicKey) keyfactory.generatePublic(keySpecX509);
 cipher = Cipher.getInstance(storageSettings.getKeyEnryptAlgorithm());
 cipher.init(Cipher.ENCRYPT_MODE, publicKey);

现在我想用加密密钥创建第二个文件,但我在 zip 中有空文件,除了第一个文件之外所有文件都是空的

 CipherOutputStream cos1 = new CipherOutputStream(pos,cipher);
 byte[] tmp = key.getEncoded();
 cos1.write(tmp);
 addFileToZip(zout, pis,"key.txt");

这是 addFileToZip()

public void addFileToZip(ZipOutputStream zout,InputStream data,String filename) throws IOException
{
    zout.putNextEntry(new ZipEntry(filename));
    byte[] m = new byte[data.available()];
    data.read(m);
    zout.write(m);
    zout.closeEntry();
}

标签: javacryptographyzip

解决方案


推荐阅读