26

国密算法SM3与SM4简介与应用

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzUxMTk4MzY3MA%3D%3D&%3Bmid=2247484508&%3Bidx=1&%3Bsn=570a9e72923581e3d50ea16f13dd4896
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

点击上方蓝字可直接关注!方便下次阅读。如果对你有帮助,麻烦点个在看或点个赞,感谢~

最近0基础在学习国密算法的相关应用,故此和大家分享下自己的一些经历。

程序平台: Ubuntu16.04  x64

VZrUFj6.jpg!web

一、国密SM3与SM4

国产密码算法(国密算法)是指国家密码局认定的国产商用密码算法,目前主要使用公开的 SM2、SM3、SM4三类算法,分别是非对称算法、哈希算法和对称算法。 不懂也没关系,以后别人说 SM2、SM3、SM4 知道它们是干啥的就行。这次主要和大家从简单的 SM3、SM4 说起。

SM3算法: SM3 杂凑算法 是我国自主设计的密码杂凑算法,适用于商用密码应用中的数字签名和验证消息认证码的生成与验证以及随机数的生成,可满足多种密码应用的安全需求。为了保证杂凑算法的安全性,其产生的杂凑值的长度不应太短,例如 MD5输出128比特杂凑值,输出长度太短,影响其安全性SHA-1算法的输出长度为160比特,SM3算法的输出长度为256比特,因此SM3算法的安全性要高于MD5算法和SHA-1算法。

SM4算法: SM4 分组密码算法 是我国自主设计的分组对称密码算法,用于实现数据的加密 /解密运算,以保证数据和信息的机密性。要保证一个对称密码算法的安全性的基本条件是其具备足够的密钥长度,SM4算法与AES算法具有相同的密钥长度分组长度128比特,因此在安全性上高于3DES算法。

里面的一些术语不知道也没关系,以后会再梳理的 ......

二、信息摘要(SM3)一些特性

消息摘要或者哈希函数以任意消息 (任意内容或者任何长度)作为输入,然后产生一个固定长度大小的哈希值作为结果输出。具体来说,该函数具有以下特性

·  对于任意给定的消息,生成哈希值很简单

·  从任意给定的哈希值去计算出一条消息是不可行的 (即函数是单向的)

·  修改消息而不修改哈希值是不可行的

·  找到两条具有相同哈希值的消息是不可行的

三、开源程序使用举例

测试文件结构如图:

BnQJvyZ.png!web

测试源码:

#include <SM3.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>


# define EVP_MAX_MD_SIZE 32

#define ALLOC_OBJ(type, size) (type *)calloc(1, (sizeof(type)*size))


int main()

{

unsigned char msgbuf[] = "abc";

unsigned char msgbuf1[] = "abc";

unsigned char dgst[EVP_MAX_MD_SIZE];

unsigned int dgstlen = (unsigned int)sizeof(dgst);


SM3_state *ctx = ALLOC_OBJ(SM3_state, 1);

SM3_Init(ctx);

SM3_Update(ctx, msgbuf, sizeof(msgbuf)-1);

SM3_Final(dgst, dgstlen, ctx, sizeof(msgbuf)-1);


printf("Digest1 is: ");

for (int i = 0; i < dgstlen; i++)

printf("%02x", dgst[i]);

printf("\n");


// second use

SM3_Hash(msgbuf1 , sizeof(msgbuf1)-1, dgst, dgstlen);

printf("Digest2 is: ");

for (int i = 0; i < dgstlen; i++)

printf("%02x", dgst[i]);

printf("\n");



free(ctx);

return 0;

}

测试效果:

JbeARbm.png!web

SM4简单举例:

int main()

{

unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

unsigned char iv[] = {1,2,3,4,5,6,7,8};

unsigned char plain_text[] = "hello world!";

unsigned char out_plain_text[sizeof(plain_text)];

unsigned char cipher_text[16];


SM4_EncCBC(key, iv, plain_text, cipher_text, sizeof(plain_text)-1);


SM4_DecCBC(key, iv, cipher_text, out_plain_text, sizeof(plain_text)-1);

printf("%s\n",cipher_text);



printf("%s\n",out_plain_text);


return 0;

}

四、 小结与资源链接

①国密C语言实现的git链接:

https://github.com/JulongChain/julongchain-csp-sdt

②相关术语链接:

http://gmssl.org/docs/evp-api.html

③纯初学入门,为了快速应用。最开始用的GmSSL,这个文档相对全一些,对初学者会友好一些,但是还是需要一点儿密码学的基础,我是两个结合一起看的。

需要完整程序的可在公众号后台留言说明。

每日 ××× :有机会一定要体验不同的生活方式与工作方式!

MZzeIjR.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK