SM4 CBC模式加密的C语言实现


因为工作的关系,最近在研究国密算法,其中无线局域网使用的SM4算法颇为神秘,网上资源也是少的可怜,不过在笔者的努力下,还是成功搞定了。

有感于SM4相关正确资料的稀少,同时也算是自我的学习积累,故写下此文,希望可以帮助后来人少走些弯路。

此处给出的是基于sm4源码及QT4做的SM4_CBC模式加密算法的验证工具,及其源码。

写在前面的话:SM4算法是国密算法中的一种,分ECB和CBC两种模式,ECB简单加密的使用方法,网上可以搜索的到,单次加密明文长度为0到16,而CBC模式网上资源极少,单次加密明文长度为0到32。

在此,分别贴出完整的文件源码供各位参考

#ifndef HEADER_SM4_H
#define HEADER_SM4_H

#ifdef  __cplusplus
extern "C" {
#endif

typedef unsigned char muint8;
typedef unsigned long muint32;

#define LITTLE_ENDIAN     //定义小端字节序
//#define BIG_ENDIAN     //定义大端字节序
#define SM4_ENCRYPT  1     //定义加密标志
#define SM4_DECRYPT  0     //定义解密标志

#define SM4_BLOCK_LEN	16
#define SM4_KEY_LEN	16
#define SM4_IV_LEN	SM4_BLOCK_LEN

// SM4的密钥扩展算法
// 参数说明:Key为加密密钥,rk为子密钥,CryptFlag为加解密标志
int SM4KeyExt(const muint8 *Key, muint32 *rk, muint32 CryptFlag);

// SM4的加解密函数
// 参数说明:Input为输入信息分组,Output为输出分组,rk为轮密钥
int SM4Crypt(const muint8 *Input, muint8 *Output, const muint32 *rk);

//For EVP
void sm4_set_key(muint32 *rk, const unsigned char *data, int enc);
void sm4_ecb_encrypt(char *in,  char *out, const muint32 *rk,
					 int enc);
void sm4_cbc_encrypt(const unsigned char *in, unsigned char *out, long length,
					 const muint32 *rk, unsigned char *iv, int enc);
void sm4_cfb64_encrypt(const unsigned char *in, unsigned char *out,
					   long length, const muint32 *rk, unsigned char *ivec,
					   int *num, int enc);
void sm4_ofb64_encrypt(const unsigned char *in, unsigned char *out,
					   long length, const muint32 *rk, unsigned char *ivec,
					   int *num);

#ifdef  __cplusplus
}
#endif

#endif
#include "sm4.h"
#include 
  
  
   
   

//muint32 rk[32];//作为加解密上下文

const muint8 Sbox[256] = {
0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05,
0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99,
0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62,
0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6,
0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8,
0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35,
0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87,
0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e,
0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,
  • 21
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 247
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值