使用openssl加载公共密钥-无效的编码

时间:2019-01-20 08:29:41

标签: c++11 openssl public-key ecdsa

我开始使用openssl。 我想使用公共密钥来检查签名。但是目前,我无法使用openssl读取我的公钥。

这是我的源代码:

#include <iostream>

#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/err.h>

bool verifyPublicKey(const std::string &sRawPublicKey);
void printAllError();


int main(int argc, char* argv[])
{
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " PUBLIC KEY" << std::endl;
        return EXIT_FAILURE;
    }

    std::string sPublicKey = argv[1];

    std::cout << "Key: " << sPublicKey << std::endl;

    bool bRes = verifyPublicKey(sPublicKey);

    if (!bRes)
    {
        std::cerr << "verifyPublicKey failled" << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

bool verifyPublicKey(const std::string &sRawPublicKey)
{
    bool bRes = false;

    EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    EC_KEY_set_conv_form(eckey, POINT_CONVERSION_UNCOMPRESSED);

    unsigned char *p_RawPublicKey = new unsigned char[sRawPublicKey.length() + 1];
    std::copy(sRawPublicKey.begin(), sRawPublicKey.end(), p_RawPublicKey);
    const unsigned char *pubkey_raw_p = p_RawPublicKey;

    o2i_ECPublicKey(&eckey, &pubkey_raw_p, sRawPublicKey.size());

    if (!EC_KEY_check_key(eckey))
    {
        EC_KEY_free(eckey);
        bRes = false;
        printAllError();
    }
    else
    {
        EC_KEY_free(eckey);
        bRes = true;
    }

    return bRes;
}

void printAllError()
{
    while (ERR_peek_last_error() != 0)
    {
        std::cerr << ERR_error_string(ERR_get_error(), nullptr) << std::endl;
    }
}

我使用以下公共密钥运行它:

  

3059301306072A8648CE3D020106082A8648CE3D03010703420004E297417036EB4C6404CC9C2AC4F28468DD0A92F2C9496D187D2BCA784DB49AB540B9FD9ACE0BA49C8532825954755EC10246A71AF2AEE9AEC34BE683CD>

ASN.1解码器:

SEQUENCE {    
    SEQUENCE {
        OBJECTIDENTIFIER 1.2.840.10045.2.1 (ecPublicKey)
        OBJECTIDENTIFIER 1.2.840.10045.3.1.7 (P-256)    
    }
    BITSTRING 0x04E297417036EB4C6404CC9C2AC4F28468DD0A92F2C9496D187D2BCA784DB49AB540B9FD9ACE0BA49C8532825954755EC10246A71AF2AEE9AEC34BE683CDDFD212
    : 0 unused bit(s) 
}

在ASN.1中,我注意到我使用的密钥格式正确: 0x04 ||十六进制(x)|| HEX(y),z = 0x04。

程序的输出如下:

  

键:3059301306072A8648CE3D020106082A8648CE3D03010703420004E297417036EB4C6404CC9C2AC4F28468DD0A92F2C9496D187D2BCA784DB49AB540B9FD9ACE0BA49C8532825954755EC10246A71AF2AEE9AEC34BE683      

错误:10067066:椭圆曲线例程:ec_GFp_simple_oct2point:编码无效

     

错误:10098010:椭圆曲线例程:o2i_ECPublicKey:EC lib

     

错误:1010206A:椭圆曲线例程:ec_key_simple_check_key:指向无穷大verifyPublicKey失败

我迷路了。你有解释吗? 而且,可以通过仅给出x和y(不带ASN.1标头)来走得更远。

谢谢

1 个答案:

答案 0 :(得分:0)

看起来您应该将原始点输入功能o2i_ECPublicKey(),而无需ASN.1框架。