使用RSA公钥解密/加密大数据

时间:2016-08-30 21:38:25

标签: c++ encryption openssl rsa


我使用RSA公钥加密大数据,然后使用私钥解密 所以我的加密功能是:

unsigned char* encryptFile::rsaEncrypt( RSA *pubKey, const unsigned char* msg, int msg_len, int *enc_len )
{
    int rsa_size = RSA_size(pubKey);
    int block_size = rsa_size - 12;
    int blocks = msg_len/block_size;
    int rest = msg_len % block_size;
    unsigned char* enc = 0;
    int curr_len = 0;
    int i = 0;
    if (0 == rest) {
        enc = (unsigned char*)malloc(blocks*rsa_size + 1);
    }
    else {
        enc = (unsigned char*)malloc((blocks+1)*rsa_size + 1);
    }

    for (i = 0; i < blocks; i++) {
        if (0 > (curr_len = RSA_public_encrypt(block_size , msg + i*block_size, enc + i*rsa_size, pubKey, RSA_PKCS1_PADDING))) {
            printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
        }
        *enc_len += curr_len;
    }
        if (0 != rest) {
            if (0 > (curr_len = RSA_public_encrypt(rest , msg + i*block_size, enc + i*rsa_size, pubKey, RSA_PKCS1_PADDING))) {
            printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
        }
        *enc_len += curr_len;
    }
    if( *enc_len == -1 )
        printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
        cout << *enc_len << endl;
    return enc;
}

它工作正常!
现在,当我想要解密时,我使用此代码

int rsa_size = RSA_size(privKey);
int msg_len = encBinLen;
int block_size = rsa_size;
int blocks = msg_len/block_size;
int rest = msg_len % block_size;
unsigned char* enc = 0;
int curr_len = 0;
enc_len = 0;
int i = 0;
if (0 == rest) {
    enc = (unsigned char*)malloc(blocks*rsa_size + 1);
}
else {
    enc = (unsigned char*)malloc((blocks+1)*rsa_size + 1);
}
for (i = 0; i < blocks; i++) {
    if (0 > (curr_len = RSA_private_decrypt(block_size , msg + i*block_size, enc + i*rsa_size, privKey, RSA_PKCS1_PADDING))) {
        printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
    }
    enc_len += curr_len;
}
    if (0 != rest) {
        if (0 > (curr_len = RSA_private_decrypt(rest , msg + i*block_size, enc + i*rsa_size, privKey, RSA_PKCS1_PADDING))) {
        printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
    }
    enc_len += curr_len;
}
if( enc_len == -1 )
    printf("ERROR: RSA_public_encrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
cout << enc;

无论如何,当我运行时,一些数据被解密但我仍然看到一些奇怪的字符,如in this picture所示。 所以我只想了解我做错了什么?

2 个答案:

答案 0 :(得分:-1)

解决方案是使用hybrid encryption

对Artjom B&amp; amp; zaph

答案 1 :(得分:-1)

我认为您应该使用enc_len代替i*rsa_size作为RSA_private_decrypt(block_size , msg + i*block_size, enc + i*rsa_size, privKey, RSA_PKCS1_PADDING)调用中输出的移位器。