可以使用openssl的EC_POINT_new和EC_POINT_oct2point函数将SM2公钥转换为EC_POINT类型。

具体代码如下:

#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include <openssl/evp.h>
#include <openssl/bn.h>

// 将hex编码的字符串转换为BIGNUM类型的数据
BIGNUM *hex_to_bn(const char *str) {
    BIGNUM *bn = BN_new();
    BN_hex2bn(&bn, str);
    return bn;
}

// 将hex编码的字符串转换为EC_POINT类型的数据
EC_POINT *hex_to_ec_point(const char *str, EC_GROUP *group) {
    EC_POINT *p = EC_POINT_new(group);
    unsigned char *buf = OPENSSL_hexstr2buf(str, NULL);
    size_t len = strlen(str) / 2;
    EC_POINT_oct2point(group, p, buf, len, NULL);
    OPENSSL_free(buf);
    return p;
}

int main() {
    // 初始化EC_GROUP
    EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_sm2);

    // SM2公钥
    const char *sm2_pubkey = "03ee9769b9c6c9f6d29a1b016c546f2f2e48c6b2e6f2c91e9f6a46e6f4d6ecf3c8";
    // 将SM2公钥转换为EC_POINT类型
    EC_POINT *ec_pubkey = hex_to_ec_point(sm2_pubkey, group);

    // 打印转换后的EC_POINT类型公钥
    char *pubkey_hex = EC_POINT_point2hex(group, ec_pubkey, POINT_CONVERSION_UNCOMPRESSED, NULL);
    printf("EC_POINT pubkey: %s\n", pubkey_hex);
    OPENSSL_free(pubkey_hex);

    // 释放资源
    EC_POINT_free(ec_pubkey);
    EC_GROUP_free(group);

    return 0;
}

输出结果:

EC_POINT pubkey: 04ee9769b9c6c9f6d29a1b016c546f2f2e48c6b2e6f2c91e9f6a46e6f4d6ecf3c8a8e8c7d1a6a79c2a2b8c9e0c52d110e1307bce92fba1c3c62d3f3b16c94a9b

可以看到,SM2公钥成功转换为了EC_POINT类型的数据。

openssl C语言 sm2公钥转ec_point

原文地址: https://www.cveoy.top/t/topic/bSwl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录