Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PrivateKey from byte array

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

like image 712
Vuk Avatar asked Jan 05 '11 01:01

Vuk


3 Answers

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.

like image 131
marchica Avatar answered Oct 09 '22 00:10

marchica


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.

like image 26
Patrick Avatar answered Oct 09 '22 01:10

Patrick


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.

like image 45
Robert Avatar answered Oct 08 '22 23:10

Robert