使用d2i_RSAPublicKey函数

时间:2018-06-10 00:39:47

标签: c openssl rsa public-key-encryption public-key

我从服务器获得RSA public key。 我需要从密钥中提取模数和公共指数来​​执行RSA操作。 我必须用C语言代码来解决这个问题,而不是shell命令。 我编写了以下测试代码,d2i_RSAPublicKey函数发生了错误。

null pointer函数会返回d2i_RSAPublicKey

void fnStr2Hex(unsigned char* out, char* in) { 
    int data_len = strlen(in); 
    unsigned char * pStr = in; 
    int i; 

    for(i=0; i<data_len/2; i++) { 
        char buf[3] = {0,}; 
        memcpy(buf, pStr, 2); 
        out[i] = (unsigned char)strtol(buf, NULL, 16); 
    pStr+=2; 
    } 
}


int der_test() { 
    BIO *STDout = NULL; 
    RSA *pub_rsa = NULL; 
    char raw_data[] =
        "30819F300D06092A864886F70D010101050003818D0030818902818100AA1"\
        "8ABA43B50DEEF38598FAF87D2AB634E4571C130A9BCA7B878267414FAAB8B"\
        "471BD8965F5C9FC3818485EAF529C26246F3055064A8DE19C8C338BE5496C"\
        "BAEB059DC0B358143B44A35449EB264113121A455BD7FDE3FAC919E94B56F"\
        "B9BB4F651CDB23EAD439D6CD523EB08191E75B35FD13A7419B3090F24787B"\
        "D4F4E19670203010001"; 

    int data_len = strlen(raw_data);  
    unsigned char * pArr = (unsigned char *)malloc(data_len); 
    memset(pArr, 0x00, data_len); 

    // raw_data is a string. Therefore, conversion to hexa form is necessary..
    fnStr2Hex(pArr, raw_data); 

    STDout=BIO_new_fp(stdout,BIO_NOCLOSE); 

    pub_rsa=d2i_RSAPublicKey(NULL,&pArr,(long)data_len); 

    if(pub_rsa == NULL) { 
        printf("error : failed d2i_RSAPublicKey \n"); 
        return -1; 
    } 

    BN_print(STDout,pub_rsa->n);   // print modulus bignum 
    BN_print(STDout,pub_rsa->e);  //  print exponent bignum 

    return 0; 
} 

int main() {
    der_test();

    return 0;
}

如果您知道需要做什么才能让d2i_RSAPublicKey正常工作,请告诉我。 请注意,raw_data中的RSA public key具有以下站点的密钥: https://crypto.stackexchange.com/questions/18031/how-to-find-modulus-from-a-rsa-public-key

这似乎是正常运作的关键。

0 个答案:

没有答案