5

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

erickson
  • 265,237
  • 58
  • 395
  • 493
user1662202
  • 51
  • 1
  • 2
  • Welcome new user! Don't forget to view the changes made by Jeremy D. Please do follow up on your question and don't forget to accept one of the answers that solves your issue. – Maarten Bodewes Sep 12 '12 at 18:13

3 Answers3

6

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);
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
1

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.

Community
  • 1
  • 1
Jumbogram
  • 2,249
  • 1
  • 20
  • 24
0

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.

Zoltán
  • 21,321
  • 14
  • 93
  • 134