問題描述
誰能解釋如何使用存儲在 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 密鑰庫的證書來加密和解密文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!