cast RSAPrivateKey to PrivateKey and vice versa

1.8k views Asked by At

I've created an org.bouncycastle.asn1.pkcs.RSAPrivateKey using its static getInstance(byte[]) from a PKCS#1 formated DER bytes, now I want to cast(or change) this to PrivateKey, how to do that??

1

There are 1 answers

2
Buddhima Gamlath On

You can directly create the PrivateKey from an ASN.1 encoded bytes array.

public static PrivateKey makeKey(byte[] keyBytes) {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return privateKey;
}