BIO_get_mem_ptr返回0作为长度和输出

时间:2017-02-27 07:48:30

标签: c openssl ssl-certificate

这里我试图将生物文件的大小设为,

long res = BIO_get_mem_ptr(certBio, &bptr);
length = bptr->length; // is the length

我从一些stackoverflow问题中获取了此示例代码。我已经尝试了很多次,但BIO_get_mem_ptrnull中给出bptr指针,返回值为0。我在任何参考站点都找不到与此问题相关的任何解决方案。

这是源代码,

int pass_cb(char *buf, int size, int rwflag, void *u)
{
    int len;
    char *tmp;  
    tmp = "123456";
    len = strlen(tmp);

    if (len <= 0) 
        return 0; 
    if (len > size) 
        len = size;
    memcpy(buf, tmp, len);
    return len;
}

int main(void)
{  
    X509 *x509;    
    int length = 0;

    unsigned char data[1000];
    unsigned char *buffer = NULL;
    buffer = data; 

    BIO *certBio = BIO_new(BIO_s_file()); 
    // BIO *certBio = BIO_new(BIO_s_mem());  -> have tried this one too gives the same result
    BUF_MEM *bptr = 0;  

    BIO_read_filename(certBio, "E:\\share\\Folder\\TempCert.pem");

    x509 = PEM_read_bio_X509_AUX(certBio, NULL, pass_cb, NULL); 

    long res = BIO_get_mem_ptr(certBio, &bptr);
    length = bptr->length;

    memset(&buffer, 0, 1000);

    int  ret = BIO_read(certBio, &buffer, length);   

    BIO_free_all(certBio);
    CertFreeCertificateContext(pContext);  
    CertCloseStore(hStore, 0); 
    return 0;
}

这里造成的问题是什么,

1 个答案:

答案 0 :(得分:1)

正如您在The Man上看到的bio_get_mem_ptr想要一个memory BIO

  

内存BIO是源/宿BIO,它使用内存作为其I / O.写入存储器BIO的数据存储在BUF_MEM结构中,该结构适当地扩展以容纳存储的数据。

您正在尝试使用文件,因此您应该使用bio_s_file的{​​{3}}上的示例代码