开发者

Decryption failed when storing the key inside Java key store

I've created an encryption key by the following code:

SecretKeyFactory skFactory = SecretKeyFactory.getInstance("PBEWithSHA1AndDESede");
SecretKey key = skFactory.generateSecret(new PBEKeySpec("<some password>".toCharArray()));

Then I've used the key to encrypt some text.

I've stored this key inside a java key store and saved in on FS:

KeyStore ks = KeyStore.getInstance("JCEKS");
ks.setKeyEntry(keyAlias, key ,keyPassword.toCharArray(), null);
FileOutputStream fileOutputStream = new FileOutputStream (keyStorePath);
keyStore.store(fileOut开发者_高级运维putStream , keyStorePassword.toCharArray());
fileOutputStream.close();

In a different process I open the key store and try to decrypt some text:

KeyStore ks2 = KeyStore.getInstance("JCEKS");
ks2.load(new java.io.FileInputStream(keyStorePath), ksPassword.toCharArray());
SecretKeyFactory skFactory2 = SecretKeyFactory.getInstance("PBEWithSHA1AndDESede");
String passForTheKey = ks2.getKey(keyAlias, keyPass.toCharArray()).toString();
KeySpec key = new PBEKeySpec(passForTheKey.toCharArray());
SecretKey sKey2 = skFactory.generateSecret(key);

When trying to decrypt the text I get the error:

java.security.InvalidKeyException: Given final block not properly padded

If I try to use the key without storing it in the key store immediately after creating it, the decription proccess is working great.

Any ideas?


You're storing the actual secret key in your keystore (which is normal). However, you seem to be trying to read it as a password, for a new key you're generating later.

Instead of this:

String passForTheKey = ks2.getKey(keyAlias, keyPass.toCharArray()).toString();
KeySpec key = new PBEKeySpec(passForTheKey.toCharArray());
SecretKey sKey2 = skFactory.generateSecret(key);

use this:

SecretKey sKey2 = (SecretKey) ks2.getKey(keyAlias, keyPassword.toCharArray());

What you're reading from the keystore is the key itself (as you've stored it), not some password. (generateSecret will just generate a new key.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜