引言
在信息安全領域,密碼算法是數據保護的核心基石。2010 年,中國國家密碼管理局發布了 SM2 橢圓曲線公鑰密碼算法,作為國產密碼標準的核心成員,它憑借高效安全的特性,逐步替代 RSA 等國際算法,廣泛應用于金融、政務、物聯網等關鍵領域。SM2 的誕生不僅是技術突破,更是國家信息安全戰略的重要布局。其基于橢圓曲線密碼學(ECC)的設計,在同等安全強度下,密鑰長度僅為 RSA 的 1/10,運算效率提升數倍。SM2 已成為 ISO/IEC 國際標準,并深度融入國產密碼生態體系,為構建安全可靠的網絡安全架構提供了堅實支撐。
一、核心功能
SM2算法提供了三大核心功能:非對稱加密、數字簽名和密鑰交換,其設計目標是通過橢圓曲線的數學特性,實現高效且安全的數據保護。
1. 密鑰生成
SM2的密鑰對由私鑰和公鑰組成:
- 私鑰:一個256位的隨機整數?dd,滿足?1≤d≤n?11≤d≤n?1,其中?nn?是橢圓曲線基點?GG?的階。
- 公鑰:通過橢圓曲線點乘運算生成,即?P=[d]GP=[d]G,結果是一個橢圓曲線上的點?(x,y)(x,y),通常以非壓縮格式?04∣∣x∣∣y04∣∣x∣∣y?存儲(65字節)。
2. 加密與解密
SM2的加密過程采用混合加密體系,結合非對稱加密和對稱加密的優點:
- 加密:生成密文?C=C1∣∣C2∣∣C3C=C1∣∣C2∣∣C3,其中:
- C1C1:隨機數?kk?與基點?GG?的點乘結果?[k]G[k]G,用于生成臨時共享密鑰。
- C2C2:明文?MM?通過對稱加密(如SM3派生的密鑰流)生成的密文。
- C3C3:通過SM3哈希算法計算的完整性校驗值?Hash(x2∣∣M∣∣y2)Hash(x2∣∣M∣∣y2),防止數據篡改。
- 解密:接收方通過私鑰?dd?計算共享密鑰,解密?C2C2?并驗證?C3C3。
3. 數字簽名與驗證
SM2的簽名機制基于SM3哈希算法和橢圓曲線數學特性:
- 簽名生成:私鑰?dd?和隨機數?kk?生成簽名?(r,s)(r,s),其中?rr?是?[k]G[k]G?的?xx?坐標模?nn,ss?是?(1+d)?1?(k?r?d)mod??n(1+d)?1?(k?r?d)modn。
- 簽名驗證:通過公鑰?PP?和簽名參數?(r,s)(r,s)?驗證等式?u1?G+u2?Pu1??G+u2??P?的?xx?坐標是否等于?rr。
4. 密鑰交換
SM2通過橢圓曲線Diffie-Hellman(ECDH)變體實現密鑰交換:
- 客戶端生成臨時密鑰對?(dC,QC)(dC?,QC?),服務端使用證書中的公鑰?QSQS??與?dCdC??計算共享密鑰,雙方通過KDF生成會話密鑰。
二、數學原理
SM2算法的安全性建立在**橢圓曲線離散對數問題(ECDLP)**的困難性上。其數學基礎包括以下核心參數:
1. 橢圓曲線方程
SM2采用素數域上的橢圓曲線,方程為:
y2=x3+ax+bmod??py2=x3+ax+bmodp
其中:
- pp:256位大素數,定義有限域?FpFp?。
- aa、bb:曲線系數,滿足?4a3+27b2≠0mod??p4a3+27b2=0modp。
- GG:基點,是曲線上的一個固定點,作為生成元。
- nn:基點?GG?的階,為大素數。
2. 密鑰生成與點乘運算
- 私鑰生成:隨機選擇?d∈[1,n?1]d∈[1,n?1]。
- 公鑰生成:計算?P=[d]GP=[d]G,即基點?GG?與私鑰?dd?的點乘結果。
3. 安全性分析
SM2的256位密鑰長度提供約128比特的安全強度,相當于3072位RSA的安全水平。其優勢在于:
- 密鑰長度短:運算效率高,適合資源受限設備(如智能卡、嵌入式系統)。
- 抗攻擊性強:基于ECDLP問題,目前無多項式時間算法可破解。
三、加解密及數字簽名開源代碼實現示例
?1. SM2加解密代碼示例:
/** This file is part of the openHiTLS project.** openHiTLS is licensed under the Mulan PSL v2.* You can use this software according to the terms and conditions of the Mulan PSL v2.* You may obtain a copy of Mulan PSL v2 at:** http://license.coscl.org.cn/MulanPSL2** THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.* See the Mulan PSL v2 for more details.*/#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "crypt_eal_pkey.h" // Header file of the interfaces for asymmetric encryption and decryption.
#include "bsl_sal.h"
#include "bsl_err.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_init.h"
#include "crypt_types.h"void *StdMalloc(uint32_t len) {return malloc((uint32_t)len);
}
void PrintLastError(void) {const char *file = NULL;uint32_t line = 0;BSL_ERR_GetLastErrorFileLine(&file, &line);printf("failed at file %s at line %d\n", file, line);
}int main(void) {int32_t ret;BSL_ERR_Init(); // Initialize the error code module./*** Before calling the algorithm APIs,* call the BSL_SAL_CallBack_Ctrl function to register the malloc and free functions.* Execute this step only once. If the memory allocation ability of Linux is available,* the two functions can be registered using Linux by default.*/BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, StdMalloc);BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free);ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_CPU | CRYPT_EAL_INIT_PROVIDER);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}CRYPT_EAL_PkeyCtx *pkey = NULL;pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2);if (pkey == NULL) {PrintLastError();goto EXIT;}// Initialize the random number.ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL);if (ret != CRYPT_SUCCESS) {printf("RandInit: error code is %x\n", ret);PrintLastError();goto EXIT;}// Generate a key pair.ret = CRYPT_EAL_PkeyGen(pkey);if (ret != CRYPT_SUCCESS) {printf("CRYPT_EAL_PkeyGen: error code is %x\n", ret);PrintLastError();goto EXIT;}// Data to be encrypted.char *data = "test enc data";uint32_t dataLen = 12;uint8_t ecrypt[125] = {0};uint32_t ecryptLen = 125;uint8_t dcrypt[125] = {0};uint32_t dcryptLen = 125;// Encrypt data.ret = CRYPT_EAL_PkeyEncrypt(pkey, data, dataLen, ecrypt, &ecryptLen);if (ret != CRYPT_SUCCESS) {printf("CRYPT_EAL_PkeyEncrypt: error code is %x\n", ret);PrintLastError();goto EXIT;}// Decrypt data.ret = CRYPT_EAL_PkeyDecrypt(pkey, ecrypt, ecryptLen, dcrypt, &dcryptLen);if (ret != CRYPT_SUCCESS) {printf("CRYPT_EAL_PkeyDecrypt: error code is %x\n", ret);PrintLastError();goto EXIT;}if (memcmp(dcrypt, data, dataLen) == 0) {printf("encrypt and decrypt success\n");} else {ret = -1;}
EXIT:// Release the context memory.CRYPT_EAL_PkeyFreeCtx(pkey);CRYPT_EAL_RandDeinit();BSL_ERR_DeInit();return ret;
}
2. SM2簽名代碼示例:
/** This file is part of the openHiTLS project.** openHiTLS is licensed under the Mulan PSL v2.* You can use this software according to the terms and conditions of the Mulan PSL v2.* You may obtain a copy of Mulan PSL v2 at:** http://license.coscl.org.cn/MulanPSL2** THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.* See the Mulan PSL v2 for more details.*/#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "crypt_eal_pkey.h" // Header file for signature verification.
#include "bsl_sal.h"
#include "bsl_err.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_init.h"void *StdMalloc(uint32_t len) {return malloc((size_t)len);
}void PrintLastError(void) {const char *file = NULL;uint32_t line = 0;BSL_ERR_GetLastErrorFileLine(&file, &line);// Obtain the name and number of lines of the error file.printf("failed at file %s at line %d\n", file, line);
}int main(void)
{int ret;uint8_t userId[32] = {0};uint8_t key[32] = {0};uint8_t msg[32] = {0};uint8_t signBuf[100] = {0};uint32_t signLen = sizeof(signBuf);CRYPT_EAL_PkeyPrv prv = {0};CRYPT_EAL_PkeyPub pub = {0};CRYPT_EAL_PkeyCtx *ctx = NULL;BSL_ERR_Init(); // Initialize the error code module./*** Before calling the algorithm APIs,* call the BSL_SAL_CallBack_Ctrl function to register the malloc and free functions.* Execute this step only once. If the memory allocation ability of Linux is available,* the two functions can be registered using Linux by default.*/BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, StdMalloc);BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free);ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_CPU | CRYPT_EAL_INIT_PROVIDER);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);goto EXIT;}ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2);if (ctx == NULL) {goto EXIT;}// Set a user ID.ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId));if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}// Initialize the random number.ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}// Generate a key pair.ret = CRYPT_EAL_PkeyGen(ctx);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}// Sign.ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}// Verify the signature.ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen);if (ret != CRYPT_SUCCESS) {printf("error code is %x\n", ret);PrintLastError();goto EXIT;}printf("pass \n");EXIT:// Release the context memory.CRYPT_EAL_PkeyFreeCtx(ctx);CRYPT_EAL_RandDeinit();BSL_ERR_DeInit();return ret;
}
【免費下載openHiTLS開源代碼】
?openHiTLS旨在打造算法先進、性能卓越、高效敏捷、安全可靠的密碼套件,通過輕量級、可剪裁的軟件技術架構滿足各行業不同場景的多樣化要求,讓密碼技術應用更簡單,同時探索后量子等先進算法創新實踐,構建密碼前沿技術底座!
?項目地址:https://gitcode.com/openHiTLS/openhitls