参考:ECDH秘钥交换的C程序
ECDH秘钥交换与SM2秘钥交换类似,下面是我从网上下到的ECDH秘钥交换的C程序
#include <openssl/ssl.h>
#define ECDH_SIZE 33
void handleErrors()
{
printf("Error occurred.\n");
}
static void disp(const char *str, const void *pbuf, const int size)
{
int i=0;
if(str != NULL){
printf("%s:\n", str);
}
if(pbuf != NULL && size > 0){
for(i=0;i<size;i++)
printf("%02x ", *((unsigned char *)pbuf+i));
putchar('\n');
}
putchar('\n');
}
int main() {
/* alice */
EC_KEY *ecdh = EC_KEY_new();
EC_POINT *point = NULL;
EC_POINT *point2c;
EC_GROUP *group;
unsigned char pubkey[ECDH_SIZE];
unsigned char shared[ECDH_SIZE];
int len;
//Generate Public
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);//NID_secp521r1
EC_KEY_generate_key(ecdh);
point = EC_KEY_get0_public_key(ecdh);
group = EC_KEY_get0_group(ecdh);
if(0 == (len = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, pubkey, ECDH_SIZE, NULL))) handleErrors();
printf("len=%d\n",len);
/* bob */
EC_KEY *ecdh2 = EC_KEY_new();
EC_POINT *point2 = NULL;
EC_POINT *pointc;
EC_GROUP *group2;
unsigned char pubkey2[ECDH_SIZE];
unsigned char shared2[ECDH_SIZE];
int len2;
//Generate Public
ecdh2 = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);//NID_secp521r1
EC_KEY_generate_key(ecdh2);
point2 = EC_KEY_get0_public_key(ecdh2);
group2 = EC_KEY_ge