Creating PrivateKey from byte array

Is there a way to generate PrivateKey from an array of bytes? I got this byte array using the getEncoded () method, but now I need to convert it to PrivateKey.

Thanks Wook

+7
source share
4 answers

I also searched for this answer and finally found it. keyBytes is an array of bytes, originally created using 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 have never done anything for JavaCard, but from this post it looks like you can use the KeyFactory class. You will probably need to download the BouncyCastle library.

+7
source

As stated in Java docs

Keys are usually obtained using key generators, certificates, or various identification classes used to manage keys. Keys can also be obtained from key specifications (transparent representations of the key's key material) using the factory key.

The KeyFactory class can help you with this.

+5
source

Discard the encoded byte array. On JavaCard, AFAIR does not have the ability to decode it directly - you need to install different key components separately.

For example, RSAPrivateKey needs to be initialized with a metric and module:

 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 on Oracle forums. If you are looking for RSAPrivateKey, you will find interesting posts.

+3
source

Either you must decode the encoded PKCS # 8 blob (parsing ASR.1 BER) yourself, either install the components, or you can get the components from the private key (at least the private exponent and module) as Java BigIntegers, convert them to unsigned bytes arrays and install them in the Java Card API, as Robert explained. PKCS # 8 parsing can be done on a Java Card, but this is a pretty terrifying exercise.

0
source

All Articles