Read certificate files from memory instead of a file using OpenSSL

后端 未结 4 1058
遇见更好的自我
遇见更好的自我 2020-12-09 04:59

I have a server which would listen on HTTPS using OpenSSL. For this, I have to provide the certificate to use. However, the current implementation uses a filename to be prov

4条回答
  •  情话喂你
    2020-12-09 05:41

    The other snippets will only load one certificate. The content of files like http://curl.haxx.se/ca/cacert.pem that contain a lot of different certificates need a new approach. This is adapted from openssl 1.0.1p (mostly openssl-1.0.1p\crypto\x509\by_file.c, char* buf contains the content of a *.pem file, ctx is a boost::asio::ssl::context), add error handling on your own:

    BIO *cbio = BIO_new_mem_buf((void*)buf, (int)length);
    X509_STORE  *cts = SSL_CTX_get_cert_store(ctx.native_handle());
    if(!cts || !cbio)
       return false;
    X509_INFO *itmp;
    int i, count = 0, type = X509_FILETYPE_PEM;
    STACK_OF(X509_INFO) *inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
    
    if (!inf)
    {
        BIO_free(cbio);//cleanup
        return false;
    }
    //itterate over all entries from the pem file, add them to the x509_store one by one
    for (i = 0; i < sk_X509_INFO_num(inf); i++) {
        itmp = sk_X509_INFO_value(inf, i);
        if (itmp->x509) {
              X509_STORE_add_cert(cts, itmp->x509);
              count++;
        }
        if (itmp->crl) {
              X509_STORE_add_crl(cts, itmp->crl);
              count++;
        }
    }
    sk_X509_INFO_pop_free(inf, X509_INFO_free); //cleanup
    BIO_free(cbio);//cleanup
    

提交回复
热议问题