OpenSSL公开一个函数PEM_write_EC_PUBKEY() https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_EC_PUBKEY.html您可以使用它来将公钥写入 PEM 格式。您首先必须使用以下函数构建您的公钥EC_KEY_xyz() https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html家庭。以下代码片段输出(我认为)您正在寻找的内容stdout
:
#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/pem.h>
const char *xHex = "053b5b02d673e6f115b538de3587318821149d3e7bc65903f300b8cfffcacdaa";
const char *yHex = "75e5d460e9d407672ff86683b748b6e882b361fa2fdf78845f8a9a369f6d016e";
int main(
int argc,
char **argv)
{
EC_KEY *eckey = NULL;
BIGNUM *x = NULL, *y = NULL;
eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
BN_hex2bn(&x, xHex);
BN_hex2bn(&y, yHex);
EC_KEY_set_public_key_affine_coordinates(eckey, x, y);
EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
PEM_write_EC_PUBKEY(stdout, eckey);
BN_free(x);
BN_free(y);
EC_KEY_free(eckey);
}
结果是:
$ ./eckey
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEiSsGkRmvLkGTl7piCk9/j+k+2O5W
e7JoJ5UzJnkdGqvE9agv2adnlftoaZBM497eOsz/tua7uKZr9SwzzJVyVg==
-----END PUBLIC KEY-----
但是,您提供的坐标并不位于曲线上,如以下命令所示:
$ openssl ec -pubin -in <(./eckey) -pubout -text -noout
read EC key
unable to load Key
140735626654664:error:1006706B:elliptic curve routines:ec_GFp_simple_oct2point:point is not on curve:ecp_oct.c:417:
140735626654664:error:10098010:elliptic curve routines:o2i_ECPublicKey:EC lib:ec_asn1.c:1286:
140735626654664:error:100D708E:elliptic curve routines:ECKEY_PUB_DECODE:decode error:ec_ameth.c:208:
140735626654664:error:0B07707D:x509 certificate routines:X509_PUBKEY_get:public key decode error:x_pubkey.c:154:
140735626654664:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83: