如何使用来自Java PKCS#12密钥库的证书加密和解密文件? [英] How to use certificates from a java PKCS#12 keystore for encrypting and decrypting files?

查看:1393
本文介绍了如何使用来自Java PKCS#12密钥库的证书加密和解密文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释如何使用存储在java'PKCS#12`密钥库中的证书加密和解密文件。

解决方案

正如Eugene Mayevski所说,你的问题是错误的,不能以原来的形式回答。但我会尽力为你澄清一下。 PKCS#12 - 加密格式用于存储证书和私钥。当您加密或解密数据时,您使用PKCS#12容器的密码实现和内容



Java对于使用PKCS#12密钥库具有内置支持,使用此容器与标准JKS密钥库无太大差别。



例如,加载JKS密钥库的代码

  KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType ()); 
store.load(is,password.toCharArray());

和加载PKCS#12密钥库的代码

  KeyStore store = KeyStore.getInstance(PKCS12); 
store.load(is,password.toCharArray());

之后,您可以无限制地使用密钥库内容。您可以获取存储在密钥库中的证书和密钥,而无需使用Firefox中的导入/导出的奇怪操作。

  Key key = store .getKey(alias_for_key,password.toCharArray()); 

接下来,当你有密钥和证书时,就是加密。用于加密。你需要Cipher类的实例。

  Cipher c = Cipher.getInstance(key.getAlgorithm()); 
c.init(Cipher.ENCRYPT_MODE,key);

密码已准备好加密。如果加密数据相对较小,可以使用 update()方法,另一种方法是创建 CipherOutputStream



要解密,只需使用不同模式的init密码,并取决于加密算法,密钥。对于对称算法,密钥将相同,对于非对称算法,使用公钥和解密私钥。



在此文章中,您可以了解有关加密的更多信息。 / p>

Can anyone explain how to encrypt and decrypt files using certificates stored in a java 'PKCS#12` keystore?

解决方案

As mention Eugene Mayevski, your question is wrong and cannot be answered in its original form. But i'll try to clarify it for you a bit. PKCS#12 - cryptographic format for storing cerificates and private keys. When you encrypt or decrypt data, you use cipher implementation and content of PKCS#12 container.

Java has build-in support for work with PKCS#12 keystores, work with this containers doesn't much differ than standart JKS keystore.

For example, code to load JKS keystore

KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
store.load(is, password.toCharArray());

and code to load PKCS#12 keystore

KeyStore store = KeyStore.getInstance("PKCS12");
store.load(is, password.toCharArray());

After that you have unlimited accsess to keystore content. You can get certificates and keys, stored in keystore, without that strange actions with import/export in Firefox.

Key key = store.getKey("alias_for_key", password.toCharArray());

Next thing, when you have keys and certificates, is encryption. For encryption. you need instance of Cipher class.

Cipher c = Cipher.getInstance(key.getAlgorithm());
c.init(Cipher.ENCRYPT_MODE, key); 

Cipher ready to encrypt. If encryption data is relativily small, you can use update() method, other way is to create CipherOutputStream.

To decrypt, simply init cipher with different mode and, depends of encryption algorithm, key. For symmetric algorithm key will the same, for asymmetric algorithm for encryption uses public key, and for decryption private key.

In this article you can learn more about cryptography.

这篇关于如何使用来自Java PKCS#12密钥库的证书加密和解密文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆