Create PrivateKey from byte array

Vuk picture Vuk · Jan 5, 2011 · Viewed 16.9k times · Source

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

Answer

marchica picture marchica · Jun 16, 2011

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.