RSA在java上加密,无法通过openssl API在c++上解密

问题描述 投票:0回答:1

在Java端:

  • 使用bouncycastle获取密钥对,privateKey和publicKey

  • 用私钥加密原始消息1,得到加密消息2

  • 用publicKey解密加密的message2就可以了,成功得到相同的原始message1

在 C++ 方面:

  • 基于openssl,“RSA_public_decrypt”和“RSA_private_encrypt”API

  • 使用相同的publicKey(在java端生成)解密message2,返回一个每个字节都填充0的缓冲区,RSA_public_decrypt返回成功。

另外:

  • 在c++端,如果使用私钥对原始message1进行加密,得到加密后的message3,然后用公钥解密,成功得到message1。但message3与加密的message2(java端)不一样。

  • 以上都使用了RSA_NO_PADDING

  • 在java端,加密多次,得到相同的消息2

  • 在C++端,加密更多次,也得到相同的消息3。但message2与message3不一样。

问题是如何在c++端解密以获得在java端加密的原始消息1?

谢谢!

java c++ openssl rsa bouncycastle
1个回答
0
投票
it works ok, thanks for all the reply!
here is the c code(use public key to decrypt with openssl api):

#include <stdio.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>

RSA* createRSA(unsigned char * key) {
    RSA *rsa = NULL;
    BIO *keybio = NULL;
    keybio = BIO_new_mem_buf(key, -1);
    if (keybio == NULL) {
        return 0;
    }
    return PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);
}

int main() {
    char encrypted_data[] = {0x62,0xe2,0xe6,0xfd,0xca,0x69,0x39,0x2f,0x0f,0x07,0x3c,0x27,0xd7,0x49,0x2c,0xd6,0x6e,0xec,0xa0,0xdd,0x7c,0xa9,0xce,0x0a,0xad,0x4a,0x68,0xa2,0x2c,0x99,0xec,0xe9,0xa0,0x3c,0x72,0x66,0xf9,0xb1,0x59,0x11,0x7e,0x64,0x87,0x22,0xa7,0x4a,0x66,0xe2,0x8b,0x51,0xa5,0x6a,0x93,0x92,0x3f,0x57,0xae,0xea,0xfa,0xe7,0x6b,0x1b,0xae,0x8f};
    char publicKey[]="-----BEGIN PUBLIC KEY-----\n"\
                     "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJVdq5JlvtxJT4CqwEceW4M4AKFbDmJE\n"\
                     "H2K0a4aXmeHqedlsQgRePVCDgiiCC7kr1DEkP3+9uOUHDUtvIIoE4VsCAwEAAQ==\n"\
                     "-----END PUBLIC KEY-----\n";
    unsigned char decrypted[1024]= {0};
    int decrypted_length = RSA_public_decrypt(sizeof(encrypted_data), encrypted_data, decrypted, createRSA(publicKey), RSA_NO_PADDING);
    if(decrypted_length == -1) {
        return -1;
    }
    printf("decrypted by openssl:\n");
    for(int i=0; i<decrypted_length; i++) {
        printf("%02x ",(unsigned char)decrypted[i]);
    }
    printf("\n");
}
© www.soinside.com 2019 - 2024. All rights reserved.