Varun
Varun

Reputation: 51

Encrypt data using private key in C and decrypting data using public key in Java

I have use case where i want to to encrypt some data using private key in C and decrypt it using public key in java.

I generated the the public/private key using openssl. I am able to run a c code for encrypting the data using private key.

Something like following code :

#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>

int padding = RSA_PKCS1_PADDING;

char * data;
char *encrypted;

FILE * fp = fopen(<private_key_file>,"rb");
RSA *rsa= RSA_new() ;
rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
RSA_private_encrypt(data_len,data,encrypted,rsa,padding);

This works fine and i am also able to decrypt it using public key in C. I am not able to decrypt the same using public key in Java. For this, I converted the public key to DER format : $ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

I am using following code

public String decrypt(byte[] encrypted) throws Exception
{
    Cipher cipher = Cipher.getInstance("RSA");

    KeyFactory kf = KeyFactory.getInstance("RSA");

    byte[] encKey = readFromFile(PUBLIC_KEY_FILE, false);

    X509EncodedKeySpec ks = new X509EncodedKeySpec(encKey);

    PublicKey pk = kf.generatePublic(ks);

    cipher.init(Cipher.DECRYPT_MODE, pk);

    byte[] plainText = cipher.doFinal(encrypted);

    return new String(plainText,"UTF-8");
}

I get the following exception with my java code.

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2121)
at AssyncKeyEncryptTest.decrypt(AssyncKeyEncryptTest.java:198)
at AssyncKeyEncryptTest.test(AssyncKeyEncryptTest.java:45)
at AssyncKeyEncryptTest.main(AssyncKeyEncryptTest.java:32)

Can someone please help me in fixing the error in decrypting the data using public key in java ?

Upvotes: 2

Views: 1697

Answers (2)

Gyan
Gyan

Reputation: 1176

Try "RSA/None/PKCS1Padding" instead of "RSA". If you are unable to find a Cipher instance with "RSA/None/PKCS1Padding" then try adding a security provider like Bouncy Castle Provider.
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Adding the bouncy castle dependency should be straightforward enough.

http://www.bouncycastle.org/latest_releases.html

Upvotes: 1

flo
flo

Reputation: 10281

The stacktrace suggests different padding between encryption and decryption.

Try "PKCS1Padding" as instance for decryption as you used it while encrypting.

Upvotes: 2

Related Questions