How to use certificates from a java PKCS#12 keystore for encrypting and decrypting files?(如何使用来自 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.
这篇关于如何使用来自 java PKCS#12 密钥库的证书来加密和解密文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用来自 java PKCS#12 密钥库的证书来加密和解密
基础教程推荐
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01