java - 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();
}
解决方案
推荐阅读
- android - 如何通过 FCM 发送 Firestore 时间戳?
- javascript - 使用多个动态图表时Highchart闪烁
- firebase - 在这种情况下,我可以取消关联 Firebase 用户帐户吗?
- sql - SSMS - 寻求帮助编写选择语句以返回 SQL 中的重复项 [包含示例]
- flutter - 如何在展开的 ListView 中设置容器宽度
- python - 小写分隔符 Python 后的第一个字母
- javascript - Vue.js - 使用无效数据调用的函数 DocumentReference.set()。不支持的字段值:未定义
- sql-server - 向 SSIS 包添加简单的脚本任务会显着降低性能吗?
- f# - 在 C# 中,如何获取 F#/Elmish.WPF 对象的类/模块类型?
- javascript - 从选项卡“卸载”时如何重置反应导航?