1

i generated a public/private keypair using java. Since i want to add the key to my code (not as file) i used

byte[] priv = private_key.getEncoded() 

to get it as a byte array. To get back the private key from the byte array i use

PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(priv);

Decryption is working as expected. But now i want to use that key inside a c application using openssl. So i copied the byte array from java to c as a char[]. But i'm not able to convert this char[] into a private key to use it for decryption via RSA_public_decrypt(...) I tried

RSA *r = d2i_RSAPrivateKey(NULL,&priv, len);

but this always return a NULL pointer

Can anyone please give me a hint on how to do this in c language?

Edit: Meanwhile i checked the error code from openssl and it says

error:0D0680A8:lib(13):func(104):reason(168)

But i don't know whet to do with those error codes. A search on the net didn't help yet.

Many thanks in advance. Greetings, -chris-

2 Answers 2

1

Are you copying the encoded binary data or just the binary data read form the file?. See this How to load an RSA key from binary data to an RSA structure using the OpenSSL C Library?

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, i came across that post earlier. That's why i posted my code above.
I just copied the byte[] from my java source to the c source as a unsigned char[].
Looks like this is the one d2i_PKCS8_PRIV_KEY_INFO you should be using.You said it is working with PKCS8EncodedKeySpec.But d2i_RSAPrivateKey is for pkcs1.see this mail-archive.com/[email protected]/msg02730.html
1

Thanks to hint from srikanth yaradla i found the right direction. Here's how i did it:

const unsigned char private_key[] = {0x30,...};
size_t private_key_len = sizeof(private_key);
char* buf = (char*)malloc(private_key_len);
memcpy(buf, private_key, private_key_len);
BIO* mem=BIO_new_mem_buf(buf, private_key_len);
PKCS8_PRIV_KEY_INFO* p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(mem, NULL);
EVP_PKEY* pkey = EVP_PKCS82PKEY(p8inf);
RSA* r = EVP_PKEY_get1_RSA(pkey);

after doing that i now can easily decrypt data i get from the java part.

1 Comment

Don't forget to free the RSA* by callint RSA_free !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.