"); //-->
基于Gmssl的SM2加解密算法Demo
GmSSL介绍
Gmssl介绍:http://gmssl.org/
当然本文也是参考 http://gmssl.org/
其中SM2为非对称算法
pair<string, string> GenKey(void) { EC_KEY *keypair = NULL; EC_GROUP *group1 = NULL; keypair = EC_KEY_new(); if(!keypair) { cout << "Failed to Gen Key" << endl; exit(1); } group1 = EC_GROUP_new_by_curve_name(NID_sm2p256v1); if(group1 == NULL){ cout << "Failed to Gen Key" << endl; exit(1); } int ret1 = EC_KEY_set_group(keypair, group1); if(ret1 != 1){ cout << "Failed to Gen Key" << endl; exit(1); } int ret2 = EC_KEY_generate_key(keypair); if(ret2 != 1){ cout << "Failed to Gen Key" << endl; exit(1); } size_t pri_len; size_t pub_len; char *pri_key = NULL; char *pub_key = NULL; BIO *pri = BIO_new(BIO_s_mem()); BIO *pub = BIO_new(BIO_s_mem()); PEM_write_bio_ECPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL); PEM_write_bio_EC_PUBKEY(pub, keypair); pri_len = BIO_pending(pri); pub_len = BIO_pending(pub); pri_key = new char[pri_len + 1]; pub_key = new char[pub_len + 1]; BIO_read(pri, pri_key, pri_len); BIO_read(pub, pub_key, pub_len); pri_key[pri_len] = '\0'; pub_key[pub_len] = '\0'; string public_key = pub_key; string private_key = pri_key; EC_KEY_free(keypair); BIO_free_all(pub); BIO_free_all(pri); delete [] pri_key; delete [] pub_key; return std::pair<string, string>(public_key, private_key); }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 已字符串形式的返回,主要考虑我们在实际运用中,可能需要传递密钥信息,所以生成的SM2公钥和私钥以字符串形式返回。 从字符串类型的密钥中生成出来EC_KEY对象 EC_KEY* CreateEC(unsigned char* key, int is_public) { EC_KEY *ec_key = NULL; BIO *keybio = NULL; keybio = BIO_new_mem_buf(key, -1); if (keybio==NULL) { cout << "Failed to Get Key" << endl; exit(1); } if(is_public) { ec_key = PEM_read_bio_EC_PUBKEY(keybio, NULL, NULL, NULL); } else { ec_key = PEM_read_bio_ECPrivateKey(keybio, NULL, NULL, NULL); } if(ec_key == NULL) { cout << "Failed to Get Key" << endl; exit(1); } return ec_key; }12345678910111213141516171819202122232425
这里使用的加密函数为SM2_encrypt_with_recommended
这里使用的解密函数为SM2_decrypt_with_recommended
下载:https://download.csdn.net/download/liulangaliulang/10884044
用例运行结果:
https://blog.csdn.net/liulangaliulang/article/details/85329878
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。