I have an applet who reads the Certificate and for consequence the public and private keys from usb Token. I can read get access to PrivateKey whenever the token is plugged, but I have a cryptographed environment where I need to post the certificate and keys to a servlet, and this servlet will sign the selected files on my application. It was working fine, till I got this token with a non exportable PrivateKey.
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, PIN.toCharArray());
Then I use a decoder to convert the bytes array to BASE64 and post it.
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String base64encoded = encoder.encode(privateKey.getEncoded());
However, using this particular token, the method getEncoded(), used on privateKey.getEncoded(), returns always null. So I didn't find a way to get the bytes array from PrivateKey object.
Is there a possible way to do it?
You can't get the private key from a PKCS11
token, PKCS11
are used to have the key material inside the secure device and can't be extracted, when you want to sign with this kind of devices (HSM, smart-cards and so on) the signature is performed inside it.
If you want to perform a signature with a client PKCS11
usb token and a applet, you have to perform the signature in the applet executed in the client machine instead of make the signature in the server side passing the key because this option it's not possible.
Hope this helps,