Friday, December 20, 2013

Create a KeyStore to save Secret Key

Secret key is used to encrypt and decrypt the strings like "password" and other secret information. KeyStore is the most secure place to keep secret key. 

Here are the main steps to create new key store and saving a secret key:
  • Get instance of KeyStore using KeyStore.getInstance method. It takes the name of the keystore
  • Once instance of KeyStore is available, load it as empty keyStore
  • Generate the secretKey and save it to keystore for future purposes.
    private final String KEYSTORE_TYPE = "JCEKS";
    private final String KEYSTORE_NAME = "CareKeyStore";
    private final String SECRET_KEY_NAME = "secretKeyAlias";
    private final String KEY_ALGO = "AES";

    private String final pwd ="mypass";

    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load (null,pwd.toCharArray());
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGO);
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();
    KeyStore.ProtectionParameter protParam =
                            new KeyStore.PasswordProtection(pwd.toCharArray());
    KeyStore.SecretKeyEntry skEntry =
                            new KeyStore.SecretKeyEntry(secretKey);
    ks.setEntry(SECRET_KEY_NAME, skEntry, protParam);
    java.io.FileOutputStream fos = null;
    try {
           fos = new java.io.FileOutputStream(KEYSTORE_NAME);
           ks.store(fos, pwd.toCharArray());
                       
     }catch(Exception ex){
           logger.error(null,ex);
                       
      }finally {
            if (fos != null) {
                  fos.close();
            }
      }