Is there a way to generate PrivateKey from byte array? I got this byte array using getEncoded() method, but now I have to convert it back to PrivateKey.
Thanks, Vuk
I was looking for this answer too and finally found it. keyBytes is a byte array originally created with getEncoded().
//add BouncyCastle as a provider if you want
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//create a keyfactory - use whichever algorithm and provider
KeyFactory kf = KeyFactory.getInstance("DSA", "BC");
//for private keys use PKCS8EncodedKeySpec; for public keys use X509EncodedKeySpec
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey pk = kf.generatePrivate(ks);
I've never done anything for JavaCard but from this post, it looks like you can use the KeyFactory class. You'll probably need to download the BouncyCastle library.
As stated on the Java docs
Keys are generally obtained through key generators, certificates, or various Identity classes used to manage keys. Keys may also be obtained from key specifications (transparent representations of the underlying key material) through the use of a key factory.
The KeyFactory class can help you out with this.
Throw away the encoded byte array. On JavaCard there is AFAIR no way to decode it directly - you have to set the different key components separately.
For example an RSAPrivateKey needs to be initialized with the exponent and the modulus:
rsaPrivate = (RSAPrivateKey) javacard.security.KeyBuilder.buildKey
(javacard.security.KeyBuilder.TYPE_RSA_PRIVATE,
javacard.security.KeyBuilder.LENGTH_RSA_512, false);
byte[] exponent = {(byte) 7};
byte[] modulus = {(byte) 33};
rsaPrivate.setExponent(exponent, (short) 0, (short) exponent.length);
rsaPrivate.setModulus(modulus, (short) 0, (short) modulus.length);
BTW: For JavaCard questions I recommend the JavaCard Forum in the Oracle forums. If you search there for RSAPrivateKey you will find some interesting posts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With