如何在openssl ecc中以十六进制格式获取私钥

时间:2018-11-03 07:51:22

标签: c++ openssl

代码:

EC_KEY *key;
if (NULL == (key = EC_KEY_new_by_curve_name(NID_secp224r1)))
    handleErrors();
if (1 > EC_KEY_generate_key(key)) handleErrors();
const BIGNUM *prv = EC_KEY_get0_private_key(key);
const EC_GROUP *group = EC_KEY_get0_group(key);
const EC_POINT *pub = EC_KEY_get0_public_key(key);
char* hexPubkey = EC_POINT_point2hex(group, pub, EC_KEY_get_conv_form(key), NULL);
char* hexPrikey=BN_bn2hex(prv);

我的结果:

  

hexPubkey:04EAD3AF4BA89F513B2D89FC749C43CC7B95523F1BD40A5713C5228F91B5F928D43B396C64A3293053550065C02E9A06B4FB078C4944BD0933   长度:57

     

hexPrikey:5D5356F3551602A89710DA40CC24FB6CDBB851FE612C977C9AB0F393   长度:114

     

正确的结果:   hexPubkey:04381​​987517AEEDB6F83FAA0EB60EFF4C1B7A78D66FF17CB04D92B37588826A64B78E0B3A965C72438860D4B3897893BB31397D1625EEA0E41   长度:57

     

hexPrikey:30820144020101041C20F21D6B7FE0D5E1D21C6B57AFE6FAD8A5A5AC31AE0596B972E01877A081E23081DF020101302806072A8648CE3D0101021D00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000013053041CFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE041CB4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4031500BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5043904B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34021D00FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D020101A13C033A0004381​​987517AEEDB6F83FAA0EB60EFF4C1B7A78D66FF17CB04D92B37588826A64B78E0B3A965C72438860D4B3897893BB31397D1625EEA0E41

     

长度:328

从私钥的长度来看,我的私钥显然是错误的,不是我的书写方法错误吗?

1 个答案:

答案 0 :(得分:0)

    BIO *bio = BIO_new(BIO_s_mem());
    PEM_write_bio_ECPrivateKey(bio, key, NULL, NULL, 0, NULL, NULL);
    int keylen = BIO_pending(bio);
    char *pem_key = (char *) calloc(keylen + 1, 1); 
    BIO_read(bio, pem_key, keylen);

    cout << pem_key << endl;

    BIO_free_all(bio);
    EC_KEY_free(key);
    free(pem_key);