go-gmsm cgo庫
介紹
基于github.com/emmansun/gmsm庫編寫的SM2對C
開放的庫
特性:非對稱加密、不支持跨平臺編譯
git地址:https://gitee.com/state-secret-series/go-gmsm.git
軟件架構
Go、Cgo、mod
安裝教程
克隆倉庫
git clone https://gitee.com/state-secret-series/go-gmsm.git
進入go-gmsm目錄
cd go-gmsm
下載依賴
go mod tidy
cgo靜態編譯
go build -x -buildmode=c-archive -o libgosm2.a
編譯完成后生成 libgosm2.a 、libgosm2.h 文件
使用教程
在C語言中調用
int main() {GO_SM2_KEY_PAIR key_pair;GO_SM2_SIGNATURE_STRUCT sm2_sig;GO_SM2_ENCRYPT_STRUCT ciphertext;GO_SM2_DECRYPT_STRUCT plaintext;GO_SM2_ERROR_STRUCT error;unsigned char msg[] = {"這是測試數據"};int msg_len = (int) (strlen((char *) msg));unsigned char user_id[] = {"1234567812345678"};int user_id_len = (int) (strlen((char *) user_id));
// unsigned char *ciphertext = NULL;
// int ciphertext_len=0;int error_code;error_code = GenerateKeyPair(&key_pair,&error);if(error_code){printf("GenerateKeyPair failed!%s\n", error.error);return error_code;}print_hex("公鑰", key_pair.pub_key, GO_SM2_PUBKEY_LEN);print_hex("私鑰", key_pair.pri_key, GO_SM2_PRIKEY_LEN);GoSm2SignData(key_pair.pri_key, GO_SM2_PRIKEY_LEN, msg, msg_len, user_id, user_id_len,GO_SM2_MODE_DEFAULT, &sm2_sig,&error);print_hex("簽名", sm2_sig.sig, sm2_sig.sig_len);error_code = Sm2SignVerify(key_pair.pub_key, GO_SM2_PUBKEY_LEN, msg, msg_len, user_id, user_id_len, &sm2_sig,&error);if (error_code) {printf("Verify SM2 signature failed!%d\n", error_code);return error_code;}printf("Verify SM2 signature succeeded!\n");error_code = Sm2Encrypt(key_pair.pub_key, GO_SM2_PUBKEY_LEN, msg, msg_len, GO_SM2_MODE_ANS1, GO_SM2_ORDER_C1C2C3, &ciphertext,&error);if (error_code) {printf("Sm2Encrypt SM2 Sm2Encrypt failed!%d\n", error_code);return error_code;}printf("Sm2Encrypt SM2 Sm2Encrypt succeeded!\n");print_hex("加密結果", ciphertext.ciphertext, ciphertext.ciphertext_len);error_code = Sm2Decrypt(key_pair.pri_key,GO_SM2_PRIKEY_LEN,ciphertext.ciphertext, ciphertext.ciphertext_len,GO_SM2_ORDER_C1C2C3,&plaintext,&error);if (error_code) {printf("Sm2Decrypt SM2 Sm2Decrypt failed!%d\n", error_code);return error_code;}printf("Sm2Decrypt SM2 Sm2Decrypt succeeded!\n");print_hex("解密結果", plaintext.plaintext, plaintext.plaintext_len);printf("文明:%s\n", plaintext.plaintext);return 0;
}