sm2算法演示
- 获取曲线参数
- 生成秘钥对
- 自定义userid
- 加密解密
- 签名验签
- 输出公私钥对
#include <openssl/evp.h>
#include <string.h>
#include <openssl/ec.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <iostream>
#include <stdlib.h>
void sm2test() {
EC_KEY* key = EC_KEY_new();
EC_GROUP* gm_group = EC_GROUP_new_by_curve_name(NID_sm2);
int ret = EC_KEY_set_group(key, gm_group);
using namespace std;
if (!ret) {
cout << "set group error" << endl;
return;
}
ret = EC_KEY_generate_key(key);
if (!ret) {
cout << "EC_KEY_generate_key error" << endl;
return;
}
const BIGNUM* pri = EC_KEY_get0_private_key(key);
const EC_POINT* point = EC_KEY_get0_public_key(key);
EVP_PKEY* pkey = EVP_PKEY_new();
ret = EVP_PKEY_set1_EC_KEY(pkey, key);
if (!ret) {
cout << "EVP_PKEY_set1_EC_KEY error" << endl;
return;
}
EVP_PKEY_CTX* pkeyCtx = EVP_PKEY_CTX_new(pkey, NULL);
const char* id = "adgdfdfdfdfd";
EVP_PKEY_CTX_set1_id(pkeyCtx, id, strlen(id));
EVP_PKEY_encrypt_init(pkeyCtx);
const char* data = "hello";
unsigned char* out = (unsigned char*)malloc(strlen(data) + 96);
size_t outlen = strlen(data) + 96;
ret = EVP_PKEY_encrypt(pkeyCtx, out, &outlen, (const unsigned char*)data, strlen(data));
if (!ret) {
cout << "EVP_PKEY_encrypt error" << endl;
return;
}
EVP_PKEY_decrypt_init(pkeyCtx);
unsigned char debuf[10] = { 0 };
size_t dlen = 10;
EVP_PKEY_decrypt(pkeyCtx, debuf, &dlen, out, outlen);
debuf[dlen] = '\0';
printf("%s\n", debuf);
EVP_PKEY_sign_init(pkeyCtx);
const char* tbs = "hello";
size_t signlen;
ret = EVP_PKEY_sign(pkeyCtx, NULL, &signlen, (const unsigned char*)tbs, (size_t)strlen((const char*)tbs));
if (!ret) {
cout << "EVP_PKEY_sign error" << endl;
return;
}
string str(signlen, '\0');
ret = EVP_PKEY_sign(pkeyCtx, (unsigned char*)str.data(), &signlen, (const unsigned char*)tbs, (size_t)strlen((const char*)tbs));
if (!ret) {
cout << "EVP_PKEY_sign error" << endl;
return;
}
EVP_PKEY_verify_init(pkeyCtx);
ret = EVP_PKEY_verify(pkeyCtx, (unsigned char*)str.data(), signlen, (const unsigned char*)tbs, (size_t)strlen((const char*)tbs));
if (!ret) {
cout << "EVP_PKEY_verify error" << endl;
return;
}
ret = PEM_write_ECPrivateKey(stdout, key, NULL, NULL, 0, NULL, NULL);
if (!ret) {
cout << "PEM_write_ECPrivateKey error" << endl;
return;
}
ret = PEM_write_EC_PUBKEY(stdout, key);
if (!ret) {
cout << "PEM_write_EC_PUBKEY error" << endl;
return;
}
}