Create PrivateKey from byte array

可紊 提交于 2019-11-30 14:03:52

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.

Either you have to decode the PKCS#8 encoded blob yourself (ASN.1 BER parsing) and set the components, or you can get the components from the private key (at least the private exponent and modulus) as Java BigIntegers, convert those to unsigned byte arrays and set them in the Java Card API as explained by Robert. PKCS#8 parsing can be done on Java Card but it's a pretty horrendous excercise.

Amal Kallel
//ECDSA algo of signature type prime256 of key
Security.addProvider(new BouncyCastleProvider());
KeyFactory factory = KeyFactory.getInstance("ECDSA", "BC");
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, privKey), spec);
PrivateKey privateKey = factory.generatePrivate(ecPrivateKeySpec);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!