Java keystores provide a
convenient mechanism for storing and deploying public and private keys. Truststore
and Keystore file will be used in the communication to provide secured
transaction between two systems. The keytool command is used to create the
key store file which contains the public/private keys and then using keystore,
Create a truststore file which contains only public keys. Keystore will keep the private key secure by adding the additional two
level password securities at both the keystore and at private key level.
Here we will be using the RSA based asymmetric approach for
encryption and decryption.
We can define
the validity also for which this key will remain valid. This we can use for
keeping the check for keys to remain valid for a year or so.
/* getting data for keystores
*/
//for decryption
File file = new File("{Path}\\keystore.jks");
//for encryption
File file1 = new File("{Path}\\truststore.jks");
FileInputStream is = new
FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream is1 = new FileInputStream(file1);
KeyStore keystore1 = KeyStore.getInstance(KeyStore.getDefaultType());
/* Information for certificate to be
generated */
String password = "{Password given at time of key generation}";
String alias = "certificatekey";
/* getting the private key */
keystore.load(is,
password.toCharArray());
PrivateKey key = (PrivateKey)
keystore.getKey(alias,password.toCharArray());
/* Get certificate of public key */
keystore1.load(is1,
password.toCharArray());
java.security.cert.Certificate cert =
keystore1.getCertificate(alias);
/* Here it prints the public key */
System.out.println("Public
Key:");
System.out.println(cert.getPublicKey());
/* Here it prints the private key */
System.out.println("\nPrivate
Key:");
System.out.println(key);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,
cert.getPublicKey());
byte[] encryptedData =
cipher.doFinal("Text to be Encrypted".getBytes());
System.out.println("Encryted
Data: " + encryptedData);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] descryptedData =
cipher.doFinal(encryptedData);
System.out.println("Decrypted
Data: " + new
String(descryptedData));