国密SM4算法(简介与C源码)

国密即国家密码局认定的国产密码算法,即商用密码。

国密算法是国家密码局制定标准的一系列算法。其中包括了对称加密算法,椭圆曲线非对称加密算法,杂凑算法。具体包括SM1,SM2,SM3,SM4等,其中:SM4为对称加解密算法与AES相似,模式也相同,开发时可以对比研究。

SM4算法主要包含5种基本模式:ECB、CBC、CFB、OFB,CTR(后4种都是ECB算法模块衍生而来);与MAC结合还诞生了GCM,CCM等高级模式;

CCM是CTR加密模式和CMAC认证算法的混合使用,常用在需要同时加密和认证的领域,比如WiFi安全中的WPE协议,它就使用了AES-CCM模式

所有SM4衍生的算法模式都基于SM4的基础轮函数。

 

 

 

经过验证的SM4国密算法代码:

ECB,CBC模式: 

https://download.csdn.net/download/htx1020/13072638

CCM模式: 

https://download.csdn.net/download/htx1020/13087068

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
FISCO-BCOS智能合约支持使用C++编写智能合约,因此可以在智能合约中使用SM4算法的C++源码实现。以下是一个简单的示例: ```cpp #include <openssl/evp.h> #include <string.h> extern "C" { #include "sm4.h" } // 使用OpenSSL库实现SM4算法加密 std::string sm4_encrypt_openssl(const std::string& key, const std::string& iv, const std::string& data) { EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_init(ctx); // 设置加密算法和模式 EVP_EncryptInit_ex(ctx, EVP_sms4_cbc(), NULL, (const unsigned char*)key.c_str(), (const unsigned char*)iv.c_str()); // 执行加密操作并获取加密后的数据 int len = data.length(); int ciphertext_len = len + EVP_MAX_BLOCK_LENGTH; unsigned char* ciphertext = new unsigned char[ciphertext_len]; int outlen; EVP_EncryptUpdate(ctx, ciphertext, &outlen, (const unsigned char*)data.c_str(), len); ciphertext_len = outlen; EVP_EncryptFinal_ex(ctx, ciphertext + outlen, &outlen); ciphertext_len += outlen; // 转换为十六进制字符串返回 std::string result; for (int i=0; i<ciphertext_len; i++) { char buf[3]; snprintf(buf, sizeof(buf), "%02x", ciphertext[i]); result.append(buf); } delete[] ciphertext; return result; } // 使用国密SM4算法加密 std::string sm4_encrypt_sm(const std::string& key, const std::string& iv, const std::string& data) { unsigned char* plaintext = new unsigned char[data.length() + 1]; strcpy((char*)plaintext, data.c_str()); // 加密 unsigned char* ciphertext = new unsigned char[data.length() + 1]; memset(ciphertext, 0, data.length() + 1); unsigned char* tmp_key = new unsigned char[key.length() + 1]; strcpy((char*)tmp_key, key.c_str()); unsigned char* tmp_iv = new unsigned char[iv.length() + 1]; strcpy((char*)tmp_iv, iv.c_str()); sm4_context ctx; sm4_setkey_enc(&ctx, tmp_key); sm4_crypt_cbc(&ctx, SM4_ENCRYPT, data.length(), tmp_iv, plaintext, ciphertext); // 转换为十六进制字符串返回 std::string result; for (int i=0; i<data.length(); i++) { char buf[3]; snprintf(buf, sizeof(buf), "%02x", ciphertext[i]); result.append(buf); } delete[] plaintext; delete[] ciphertext; delete[] tmp_key; delete[] tmp_iv; return result; } ``` 其中,`sm4_encrypt_openssl`使用OpenSSL库实现SM4算法加密,`sm4_encrypt_sm`使用国密SM4算法加密。在使用国密SM4算法加密时,需要包含国密SM4算法的头文件,并调用其API实现加密操作。 请注意,由于国密SM4算法的限制,其密钥长度必须为16个字节,IV长度必须为16个字节。在实际使用时,需要根据实际情况生成合适的密钥和IV。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值