user1662202
user1662202

Reputation: 61

How do I create an RSAPrivateKey instance from a byte array?

Hello I am trying to decrypt a file that is encrypted with RSA public key. I have a 3072-bit RSA private key corresponding to pubkey. The file contains the raw bytes of a PKCS8 encoding of the key. which i have in a byte array rsa_priv.

public void decrypt()
{
try
{
    SecretKeySpec sk=new SecretKeySpec(rsa_priv,"RSA/EBC/PKCS8");
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, sk,new IvParameterSpec(iv));
     //OAEPWithSHA-512AndMGF1Padding        
     byte temp[];
     temp=dec.doFinal(sess);
     String t=temp.toString();
     System.out.println("Session key is:"+ t);
     //session=dec(sess,rsa_priv);OAEPWithSHA-256AndMGF1Padding
}
catch (Exception e)
{
    System.out.println("Exception occured:"+ e);
}
}

when i run this code i get the following

Exception occured:java.security.InvalidKeyException: No installed provider 
supports this key: javax.crypto.spec.SecretKeySpec

I have imported these

import java.io.*;
import javax.crypto.*; 
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.KeyGenerator;
import java.security.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.OAEPParameterSpec;

someone please help me

Upvotes: 6

Views: 9251

Answers (3)

Maarten Bodewes
Maarten Bodewes

Reputation: 94078

Presuming you only have the inner encoding (such as provided by RSAPrivateKey.getEncoded()) and not an actual PKCS#8 encrypted RSA private key:

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(rsa_priv);
KeyFactory rsaFact = KeyFactory.getInstance("RSA");
RSAPrivateKey key = (RSAPrivateKey) rsaFact.generatePrivate(spec);

Upvotes: 6

Jumbogram
Jumbogram

Reputation: 2259

There are several problems.

First, it's ECB mode, not EBC; that's the first error you're getting.

Second, an RSA key isn't a SecretKeySpec.

How to read a password encrypted key with java? shows a method for retrieving the RSA key, and once you have that, http://www.flexiprovider.de/examples/ExampleRSA.html shows how to use it.

Upvotes: 1

Zoltán
Zoltán

Reputation: 22196

You should really just copy and paste the error into Google before posting it here.

This probably solves your problem.

Basically, you need an init() method setting the provider as described in the link.

/**
 * Init java security to add BouncyCastle as an RSA provider
 */
public static void init() {
   Security.addProvider(new BouncyCastleProvider());
}

For this you will need to import the BouncyCastle library.

Upvotes: 0

Related Questions