如何在Java中将受密码保护的KeyStore文件添加到zip中

时间:2018-09-13 09:18:51

标签: java spring zip keystore pfx

我创建了受密码保护的KeyStore文件

CertificateFactorycertFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(certyfikat);
X509Certificate cert = (X509Certificate)  
certFactory.generateCertificate(in);
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(null,null);
ks.setCertificateEntry("alias", cert);
FileOutputStream fos = new FileOutputStream("test.pfx");
ks.store(fos, "yourPassword".toCharArray());

这是向KeyStore添加密码保护的正确方法吗?

我想在zip文件中返回它。我尝试了ZipOutputStream和ZipEntry,但是使用ZipOutputStream.write()只能处理byte []。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry("cert.pfx");
zos.putNextEntry(entry);
zos.write(ks???);

如何将KeyStore转换为byte []?

还有其他使用KeyStore创建zip的方法吗?

也许应该以其他方式而不是使用KeyStore类创建.pfx文件?

1 个答案:

答案 0 :(得分:0)

Using ByteArrayOutputStream instead of FileOutputStream should work.

Replace

FileOutputStream fos = new FileOutputStream("test.pfx");
ks.store(fos, "yourPassword".toCharArray());

With

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ks.store(bos, "yourPassword".toCharArray());
byte keystore[] = bos.toByteArray();