繁体   English   中英

C / C ++中的简单OpenSSL RSA加密使我头痛

[英]SIMPLE OpenSSL RSA Encryption in C/C++ is causing me headaches

求助:我很傻。 加密的第一个参数应该是key.size(),解密的第一个参数应该是RSA_size(myKey)。

大家好,我在弄清楚如何执行此操作时遇到了一些麻烦。

基本上,我只希望客户端和服务器能够互相发送加密的消息。

这将是极度不安全的,因为我正试图解决所有问题,所以我不妨从底层开始。

到目前为止,我已经使用了所有的密钥,但是加密/解密使我陷入了困境。

首先,我要使用C ++,但是其中大多数功能都需要C字符串,因此我所做的任何事情都可能导致问题。

请注意,在客户端,我收到有关解密的以下错误。

error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed

我不太了解填充的工作原理,所以不知道如何解决。

此处的任何一方都是相关变量,后跟代码。

客户:

RSA *myKey; // Loaded with private key
// The below will hold the decrypted message
unsigned char* decrypted = (unsigned char*) malloc(RSA_size(myKey));
/* The below holds the encrypted string received over the network. 
Originally held in a C-string but C strings never work for me and scare me 
so I put it in a C++ string */
string encrypted;

// The reinterpret_cast line was to get rid of an error message.
// Maybe the cause of one of my problems?
if(RSA_private_decrypt(sizeof(encrypted.c_str()), reinterpret_cast<const unsigned char*>(encrypted.c_str()), decrypted, myKey, RSA_PKCS1_OAEP_PADDING)==-1)
    {
        cout << "Private decryption failed" << endl;
        ERR_error_string(ERR_peek_last_error(), errBuf);
        printf("Error: %s\n", errBuf);
        free(decrypted);
        exit(1);
    }

服务器:

RSA *pkey; // Holds the client's public key
string key; // Holds a session key I want to encrypt and send
//The below will hold the encrypted message
unsigned char *encrypted = (unsigned char*)malloc(RSA_size(pkey));

// The reinterpret_cast line was to get rid of an error message.
// Maybe the cause of one of my problems?
if(RSA_public_encrypt(sizeof(key.c_str()), reinterpret_cast<const unsigned char*>(key.c_str()), encrypted, pkey, RSA_PKCS1_OAEP_PADDING)==-1)
        {
            cout << "Public encryption failed" << endl;
            ERR_error_string(ERR_peek_last_error(), errBuf);
            printf("Error: %s\n", errBuf);
            free(encrypted);
            exit(1);
        }

让我再说一次,以防万一,我知道我的代码很烂,但是我只是想建立一个框架来理解这一点。

很抱歉,这冒犯了您的资深编码员。

预先感谢你们提供的任何帮助!

可能不是唯一的问题,但是: RAS_xxxcrypt函数的第一个参数是缓冲区的字节数。 sizeof(key.c_str())不产生key中的字节数,它产生key.c_str()结果类型的sizeof(const char*) ,即sizeof(const char*) 您可能希望改为传递字符串中的字符数,这可以通过size()成员函数获得。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM