以下是如何通过提供一个 EC_KEY 的公钥集等于公共证书的公钥和私钥设置为任何非零值来绕过 openssl 验证规则(在我的示例中,我刚刚将其设置为公钥的 X 坐标)。创建密钥并将其存储在文件中后,可以将其作为常规私钥传递给 SSL_Context。
我认为,理想情况下,openssl 应该以更系统和更透明的方式解决这个问题,但在完成之前,建议的解决方案可以用作解决方法:
#include <string.h>
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
static char * my_prog = "dummykey";
static char * key_file = NULL;
static char * cert_file = NULL;
int verbose = 0;
static void print_help() {
fprintf(stderr,"Version: %s\nUSAGE: %s -cert in_cert_file -key out_key_file\n",
VERSION, my_prog);
}
static void parse_args(int argc, char** argv) {
argc--;
argv++;
while (argc >= 1) {
if (!strcmp(*argv,"-key")) {
key_file = *++argv;
argc--;
}
else if (!strcmp(*argv,"-cert")) {
cert_file = *++argv;
argc--;
}
else if (!strcmp(*argv,"-v")) {
verbose = 1;
}
else {
fprintf(stderr, "%s: Invalid param: %s\n", my_prog, *argv);
print_help();
exit(1);
}
argc--;
argv++;
}
if (key_file == NULL || cert_file == NULL ) {
print_help();
exit(1);
}
}
int get_curve_nid(X509 *c) {
int ret = 0;
if (c->cert_info->key->algor->parameter) {
ASN1_TYPE *p = c->cert_info->key->algor->parameter;
if (p && p->type == V_ASN1_OBJECT) {
ret = OBJ_obj2nid(c->cert_info->key->algor->parameter->value.object);
}
}
return ret;
}
int main(int argc, char** argv) {
X509 *c=NULL;
FILE *fp=NULL;
FILE *ofp=NULL;
EC_POINT *ec_point = NULL;
BIGNUM *x = NULL;
BIGNUM *y = NULL;
EC_KEY *ec_key = NULL;
EC_GROUP *grp = NULL;
parse_args(argc, argv);
fp = fopen(cert_file, "r");
if (!fp) {
fprintf(stderr,"%s: Can't open %s\n", my_prog, cert_file);
return 1;
}
c = PEM_read_X509 (fp, NULL, (int (*) ()) 0, (void *) 0);
if (c) {
x = BN_new();
y = BN_new();
int len = c->cert_info->key->public_key->length-1;
BN_bin2bn(c->cert_info->key->public_key->data+1, len/2, x);
BN_bin2bn(c->cert_info->key->public_key->data+1+len/2, len/2, y);
EC_GROUP *grp = EC_GROUP_new_by_curve_name(get_curve_nid(c));
ec_key = EC_KEY_new();
int sgrp = EC_KEY_set_group(ec_key, grp);
int sprk = EC_KEY_set_private_key(ec_key, x);
if (sgrp && sprk) {
ec_point = EC_POINT_new(grp);
int ac = EC_POINT_set_affine_coordinates_GFp(grp, ec_point, x, y, BN_CTX_new());
int spub =EC_KEY_set_public_key(ec_key, ec_point);
ofp = fopen(key_file, "w");
int r = 0;
if (ofp) {
r = PEM_write_ECPrivateKey(ofp, ec_key, NULL, NULL, 0, NULL, NULL);
if (!r)
fprintf(stderr,"%s: Can't write EC key %p to %s\n", my_prog, ec_key, key_file);
}
else {
fprintf(stderr,"%s: Can't open %s\n", my_prog, key_file);
}
}
}
if (ec_key)
EC_KEY_free(ec_key);
if (grp)
EC_GROUP_free(grp);
if (x)
BN_free(x);
if (y)
BN_free(y);
if (c)
X509_free (c);
if (fp)
fclose(fp);
if (ofp)
fclose(ofp);
return 0;
}