How to use certificates from a java PKCS#12 keystore for encrypting and decrypting files?

cryptography, java, pkcs#12

Solution

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 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.

Problem

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

Original source