from: http://blog.csdn.net/lwanttowin/article/details/53726450

时间:2021-11-14 04:02:49

from: http://blog.csdn.net/lwanttowin/article/details/53726450

SHA-256算法实现


SHA-256 算法输入报文的最大长度不超过2^64 bit,输入按512-bit 分组进行处理,产生 

的输出是一个256-bit 的报文摘要。该算法处理包括以下几步: 


STEP1:附加填充比特。对报文进行填充使报文长度与448 模512 同余(长度=448 mod 512), 
填充的比特数范围是1 到512,填充比特串的最高位为1,其余位为0。
就是先在报文后面加一个 1,再加很多个0,直到长度 满足 mod 512=448.
为什么是448,因为448+64=512. 第二步会加上一个 64bit的 原始报文的 长度信息。


STEP2:附加长度值。将用64-bit 表示的初始报文(填充前)的位长度附加在步骤1 的结果 
后(低位字节优先)。


STEP3:初始化缓存。使用一个256-bit 的缓存来存放该散列函数的中间及最终结果。 
该缓存表示为A=0x6A09E667 , B=0xBB67AE85 , C=0x3C6EF372 , D=0xA54FF53A, 
E=0x510E527F , F=0x9B05688C , G=0x1F83D9AB , H=0x5BE0CD19 。


STEP4:处理512-bit(16 个字)报文分组序列。该算法使用了六种基本逻辑函数,由64 
步迭代运算组成。每步都以256-bit 缓存值ABCDEFGH 为输入,然后更新缓存内容。 
每步使用一个32-bit 常数值Kt 和一个32-bit Wt。 

常数K为

from: http://blog.csdn.net/lwanttowin/article/details/53726450

六种基本函数如下:

from: http://blog.csdn.net/lwanttowin/article/details/53726450

from: http://blog.csdn.net/lwanttowin/article/details/53726450

from: http://blog.csdn.net/lwanttowin/article/details/53726450

就像上图一样,参与运算的都是 32 bit的数,Wt 是 分组之后的报文,512 bit=32bit*16. 也就是 Wt t=1,2..16 由 该组报文产生。
Wt t=17,18,..,64 由 前面的Wt按递推公式 计算出来。Wt递推公式为:

from: http://blog.csdn.net/lwanttowin/article/details/53726450
Kt t=1,2..64 是已知的常数。


上面的计算就是不断更新 a,b,c…h这 32bit*8 。在每个512bit的分组里面迭代计算64次。


STEP5:所有的512-bit分组处理完毕后,对于SHA-256算法最后一个分组产生的输出便是256-bit的报文摘要。


实现代码

SHA256.h

  1. #ifndef _SHA_256_H  
  2. #define _SHA_256_H  
  3. #include<iostream>  
  4. using namespace std;  
  5. typedef unsigned int UInt32;  
  6. //六个逻辑函数  
  7. #define Conditional(x,y,z) ((x&y)^((~x)&z))  
  8. #define Majority(x,y,z) ((x&y)^(x&z)^(y&z))  
  9. #define LSigma_0(x) (ROTL(x,30)^ROTL(x,19)^ROTL(x,10))  
  10. #define LSigma_1(x) (ROTL(x,26)^ROTL(x,21)^ROTL(x,7))  
  11. #define SSigma_0(x) (ROTL(x,25)^ROTL(x,14)^SHR(x,3))  
  12. #define SSigma_1(x) (ROTL(x,15)^ROTL(x,13)^SHR(x,10))  
  13. //信息摘要结构  
  14. struct Message_Digest{  
  15.     UInt32 H[8];  
  16. };  
  17. //SHA256类  
  18. class SHA256  
  19. {  
  20. public:  
  21.     SHA256(){INIT();};  
  22.     ~SHA256(){};  
  23.     Message_Digest DEAL(UInt32 W[16]);//处理512比特数据,返回信息摘要  
  24. private:  
  25.     void INIT();                //初始杂凑值  
  26.     UInt32 ROTR(UInt32 W,int n);//右旋转  
  27.     UInt32 ROTL(UInt32 W,int n);//左旋转  
  28.     UInt32 SHR(UInt32 W,int n); //右移位  
  29. private:  
  30.     //信息摘要  
  31.     Message_Digest MD;  
  32. };  
  33.   
  34. #endif  


SHA256.cpp
  1. #include"SHA-256.h"  
  2. //64个32比特字的常数(前64个素数的立方根小数前32位)  
  3. const UInt32 K[64] = {  
  4.         0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,  
  5.         0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,  
  6.         0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,  
  7.         0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,  
  8.         0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,  
  9.         0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,  
  10.         0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,  
  11.         0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,  
  12. };  
  13. //初始化杂凑值(前8个素数的平方根小数前32位)  
  14. void SHA256::INIT(){  
  15.     MD.H[0] = 0x6a09e667;  
  16.     MD.H[1] = 0xbb67ae85;  
  17.     MD.H[2] = 0x3c6ef372;  
  18.     MD.H[3] = 0xa54ff53a;  
  19.         MD.H[4] = 0x510e527f;  
  20.     MD.H[5] = 0x9b05688c;  
  21.     MD.H[6] = 0x1f83d9ab;  
  22.     MD.H[7] = 0x5be0cd19;  
  23. }  
  24. //处理512比特数据,返回信息摘要  
  25. Message_Digest SHA256::DEAL(UInt32 M[16]){  
  26.     int i;  
  27.     UInt32 T1=0,T2=0;  
  28.     UInt32 W[64]={0};  
  29.     UInt32 A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0;  
  30.     for(i=0;i<16;i++){  
  31.         W[i] = M[i];  
  32.     }  
  33.     for(i=16;i<64;i++){  
  34.         W[i] = SSigma_1(W[i-2])+W[i-7]+SSigma_0(W[i-15])+W[i-16];  
  35.     }  
  36.     A = MD.H[0];  
  37.     B = MD.H[1];  
  38.     C = MD.H[2];  
  39.     D = MD.H[3];  
  40.     E = MD.H[4];  
  41.     F = MD.H[5];  
  42.     G = MD.H[6];  
  43.     H = MD.H[7];  
  44.     cout<<"初始:";  
  45.     cout<<hex<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<" "<<F<<" "<<G<<" "<<H<<endl;  
  46.     for(i=0;i<64;i++){  
  47.         T1 = H + LSigma_1(E) + Conditional(E, F, G) + K[i] + W[i];  
  48.         T2 = LSigma_0(A) + Majority(A, B, C);  
  49.         H = G;  
  50.         G = F;  
  51.         F = E;  
  52.         E = D + T1;  
  53.         D = C;  
  54.         C = B;  
  55.         B = A;  
  56.         A = T1 + T2;  
  57.         cout<<dec<<i<<":";  
  58.         cout<<hex<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<" "<<F<<" "<<G<<" "<<H<<endl;  
  59.     }  
  60.     MD.H[0]=(MD.H[0]+A) & 0xFFFFFFFF;  
  61.     MD.H[1]=(MD.H[1]+B) & 0xFFFFFFFF;  
  62.     MD.H[2]=(MD.H[2]+C) & 0xFFFFFFFF;  
  63.     MD.H[3]=(MD.H[3]+D) & 0xFFFFFFFF;  
  64.     MD.H[4]=(MD.H[4]+E) & 0xFFFFFFFF;  
  65.     MD.H[5]=(MD.H[5]+F) & 0xFFFFFFFF;  
  66.     MD.H[6]=(MD.H[6]+G) & 0xFFFFFFFF;  
  67.     MD.H[7]=(MD.H[7]+H) & 0xFFFFFFFF;  
  68.   
  69.     return MD;  
  70. }  
  71. //右旋转  
  72. UInt32 SHA256::ROTR(UInt32 W,int n){  
  73.     return ((W >> n) & 0xFFFFFFFF) | (W) << (32-(n));  
  74. }  
  75. //左旋转  
  76. UInt32 SHA256::ROTL(UInt32 W,int n){  
  77.     return ((W << n) & 0xFFFFFFFF) | (W) >> (32-(n));  
  78. }  
  79. //右移位  
  80. UInt32 SHA256::SHR(UInt32 W,int n){  
  81.     return ((W >> n) & 0xFFFFFFFF);  
  82. }  

TEST.CPP
  1. #include<iostream>  
  2. #include"SHA-256.h"  
  3. using namespace std;  
  4.   
  5. typedef unsigned int UInt32;  
  6. typedef unsigned __int64 UInt64;  
  7. typedef unsigned char UChar;  
  8. #define Max 1000//最大字符数  
  9. SHA256 sha256=SHA256();  
  10. Message_Digest M_D;  
  11. UInt32 W[Max/4];//整型  
  12. UInt32 M[16];   //存分组信息  
  13. //压缩+显示  
  14. void compress(){  
  15.     int i;  
  16.     M_D = sha256.DEAL(M);  
  17.     cout<<"哈希值: ";  
  18.     for(i=0;i<8;i++){  
  19.         cout<<hex<<M_D.H[i]<<" ";  
  20.     }  
  21.     cout<<endl;  
  22. }  
  23. //添加填充位+添加长度  
  24. void PAD(UChar Y[Max]){  
  25.     //x+1+d+l=|x|  
  26.     UInt32 i,j;  
  27.     UInt32 T1=0,T2=0,T3=0,T4=0;  
  28.     UChar temp[Max]={0};  
  29.     UInt64 x = strlen((char *)Y);//数据长度  
  30.     UInt32 d = abs(55-x) % 64;   //填充长度  
  31.     UInt32 n = (x+8)/64+1; //分组数  
  32.     UInt32 m = x%64;       //最后组数据长度  
  33.     UInt32 l = 8;        
  34.     cout<<"数据长度x:"<<int(x)<<" ";  
  35.     cout<<"填充长度d:"<<d<<" ";  
  36.     cout<<"分组数量n:"<<n<<" ";  
  37.     cout<<"最后长度m:"<<m<<endl;  
  38.     //不填充  
  39.     for(i=0;i<x;i++){  
  40.         temp[i] = Y[i];  
  41.     }  
  42.     //填充1次1000 0000  
  43.         temp[x] = 0x80;  
  44.     //填充d次0000 0000  
  45.     for(i=x+1;i<x+d+1;i++){  
  46.         temp[i] = 0x00;  
  47.     }  
  48.     //填充长度的63-0位  
  49.     for(i=1;i<=l;i++){  
  50.         temp[(n*64)-i] = (UChar)(8*x>>(i-1)*8);  
  51.     }  
  52.     //无符号字符转换为无符号整型  
  53.     for(i=0;i<Max/4;i++){  
  54.         for(j=0;j<4;j++){  
  55.             if(j==0)  
  56.                 T1 = temp[4*i+j];  
  57.             if(j==1)  
  58.                 T2 = temp[4*i+j];  
  59.             if(j==2)  
  60.                 T3 = temp[4*i+j];  
  61.             if(j==3)  
  62.                 T4 = temp[4*i+j];  
  63.         }  
  64.         W[i] = (T1<<24) + (T2<<16) + (T3<<8) +T4;  
  65.     }  
  66.     //显示16进制数据  
  67.     cout<<"16进制数据:";  
  68.     for(i=0;i<n*16;i++){  
  69.         cout<<hex<<" "<<W[i];  
  70.     }  
  71.     cout<<endl;  
  72.     //分组处理  
  73.     for(i=0;i<n;i++){  
  74.         cout<<"分组处理:"<<i+1<<endl;  
  75.         for(j=0;j<16;j++){  
  76.             M[j] = W[(i*16)+j];  
  77.         }  
  78.         compress();//sha-256压缩  
  79.     }  
  80. }  
  81. //主函数  
  82. int main(){  
  83.     UChar Y[Max];  
  84.     cout<<"请输入要加密的字符串(最大"<<Max<<"个):"<<endl;  
  85.     cin>>Y;  
  86.     PAD(Y);  
  87.   
  88.     system("pause");  
  89.     return 0;  
  90. }  


参考:

http://www.iwar.org.uk/comsec/resources/cipher/sha256-384-512.pdf



from: 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#############################################