C语言代码实现sha256算法

################################sha256.h##########################################

#define SHA256_HASH_LEN 32


typedef struct {

unsigned int h0;
unsigned int h1;
unsigned int h2;
unsigned int h3;
unsigned int h4;
unsigned int h5;
unsigned int h6;
unsigned int h7;
unsigned int nblocks;
unsigned int buf[16];
unsigned shortcount;
}SHA256_CONTEXT;


void L_sha256_init(char* pContxt);
void L_sha256_update(char *pContxt, const char *pSrcBuf, int wSrcLen);
void L_sha256_final(char* pContxt, char* pDestBuf);


void calc_sha256_endstep(char* pContxt);


################################ end#############################################



################################sha256.c#########################################

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h> 
#include "sha256.h"


/****************
 * Rotate a 32 bit integer by n bytes
 ****************/   
#define shr(x,n) ( x >> n )
#define rotr(x,n) ( (x >> n) | (x << (32-n)) )


#define SETDWORD(buffer, val)     \
do      \
{       \
(buffer)[0] = (char)((val) >> 24);      \
(buffer)[1] = (char)((val) >> 16);      \
(buffer)[2] = (char)((val) >> 8);       \
(buffer)[3] = (char)(val);              \
}while(0)


#define GETDWORD(p)     ((DWORD)(p)[0]<<24 | (DWORD)(p)[1]<<16 | (WORD)(p)[2]<<8 | (p)[3])


unsigned int K256[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};


// Transform the message X which consists of 16 32-bit-words
void sha256_transform(SHA256_CONTEXT *hd)
{
unsigned int *x = hd->buf;
unsigned int a,b,c,d,e,f,g,h,t1,t2; //s0,s1
unsigned int W[64];
unsigned char num;


/* get values from the chaining vars */
a = hd->h0;
b = hd->h1;
c = hd->h2;
d = hd->h3;
e = hd->h4;
f = hd->h5;
g = hd->h6;
h = hd->h7;

//printf("a = %x\nb = %x\nc = %x\nd = %x\ne = %x\nf = %x\ng = %x\nh = %x\n",a,b,c,d,e,f,g,h);


#define Sigma0(x) ( (rotr(x,2)) ^ (rotr(x,13)) ^ (rotr(x,22)) )
#define Sigma1(x) ( (rotr(x,6)) ^ (rotr(x,11)) ^ (rotr(x,25)) )
#define Gamma0(x) ( (rotr(x,7)) ^ (rotr(x,18)) ^ (shr(x,3))  )
#define Gamma1(x) ( (rotr(x,17)) ^ (rotr(x,19)) ^ (shr(x,10)) )


#define Ch(x,y,z) ( (x & y) ^ ((~x) & z) )
#define Maj(x,y,z)       ( (x & y) ^ (x & z) ^ (y & z) )


/*#define R(a,b,c,d,e,f,g,h,i)      do{ t1 = h + Sigma1(e) + Ch(e, f, g) + K256[i] + Wt;  \
t2 = Sigma0(a) + Maj(a, b, c);                    \
d += t1;                                          \
h  = t1 + t2;                                     \
   }while(0)*/


//#define M(i) ( x[i&0x0f] += x[(i-15)&0x0f] + x[(i-7)&0x0f] + x[(i-2)&0x0f] )

for(num = 0; num < 64; num++)
{
if(num < 16)
{  
W[num] = ntohl(x[num]);
                        printf("W[%d] = %x\n", num, W[num]); 
printf("Wt = %x\n", x[num]);                      
}
else
{     
W[num] = Gamma1(W[num - 2]) + W[num - 7] + Gamma0(W[num - 15]) + W[num - 16];
                         printf("W[%d] = %x\n", num, W[num]);
}              
   
t1 = h + Sigma1(e) + Ch(e, f, g) + K256[num] + W[num];  
t2 = Sigma0(a) + Maj(a, b, c);


                h = g; 
                g = f;
                f = e;
                e = d + t1;
d = c; 
                c = b;
                b = a;
a = t1 + t2;                       

 if(num >= 15)           //for a test
{          
printf("a = %x\n", a);
printf("b = %x\n", b);
printf("c = %x\n", c);
printf("d = %x\n", d);
printf("e = %x\n", e);
printf("f = %x\n", f);
printf("g = %x\n", g);
printf("h = %x\n", h);
       printf("\n");
}

}

/* Update chaining vars */
hd->h0 += a;
hd->h1 += b;
hd->h2 += c;
hd->h3 += d;
hd->h4 += e;
hd->h5 += f;
hd->h6 += g;
hd->h7 += h; 


printf("a = %x\n", hd->h0);
printf("b = %x\n", hd->h1);
printf("c = %x\n", hd->h2);
printf("d = %x\n", hd->h3);
printf("e = %x\n", hd->h4);
printf("f = %x\n", hd->h5);
printf("g = %x\n", hd->h6);
printf("h = %x\n", hd->h7);
        printf("\n");
}


void L_sha256_init(char *pContxt)
{
SHA256_CONTEXT *hd = (SHA256_CONTEXT *)pContxt;

hd->h0 = 0x6a09e667;
hd->h1 = 0xbb67ae85;
hd->h2 = 0x3c6ef372;
hd->h3 = 0xa54ff53a;
hd->h4 = 0x510e527f;
hd->h5 = 0x9b05688c;
hd->h6 = 0x1f83d9ab;
hd->h7 = 0x5be0cd19;
hd->nblocks = 0;
hd->count = 0;
}


// Update the message digest with the contents
void L_sha256_update(char *pContxt, const char *pSrcBuf, int wSrcLen)
{
SHA256_CONTEXT *hd = (SHA256_CONTEXT *)pContxt;
char *pBuf = (char *)hd->buf;

while((wSrcLen + hd->count) >= 64)
{
char costLen = 64 - hd->count;
memcpy(pBuf + hd->count, pSrcBuf, costLen);       
                
/*FILE *fp;       // for a test
fp=fopen("data.txt","wr");
if(fp==NULL)
{
printf("Fail to create file");
exit(-1);
}


fwrite(hd->buf, 1, 64, fp);
fclose(fp);     // end test*/


sha256_transform(hd);
hd->count = 0;
hd->nblocks++;
wSrcLen -= costLen;
pSrcBuf += costLen;
}
memcpy(pBuf + hd->count, pSrcBuf, wSrcLen);
        hd->count += wSrcLen;   


//printf("pSrcBuf:%s,hd->buf[0] = %x\n",pSrcBuf, hd->buf[0]);   

}


// The routine final terminates the computation and
// returns the digest.
// The handle is prepared for a new cycle, but adding bytes to the
// handle will the destroy the returned buffer.
// Returns: 20 bytes representing the digest.
void calc_sha256_endstep(char *pContxt)
{
SHA256_CONTEXT *hd = (SHA256_CONTEXT *)pContxt;
unsigned int t;
unsigned int msb;
unsigned int lsb;
unsigned char tmp;


t = hd->nblocks;
// multiply by 64 to make a byte count 
lsb = t << 6;
msb = t >> 26;
// add the count 
t = lsb;
if((lsb += hd->count) < t)
msb++;
// multiply by 8 to make a bit count 
t = lsb;
lsb <<= 3;
msb <<= 3;
msb |= t >> 29;


tmp = 0x80;
L_sha256_update(pContxt, &tmp, 1);


tmp = 0x00;
while(hd->count != 56)
L_sha256_update(pContxt, &tmp, 1);        
      
    //append the 64 bit count
  {
char tailBuf[8];
SETDWORD(tailBuf, msb);
SETDWORD(tailBuf+sizeof(msb), lsb);
L_sha256_update(pContxt, tailBuf, sizeof(tailBuf));
}            
 
}

void L_sha256_final(char* pContxt, char* pDestBuf)
{
SHA256_CONTEXT  *hd = (SHA256_CONTEXT *)pContxt;


calc_sha256_endstep(pContxt);
memcpy(pDestBuf, &hd->h0, SHA256_HASH_LEN);
memset(hd, 0, sizeof(*hd));
}


################################end#############################################


  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SHA-256是一种加密哈希算法,其用途是将输入的任意长度的数据转换为固定长度的哈希值。在C语言中,我们可以使用以下方式实现SHA-256的最终处理函数: 1. 首先,我们需要定义一些预定义常量和数据结构。这些变量包括SHA-256的初始哈希值,以及一些用于处理消息块的辅助变量。 ```c #include <stdint.h> // 定义SHA-256初始哈希值 const uint32_t sha256_initial_hash[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; // 定义SHA-256的辅助变量 uint32_t sha256_hash[8]; uint32_t sha256_data[16]; ``` 2. 实现SHA-256最终处理函数的主体部分。这个函数将在所有的消息块都经过处理后被调用。 ```c #include <string.h> void sha256_final(unsigned char *hash) { // 将数据长度转换为比特位 uint64_t bit_length = bit_count * 8; // 添加一个1和若干个0来填充最后一个消息块 sha256_data[data_index++] = 0x80; // 检查消息块是否有足够的空间来存储数据长度描述 if (data_index > 14) { while (data_index < 16) { sha256_data[data_index++] = 0; } sha256_transform(); memset(sha256_data, 0, sizeof(sha256_data)); } // 最后四个字节存储数据长度(比特位) sha256_data[14] = bit_length >> 32; sha256_data[15] = bit_length & 0xffffffff; // 完成最后一个消息块的处理 sha256_transform(); // 将哈希值复制到输出缓冲区 for (int i = 0; i < 8; ++i) { hash[i * 4] = sha256_hash[i] >> 24; hash[i * 4 + 1] = (sha256_hash[i] >> 16) & 0xff; hash[i * 4 + 2] = (sha256_hash[i] >> 8) & 0xff; hash[i * 4 + 3] = sha256_hash[i] & 0xff; } } ``` 以上代码片段演示了SHA-256最终处理函数的C语言实现。在实际中,我们还需要实现其他函数,如数据填充、消息转换等,以完成整个SHA-256算法实现
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值