0

I do the following to store a SecretKey based on a user password in the KeyStore:

// load KeyStore

static byte[] salt = // for learning purposes
                     { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
                       (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 };

String alias = "aeskey";
char[] password = "password".toCharArray();
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES/CBC/PKCS5Padding");
Entry aesentry = new KeyStore.SecretKeyEntry(secret);
store.setEntry(alias, aesentry, protParam);

Now I can get the SecretKey from the KeyStore:

KeyStore.SecretKeyEntry e = (SecretKeyEntry) store.getEntry("aeskey", protParam);
secret = e.getSecretKey();

How to get the inital password from that SecretKey?

Danny Lo
  • 1,553
  • 4
  • 26
  • 48

1 Answers1

5

You can't get the original password from the KeySpec. Some bytes of the password and the salt are chosen, to come up with the KeySpec. If you are trying to encrypt and decrypt text, you need to do the following:

  1. Generate the KeySpec using a password and salt
  2. Generate a SecretKey
  3. generate a Cipher instance using this
  4. Encrypt your text using this cipher

Now, say you share your password and salt with someone offline. They can then use these to decrypt the encrypted text.

See this for a good discussion on this.

Community
  • 1
  • 1
Aritra
  • 1,234
  • 12
  • 20
  • I considered to use a KeyStore to keep a bunch of inital passwords in it. Now I see this was a wrong approach. I could use a single initial password to encrypt/decrypt the other initial passwords as a plain text. The output would be a bunch of crypted bytearrays. Should I just put them in a file? Or would you suggest a better way for achieving that? – Danny Lo Sep 30 '14 at 16:28
  • It depends on the use case. Take a look at [jasypt](http://www.jasypt.org/) to get some things out of the box. Then, you can choose to store encrypted stuff in files, database, etc. – Aritra Sep 30 '14 at 18:33
  • Thanks for Jasypt, this will probably fit me best. – Danny Lo Oct 01 '14 at 10:24