1.在SM3算法源文件中主要有以下几个函数:

void sm3_starts( sm3_context *ctx );
void sm3_update( sm3_context *ctx, unsigned char *input, int ilen );
void sm3_finish( sm3_context *ctx, unsigned char output[32] );
void sm3( unsigned char *input, int ilen, unsigned char output[32]);
int sm3_file( char *path, unsigned char output[32] );
void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen);
void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen );
void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] );
void sm3_hmac( unsigned char *key, int keylen,unsigned char *input, int ilen,unsigned char output[32] );

2. 还有一个重要的结构体:

/*** \brief          SM3 context structure*/
typedef struct
{unsigned long total[2];     /*!< number of bytes processed  */unsigned long state[8];     /*!< intermediate digest state  */unsigned char buffer[64];   /*!< data block being processed */unsigned char ipad[64];     /*!< HMAC: inner padding        */unsigned char opad[64];     /*!< HMAC: outer padding        */}
sm3_context;

该结构体规定了要处理的字节数、中间摘要状态、数据分组块等等。

3. SM3函数介绍

/*** \brief          Output = SM3( input buffer )** \param input    buffer holding the  data* \param ilen     length of the input data* \param output   SM3 checksum result*/
void sm3( unsigned char *input, int ilen,unsigned char output[32]);

字符指针input存储输入数组,ilen参数表示数据长度,字符数组output存储输出结果,在执行sm3函数时内部会调用:sm3_starts()、sm3_update()、sm3_finish()函数。

4. sm3.h源代码


/*** \file sm3.h* thanks to Xyssl* SM3 standards:http://www.oscca.gov.cn/News/201012/News_1199.htm* author:goldboar* email:goldboar@163.com* 2011-10-26*/
#ifndef XYSSL_SM3_H
#define XYSSL_SM3_H/*** \brief          SM3 context structure*/
typedef struct
{unsigned long total[2];     /*!< number of bytes processed  */unsigned long state[8];     /*!< intermediate digest state  */unsigned char buffer[64];   /*!< data block being processed */unsigned char ipad[64];     /*!< HMAC: inner padding        */unsigned char opad[64];     /*!< HMAC: outer padding        */}
sm3_context;#ifdef __cplusplus
extern "C" {
#endif/*** \brief          SM3 context setup** \param ctx      context to be initialized*/
void sm3_starts( sm3_context *ctx );/*** \brief          SM3 process buffer** \param ctx      SM3 context* \param input    buffer holding the  data* \param ilen     length of the input data*/
void sm3_update( sm3_context *ctx, unsigned char *input, int ilen );/*** \brief          SM3 final digest** \param ctx      SM3 context*/
void sm3_finish( sm3_context *ctx, unsigned char output[32] );/*** \brief          Output = SM3( input buffer )** \param input    buffer holding the  data* \param ilen     length of the input data* \param output   SM3 checksum result*/
void sm3( unsigned char *input, int ilen,unsigned char output[32]);/*** \brief          Output = SM3( file contents )** \param path     input file name* \param output   SM3 checksum result** \return         0 if successful, 1 if fopen failed,*                 or 2 if fread failed*/
int sm3_file( char *path, unsigned char output[32] );/*** \brief          SM3 HMAC context setup** \param ctx      HMAC context to be initialized* \param key      HMAC secret key* \param keylen   length of the HMAC key*/
void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen);/*** \brief          SM3 HMAC process buffer** \param ctx      HMAC context* \param input    buffer holding the  data* \param ilen     length of the input data*/
void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen );/*** \brief          SM3 HMAC final digest** \param ctx      HMAC context* \param output   SM3 HMAC checksum result*/
void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] );/*** \brief          Output = HMAC-SM3( hmac key, input buffer )** \param key      HMAC secret key* \param keylen   length of the HMAC key* \param input    buffer holding the  data* \param ilen     length of the input data* \param output   HMAC-SM3 result*/
void sm3_hmac( unsigned char *key, int keylen,unsigned char *input, int ilen,unsigned char output[32] );#ifdef __cplusplus
}
#endif#endif /* sm3.h */

4. sm3.c源代码

/** SM3 Hash alogrith* thanks to Xyssl* author:goldboar* email:goldboar@163.com* 2011-10-26*/ //Testing data from SM3 Standards
//http://www.oscca.gov.cn/News/201012/News_1199.htm
// Sample 1
// Input:"abc"
// Output:66c7f0f4 62eeedd9 d1f2d46b dc10e4e2 4167c487 5cf2f7a2 297da02b 8f4ba8e0// Sample 2
// Input:"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"
// Outpuf:debe9ff9 2275b8a1 38604889 c18e5a4d 6fdb70e5 387e5765 293dcba3 9c0c5732#include "sm3.h"
#include <string.h>
#include <stdio.h>/** 32-bit integer manipulation macros (big endian)*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i)                             \
{                                                       \(n) = ( (unsigned long) (b)[(i)    ] << 24 )        \| ( (unsigned long) (b)[(i) + 1] << 16 )        \| ( (unsigned long) (b)[(i) + 2] <<  8 )        \| ( (unsigned long) (b)[(i) + 3]       );       \
}
#endif#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i)                             \
{                                                       \(b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \(b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \(b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \(b)[(i) + 3] = (unsigned char) ( (n)       );       \
}
#endif/** SM3 context setup*/
void sm3_starts( sm3_context *ctx )
{ctx->total[0] = 0;ctx->total[1] = 0;ctx->state[0] = 0x7380166F;ctx->state[1] = 0x4914B2B9;ctx->state[2] = 0x172442D7;ctx->state[3] = 0xDA8A0600;ctx->state[4] = 0xA96F30BC;ctx->state[5] = 0x163138AA;ctx->state[6] = 0xE38DEE4D;ctx->state[7] = 0xB0FB0E4E;}static void sm3_process( sm3_context *ctx, unsigned char data[64] )
{unsigned long SS1, SS2, TT1, TT2, W[68],W1[64];unsigned long A, B, C, D, E, F, G, H;unsigned long T[64];unsigned long Temp1,Temp2,Temp3,Temp4,Temp5;int j;
#ifdef _DEBUGint i;
#endif//    for(j=0; j < 68; j++)
//      W[j] = 0;
//  for(j=0; j < 64; j++)
//      W1[j] = 0;for(j = 0; j < 16; j++)T[j] = 0x79CC4519;for(j =16; j < 64; j++)T[j] = 0x7A879D8A;GET_ULONG_BE( W[ 0], data,  0 );GET_ULONG_BE( W[ 1], data,  4 );GET_ULONG_BE( W[ 2], data,  8 );GET_ULONG_BE( W[ 3], data, 12 );GET_ULONG_BE( W[ 4], data, 16 );GET_ULONG_BE( W[ 5], data, 20 );GET_ULONG_BE( W[ 6], data, 24 );GET_ULONG_BE( W[ 7], data, 28 );GET_ULONG_BE( W[ 8], data, 32 );GET_ULONG_BE( W[ 9], data, 36 );GET_ULONG_BE( W[10], data, 40 );GET_ULONG_BE( W[11], data, 44 );GET_ULONG_BE( W[12], data, 48 );GET_ULONG_BE( W[13], data, 52 );GET_ULONG_BE( W[14], data, 56 );GET_ULONG_BE( W[15], data, 60 );#ifdef _DEBUGprintf("Message with padding:\n");for(i=0; i< 8; i++)printf("%08x ",W[i]);printf("\n");for(i=8; i< 16; i++)printf("%08x ",W[i]);printf("\n");
#endif#define FF0(x,y,z) ( (x) ^ (y) ^ (z))
#define FF1(x,y,z) (((x) & (y)) | ( (x) & (z)) | ( (y) & (z)))#define GG0(x,y,z) ( (x) ^ (y) ^ (z))
#define GG1(x,y,z) (((x) & (y)) | ( (~(x)) & (z)) )#define  SHL(x,n) (((x) & 0xFFFFFFFF) << n)
#define ROTL(x,n) (SHL((x),n) | ((x) >> (32 - n)))#define P0(x) ((x) ^  ROTL((x),9) ^ ROTL((x),17))
#define P1(x) ((x) ^  ROTL((x),15) ^ ROTL((x),23))for(j = 16; j < 68; j++ ){//W[j] = P1( W[j-16] ^ W[j-9] ^ ROTL(W[j-3],15)) ^ ROTL(W[j - 13],7 ) ^ W[j-6];//Why thd release's result is different with the debug's ?//Below is okay. Interesting, Perhaps VC6 has a bug of Optimizaiton.Temp1 = W[j-16] ^ W[j-9];Temp2 = ROTL(W[j-3],15);Temp3 = Temp1 ^ Temp2;Temp4 = P1(Temp3);Temp5 =  ROTL(W[j - 13],7 ) ^ W[j-6];W[j] = Temp4 ^ Temp5;}#ifdef _DEBUGprintf("Expanding message W0-67:\n");for(i=0; i<68; i++){printf("%08x ",W[i]);if(((i+1) % 8) == 0) printf("\n");}printf("\n");
#endiffor(j =  0; j < 64; j++){W1[j] = W[j] ^ W[j+4];}#ifdef _DEBUGprintf("Expanding message W'0-63:\n");for(i=0; i<64; i++){printf("%08x ",W1[i]);if(((i+1) % 8) == 0) printf("\n");}printf("\n");
#endifA = ctx->state[0];B = ctx->state[1];C = ctx->state[2];D = ctx->state[3];E = ctx->state[4];F = ctx->state[5];G = ctx->state[6];H = ctx->state[7];
#ifdef _DEBUGprintf("j     A       B        C         D         E        F        G       H\n");printf("   %08x %08x %08x %08x %08x %08x %08x %08x\n",A,B,C,D,E,F,G,H);
#endiffor(j =0; j < 16; j++){SS1 = ROTL((ROTL(A,12) + E + ROTL(T[j],j)), 7);SS2 = SS1 ^ ROTL(A,12);TT1 = FF0(A,B,C) + D + SS2 + W1[j];TT2 = GG0(E,F,G) + H + SS1 + W[j];D = C;C = ROTL(B,9);B = A;A = TT1;H = G;G = ROTL(F,19);F = E;E = P0(TT2);
#ifdef _DEBUGprintf("%02d %08x %08x %08x %08x %08x %08x %08x %08x\n",j,A,B,C,D,E,F,G,H);
#endif}for(j =16; j < 64; j++){SS1 = ROTL((ROTL(A,12) + E + ROTL(T[j],j)), 7);SS2 = SS1 ^ ROTL(A,12);TT1 = FF1(A,B,C) + D + SS2 + W1[j];TT2 = GG1(E,F,G) + H + SS1 + W[j];D = C;C = ROTL(B,9);B = A;A = TT1;H = G;G = ROTL(F,19);F = E;E = P0(TT2);
#ifdef _DEBUGprintf("%02d %08x %08x %08x %08x %08x %08x %08x %08x\n",j,A,B,C,D,E,F,G,H);
#endif}ctx->state[0] ^= A;ctx->state[1] ^= B;ctx->state[2] ^= C;ctx->state[3] ^= D;ctx->state[4] ^= E;ctx->state[5] ^= F;ctx->state[6] ^= G;ctx->state[7] ^= H;
#ifdef _DEBUGprintf("   %08x %08x %08x %08x %08x %08x %08x %08x\n",ctx->state[0],ctx->state[1],ctx->state[2],ctx->state[3],ctx->state[4],ctx->state[5],ctx->state[6],ctx->state[7]);
#endif
}/** SM3 process buffer*/
void sm3_update( sm3_context *ctx, unsigned char *input, int ilen )
{int fill;unsigned long left;if( ilen <= 0 )return;left = ctx->total[0] & 0x3F;fill = 64 - left;ctx->total[0] += ilen;ctx->total[0] &= 0xFFFFFFFF;if( ctx->total[0] < (unsigned long) ilen )ctx->total[1]++;if( left && ilen >= fill ){memcpy( (void *) (ctx->buffer + left),(void *) input, fill );sm3_process( ctx, ctx->buffer );input += fill;ilen  -= fill;left = 0;}while( ilen >= 64 ){sm3_process( ctx, input );input += 64;ilen  -= 64;}if( ilen > 0 ){memcpy( (void *) (ctx->buffer + left),(void *) input, ilen );}
}static const unsigned char sm3_padding[64] =
{0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};/** SM3 final digest*/
void sm3_finish( sm3_context *ctx, unsigned char output[32] )
{unsigned long last, padn;unsigned long high, low;unsigned char msglen[8];high = ( ctx->total[0] >> 29 )| ( ctx->total[1] <<  3 );low  = ( ctx->total[0] <<  3 );PUT_ULONG_BE( high, msglen, 0 );PUT_ULONG_BE( low,  msglen, 4 );last = ctx->total[0] & 0x3F;padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );sm3_update( ctx, (unsigned char *) sm3_padding, padn );sm3_update( ctx, msglen, 8 );PUT_ULONG_BE( ctx->state[0], output,  0 );PUT_ULONG_BE( ctx->state[1], output,  4 );PUT_ULONG_BE( ctx->state[2], output,  8 );PUT_ULONG_BE( ctx->state[3], output, 12 );PUT_ULONG_BE( ctx->state[4], output, 16 );PUT_ULONG_BE( ctx->state[5], output, 20 );PUT_ULONG_BE( ctx->state[6], output, 24 );PUT_ULONG_BE( ctx->state[7], output, 28 );
}/** output = SM3( input buffer )*/
void sm3( unsigned char *input, int ilen,unsigned char output[32] )
{sm3_context ctx;sm3_starts( &ctx );sm3_update( &ctx, input, ilen );sm3_finish( &ctx, output );memset( &ctx, 0, sizeof( sm3_context ) );
}/** output = SM3( file contents )*/
int sm3_file( char *path, unsigned char output[32] )
{FILE *f;size_t n;sm3_context ctx;unsigned char buf[1024];if( ( f = fopen( path, "rb" ) ) == NULL )return( 1 );sm3_starts( &ctx );while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )sm3_update( &ctx, buf, (int) n );sm3_finish( &ctx, output );memset( &ctx, 0, sizeof( sm3_context ) );if( ferror( f ) != 0 ){fclose( f );return( 2 );}fclose( f );return( 0 );
}/** SM3 HMAC context setup*/
void sm3_hmac_starts( sm3_context *ctx, unsigned char *key, int keylen )
{int i;unsigned char sum[32];if( keylen > 64 ){sm3( key, keylen, sum );keylen = 32;//keylen = ( is224 ) ? 28 : 32;key = sum;}memset( ctx->ipad, 0x36, 64 );memset( ctx->opad, 0x5C, 64 );for( i = 0; i < keylen; i++ ){ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] );ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] );}sm3_starts( ctx);sm3_update( ctx, ctx->ipad, 64 );memset( sum, 0, sizeof( sum ) );
}/** SM3 HMAC process buffer*/
void sm3_hmac_update( sm3_context *ctx, unsigned char *input, int ilen )
{sm3_update( ctx, input, ilen );
}/** SM3 HMAC final digest*/
void sm3_hmac_finish( sm3_context *ctx, unsigned char output[32] )
{int hlen;unsigned char tmpbuf[32];//is224 = ctx->is224;hlen =  32;sm3_finish( ctx, tmpbuf );sm3_starts( ctx );sm3_update( ctx, ctx->opad, 64 );sm3_update( ctx, tmpbuf, hlen );sm3_finish( ctx, output );memset( tmpbuf, 0, sizeof( tmpbuf ) );
}/** output = HMAC-SM#( hmac key, input buffer )*/
void sm3_hmac( unsigned char *key, int keylen,unsigned char *input, int ilen,unsigned char output[32] )
{sm3_context ctx;sm3_hmac_starts( &ctx, key, keylen);sm3_hmac_update( &ctx, input, ilen );sm3_hmac_finish( &ctx, output );memset( &ctx, 0, sizeof( sm3_context ) );
}

5 sm3test.c 源代码

#include <string.h>
#include <stdio.h>
#include "sm3.h"int main( int argc, char *argv[] )
{unsigned char *input = "abc";int ilen = 3;unsigned char output[32];int i;sm3_context ctx;printf("Message: ");printf("%s\n",input);sm3(input, ilen, output);printf("Hash:   ");for(i=0; i<32; i++){printf("%02x",output[i]);if (((i+1) % 4 ) == 0) printf(" ");}printf("\n");printf("Message: ");for(i=0; i < 16; i++)printf("abcd");printf("\n");sm3_starts( &ctx );for(i=0; i < 16; i++)sm3_update( &ctx, "abcd", 4 );sm3_finish( &ctx, output );memset( &ctx, 0, sizeof( sm3_context ) );printf("Hash:   ");for(i=0; i<32; i++){printf("%02x",output[i]);if (((i+1) % 4 ) == 0) printf(" ");}printf("\n");//getch();   //VS2008
}

SM3密码杂凑算法源码解析相关推荐

  1. 国密SM3密码杂凑算法原理及实现(附源码)

    相关文章: 国密SM3哈希算法原理及实现(附源码) SHA1哈希算法原理及实现(附源码) MD5哈希算法原理及实现(附源码) MD4哈希算法原理及实现(附源码) MD2哈希算法原理及实现(附源码) M ...

  2. 原味的SM3密码杂凑算法

    根据国家密码管理局官网发布的规范文档里的算法描述,对SM3密码杂凑算法进行了原汁原味的实现.代码里的函数.变量名称都尽量使用算法描述中的名称,尽量遵循算法描述的原始步骤,不使用算法技巧进行处理. 算法 ...

  3. android杂凑算法,SM3密码杂凑算法分析

    SM3密码杂凑算法分析 杂凑函数在密码学中具有重要的地位,被广泛应用在数字签名,消息认证,数据完整性检测等领域.杂凑函数通常被认为需要满足三个基本特性:碰撞稳固性,原根稳固性和第二原根稳固性.2005 ...

  4. Android图案密码,手势锁源码解析

    Android图案密码解锁源码解析 Android Lock Pattern 源码解析  1. 介绍   1.1 关于 Android 的图案密码解锁,通过手势连接 3 * 3 的点矩阵绘制图案表示解 ...

  5. 以太坊Geth 共识算法源码解析

    共识算法 目前以太坊中有两个公式算法的实现,分别为clique和ethash.其中clique是PoA共识的实现,ethash是PoW共识的实现,其相应的代码位于go-ethereum/consens ...

  6. 【详解】Ribbon 负载均衡服务调用原理及默认轮询负载均衡算法源码解析、手写

    Ribbon 负载均衡服务调用 一.什么是 Ribbon 二.LB负载均衡(Load Balancer)是什么 1.Ribbon 本地负载均衡客户端 VS Nginx 服务端负载均衡的区别 2.LB负 ...

  7. ZooKeeper的FastLeaderElection算法源码解析

    Zookeeper服务器在启动的时候会通过一定的选举算法从多个server中选出leader server,剩下的server则作为follower.目前实现的选举算法有FastLeaderElect ...

  8. Robin六种常用负载均衡算法源码解析

    文章目录 1 经典轮询算法 2 随机算法 3 以响应时间为权重的轮询策略(重中之重) 4 重试策略 5 断言策略 6 最佳可用性策略 1 经典轮询算法 //Robin的负载均衡原理为 请求服务=请求次 ...

  9. 【Hll】Hll HyperLogLog: Cardinality Estimation(基数估计算法源码解析)

    1.概述 好文章,转载防丢失 主要是这里有源码,我遇到问题了,问题是flink在累加器中使用的时候,每次累加最终结果是1,2 每次到了2 就会重新回到1,很郁闷于是看看源码 2.背景 我们经常会统计某 ...

最新文章

  1. c++的ORM解决方案 -- ODB
  2. 【自动驾驶】视觉里程计
  3. 新建android项目导包,Cordova开发App入门(一)创建android项目
  4. python 进程与线程(理论部分)
  5. Python pytest框架之@pytest.fixture()和conftest详解
  6. 第九章 利用化学知识制药
  7. 【Elasticsearch】 es 搜索 返回信息 字段 解释
  8. 转载:Asp.net 2.0 GridView数据导出Excel文件(示例代码下载)
  9. 又找到一个免费的ASP.net2.0免费空间,支持MS Sql Server Express2005 及Ftp
  10. 一系列JavaScript的基础工具
  11. HIT计算机系统大作业——hello的一生
  12. tar/zip 压缩解压
  13. Android仿微信语音聊天界面
  14. docker容器-nginx conf文件使用环境变量值
  15. 7款英文语法检查工具推荐
  16. 2021-2027全球与中国超声波焊接头市场现状及未来发展趋势
  17. 02 ABY框架的搭建及踩到的坑
  18. Github每日精选(第77期):Go (Golang) 编写的 HTTP Web 框架gin
  19. LLMs之Alpaca:《Alpaca: A Strong, Replicable Instruction-Following Model》翻译与解读
  20. 从 foxmail 到 thunderbird (邮件客户端)

热门文章

  1. php word excel,PHP 生成word 和 excel 文档
  2. 关于java中nextline读取空白行的问题
  3. Codeforces Round #735 (Div. 2)(A-D)没有B
  4. 143. 最大异或对
  5. java 观察者模式_图解Java设计模式之观察者模式
  6. mysql查询错误_一个奇怪的MySQL查询错误
  7. 计算机动画 应用,计算机动画与应用.PDF
  8. Linux TCP server系列(5)-select模式下的单进程server
  9. 五大算法之二--动态规划
  10. ELF动态库加载技术