getKey throws an exception on multi-thread env even if it is synchronized
843811May 7 2009 — edited May 20 2009 Hello,
I got the following exception when I used KeyStore#getKey method on multi-thread environment.
java.security.UnrecoverableKeyException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_z.a(DashoA13*..)
at com.sun.crypto.provider.JceKeyStore.engineGetKey(DashoA13*..)
at java.security.KeyStore.getKey(KeyStore.java:763)
at KeyStoreTest.run(KeyStoreTest.java:43)
at java.lang.Thread.run(Thread.java:619)
This is similar to the topic "Is KeyStore thread safe?"(Jan 29, 2008 8:40 PM), I suppose.
In the topic, KeyStore#getKey should be synchronized because it isn't thread safe.
Therefore I synchronized it, but this problem still occurred.
I used the following program for a duration test.
About in 1 hour, the exception always occurs.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
public class KeyStoreTest implements Runnable {
public final static String KSFILE = ".\\.jcekeystore"; // Please change here. Your "JCEKS" file name.
public static String sLock = "lock";
public static void main(String[] args) {
Thread[] threads;
int count = 20;
while (true) {
threads = new Thread[count];
for (int i = 0; i < count; i++) {
threads[i] = new Thread(new KeyStoreTest());
threads.start();
}
for (int i = 0; i < count; i++) {
if (threads[i].isAlive()) {
try {
threads[i].join();
} catch (InterruptedException e) {}
}
}
}
}
public void run() {
InputStream is = null;
try {
is = new FileInputStream(KSFILE);
Key key;
synchronized (sLock) {
//System.out.print("start - ");
KeyStore store = KeyStore.getInstance("jceks");
store.load(is, "12345678".toCharArray()); // Please change here. PIN code.
String alias = "alias"; // Please change here. Alias.
String keypassed = "keypasswd"; // Please change here. Key Password.
key = store.getKey(alias, keypassed.toCharArray());
//System.out.println("end");
}
System.out.println(key.getAlgorithm());
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(0);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
is = null;
}
}
}
}
I think there's no problem in my test program.
Do you have any information about the problem?
My test environment is below:
Java : jre1.6.0 update 13
OS : Windows XP
I tested this code with jre1.5.0 update 18, too.
But I didn't get the exception.
Thanks,
Masanori Hayashi