开发者

OpenSSL: Trying to use keying material obtain by handshake to locally encrypt data

开发者 https://www.devze.com 2023-04-03 05:03 出处:网络
This is the code: bool EncoderTLS::handshake() { int sock = getSocket(); SSL *ssl = SSL_new(ctx); BIO *sbio = BIO_new_socket(sock, BIO_NOCLOSE);

This is the code:

bool EncoderTLS::handshake()
{
    int sock = getSocket();
    SSL *ssl = SSL_new(ctx);
    BIO *sbio = BIO_new_socket(sock, BIO_NOCLOSE);
    SSL_set_bio(ssl, sbio, sbio);
    int r;
    int i = 0;
    while(i < ATTEMPTS)
    {
        int s;
        if((r = ((isServer) ? SSL_accept(ssl) :SSL_connect(ssl)) )<=0)
        {
            s = SSL_get_error(ssl,r);
            if (SSL_get_error(ssl,r) == SSL_ERROR_SYSCALL)
            {
                if (errno == 0) break;
                printf("errno = %d\n",errno);
                perror("Syscall error");
            }
        }
        if (s == SSL_ERROR_WANT_READ || s == SSL_ERROR_WANT_WRITE) usleep(10);
        else 
        {
            logger->log(Level::WARNING, "SSL handshake failed");
            return false;
        }
        i++;
    }
    if (!isServer && SSL_get_verify_result(ssl) != X509_V_OK) //Server authentication
    {
        logger->log(Level::WARNING, "couldn't verify certificate");
        printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
        return false;
    }
    BIO *test = BIO_new(BIO_s_mem());
    SSL_set_bio(ssl, test, test);
    SSL_write(ssl, "blablablablabla", 10);
    char **p;
    int length = BIO_get_mem_data(test,p);
    printf("Printing encoding of 'blablablab', of length %d:\n", length);
开发者_开发知识库    for(int j=0; j<length; j++)
        printf("%c", p[j]);
    printf("\n");
    return true;
}

I'd expect the data written by SSL_write towards the end would go into the BIO, and to memory. However, when I try to fetch the data from the BIO, it tells me it's length is 0.

What am I doing wrong?


Check what SSL_write() returns. Maybe it's SSL_ERROR_WANT_READ, in this case you must first read from your SSL connection and supply the read data to your SSL object. SSL_read() will do it for you if you call it before the second SSL_set_bio().

But when you will succeed with your SSL_write() - be aware that it won't be only encrypted data in your mem BIO. Protocol-related data will also be there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号