如何使用来自 java PKCS#12 密钥库的证书来加密和解密文件?
谁能解释如何使用存储在 java 'PKCS#12` 密钥库中的证书来加密和解密文件?
Can anyone explain how to encrypt and decrypt files using certificates stored in a java 'PKCS#12` keystore?
推荐答案
正如提到 Eugene Mayevski,您的问题是错误的,无法以原始形式回答.但我会试着为你澄清一下.PKCS#12 - 加密格式用于存储证书和私钥.当您加密或解密数据时,您使用 PKCS#12
容器的密码实现和 content.
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 is for storing cerificates and private keys. When you encrypt or decrypt data, you use cipher implementation and content of PKCS#12
container.
Java 内置支持使用 PKCS#12 密钥库,使用此容器与标准 JKS 密钥库没有太大区别.
Java has build-in support for work with PKCS#12 keystores, work with this containers doesn't much differ than standart JKS keystore.
例如,加载 JKS 密钥库的代码
For example, code to load JKS keystore
KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
store.load(is, password.toCharArray());
以及加载 PKCS#12 密钥库的代码
and code to load PKCS#12 keystore
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(is, password.toCharArray());
之后,您可以无限制地访问密钥库内容.您可以获取存储在密钥库中的证书和密钥,而无需在 Firefox 中使用导入/导出进行奇怪的操作.
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());
接下来,当您拥有密钥和证书时,就是加密.用于加密.你需要 Cipher 类的实例.
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);
准备加密的密码.如果加密数据比较小,可以使用update()
方法,其他方法是创建CipherOutputStream
.
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.
相关文章