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为
六种基本函数如下:
就像上图一样,参与运算的都是 32 bit的数,Wt 是 分组之后的报文,512 bit=32bit*16. 也就是 Wt t=1,2..16 由 该组报文产生。
Wt t=17,18,..,64 由 前面的Wt按递推公式 计算出来。Wt递推公式为:
Kt t=1,2..64 是已知的常数。
上面的计算就是不断更新 a,b,c…h这 32bit*8 。在每个512bit的分组里面迭代计算64次。
STEP5:所有的512-bit分组处理完毕后,对于SHA-256算法最后一个分组产生的输出便是256-bit的报文摘要。
实现代码
SHA256.h
- #ifndef _SHA_256_H
- #define _SHA_256_H
- #include<iostream>
- using namespace std;
- typedef unsigned int UInt32;
- //六个逻辑函数
- #define Conditional(x,y,z) ((x&y)^((~x)&z))
- #define Majority(x,y,z) ((x&y)^(x&z)^(y&z))
- #define LSigma_0(x) (ROTL(x,30)^ROTL(x,19)^ROTL(x,10))
- #define LSigma_1(x) (ROTL(x,26)^ROTL(x,21)^ROTL(x,7))
- #define SSigma_0(x) (ROTL(x,25)^ROTL(x,14)^SHR(x,3))
- #define SSigma_1(x) (ROTL(x,15)^ROTL(x,13)^SHR(x,10))
- //信息摘要结构
- struct Message_Digest{
- UInt32 H[8];
- };
- //SHA256类
- class SHA256
- {
- public:
- SHA256(){INIT();};
- ~SHA256(){};
- Message_Digest DEAL(UInt32 W[16]);//处理512比特数据,返回信息摘要
- private:
- void INIT(); //初始杂凑值
- UInt32 ROTR(UInt32 W,int n);//右旋转
- UInt32 ROTL(UInt32 W,int n);//左旋转
- UInt32 SHR(UInt32 W,int n); //右移位
- private:
- //信息摘要
- Message_Digest MD;
- };
- #endif
- #include"SHA-256.h"
- //64个32比特字的常数(前64个素数的立方根小数前32位)
- const UInt32 K[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,
- };
- //初始化杂凑值(前8个素数的平方根小数前32位)
- void SHA256::INIT(){
- MD.H[0] = 0x6a09e667;
- MD.H[1] = 0xbb67ae85;
- MD.H[2] = 0x3c6ef372;
- MD.H[3] = 0xa54ff53a;
- MD.H[4] = 0x510e527f;
- MD.H[5] = 0x9b05688c;
- MD.H[6] = 0x1f83d9ab;
- MD.H[7] = 0x5be0cd19;
- }
- //处理512比特数据,返回信息摘要
- Message_Digest SHA256::DEAL(UInt32 M[16]){
- int i;
- UInt32 T1=0,T2=0;
- UInt32 W[64]={0};
- UInt32 A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0;
- for(i=0;i<16;i++){
- W[i] = M[i];
- }
- for(i=16;i<64;i++){
- W[i] = SSigma_1(W[i-2])+W[i-7]+SSigma_0(W[i-15])+W[i-16];
- }
- A = MD.H[0];
- B = MD.H[1];
- C = MD.H[2];
- D = MD.H[3];
- E = MD.H[4];
- F = MD.H[5];
- G = MD.H[6];
- H = MD.H[7];
- cout<<"初始:";
- cout<<hex<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<" "<<F<<" "<<G<<" "<<H<<endl;
- for(i=0;i<64;i++){
- T1 = H + LSigma_1(E) + Conditional(E, F, G) + K[i] + W[i];
- T2 = LSigma_0(A) + Majority(A, B, C);
- H = G;
- G = F;
- F = E;
- E = D + T1;
- D = C;
- C = B;
- B = A;
- A = T1 + T2;
- cout<<dec<<i<<":";
- cout<<hex<<A<<" "<<B<<" "<<C<<" "<<D<<" "<<E<<" "<<F<<" "<<G<<" "<<H<<endl;
- }
- MD.H[0]=(MD.H[0]+A) & 0xFFFFFFFF;
- MD.H[1]=(MD.H[1]+B) & 0xFFFFFFFF;
- MD.H[2]=(MD.H[2]+C) & 0xFFFFFFFF;
- MD.H[3]=(MD.H[3]+D) & 0xFFFFFFFF;
- MD.H[4]=(MD.H[4]+E) & 0xFFFFFFFF;
- MD.H[5]=(MD.H[5]+F) & 0xFFFFFFFF;
- MD.H[6]=(MD.H[6]+G) & 0xFFFFFFFF;
- MD.H[7]=(MD.H[7]+H) & 0xFFFFFFFF;
- return MD;
- }
- //右旋转
- UInt32 SHA256::ROTR(UInt32 W,int n){
- return ((W >> n) & 0xFFFFFFFF) | (W) << (32-(n));
- }
- //左旋转
- UInt32 SHA256::ROTL(UInt32 W,int n){
- return ((W << n) & 0xFFFFFFFF) | (W) >> (32-(n));
- }
- //右移位
- UInt32 SHA256::SHR(UInt32 W,int n){
- return ((W >> n) & 0xFFFFFFFF);
- }
TEST.CPP
- #include<iostream>
- #include"SHA-256.h"
- using namespace std;
- typedef unsigned int UInt32;
- typedef unsigned __int64 UInt64;
- typedef unsigned char UChar;
- #define Max 1000//最大字符数
- SHA256 sha256=SHA256();
- Message_Digest M_D;
- UInt32 W[Max/4];//整型
- UInt32 M[16]; //存分组信息
- //压缩+显示
- void compress(){
- int i;
- M_D = sha256.DEAL(M);
- cout<<"哈希值: ";
- for(i=0;i<8;i++){
- cout<<hex<<M_D.H[i]<<" ";
- }
- cout<<endl;
- }
- //添加填充位+添加长度
- void PAD(UChar Y[Max]){
- //x+1+d+l=|x|
- UInt32 i,j;
- UInt32 T1=0,T2=0,T3=0,T4=0;
- UChar temp[Max]={0};
- UInt64 x = strlen((char *)Y);//数据长度
- UInt32 d = abs(55-x) % 64; //填充长度
- UInt32 n = (x+8)/64+1; //分组数
- UInt32 m = x%64; //最后组数据长度
- UInt32 l = 8;
- cout<<"数据长度x:"<<int(x)<<" ";
- cout<<"填充长度d:"<<d<<" ";
- cout<<"分组数量n:"<<n<<" ";
- cout<<"最后长度m:"<<m<<endl;
- //不填充
- for(i=0;i<x;i++){
- temp[i] = Y[i];
- }
- //填充1次1000 0000
- temp[x] = 0x80;
- //填充d次0000 0000
- for(i=x+1;i<x+d+1;i++){
- temp[i] = 0x00;
- }
- //填充长度的63-0位
- for(i=1;i<=l;i++){
- temp[(n*64)-i] = (UChar)(8*x>>(i-1)*8);
- }
- //无符号字符转换为无符号整型
- for(i=0;i<Max/4;i++){
- for(j=0;j<4;j++){
- if(j==0)
- T1 = temp[4*i+j];
- if(j==1)
- T2 = temp[4*i+j];
- if(j==2)
- T3 = temp[4*i+j];
- if(j==3)
- T4 = temp[4*i+j];
- }
- W[i] = (T1<<24) + (T2<<16) + (T3<<8) +T4;
- }
- //显示16进制数据
- cout<<"16进制数据:";
- for(i=0;i<n*16;i++){
- cout<<hex<<" "<<W[i];
- }
- cout<<endl;
- //分组处理
- for(i=0;i<n;i++){
- cout<<"分组处理:"<<i+1<<endl;
- for(j=0;j<16;j++){
- M[j] = W[(i*16)+j];
- }
- compress();//sha-256压缩
- }
- }
- //主函数
- int main(){
- UChar Y[Max];
- cout<<"请输入要加密的字符串(最大"<<Max<<"个):"<<endl;
- cin>>Y;
- PAD(Y);
- system("pause");
- return 0;
- }
参考:
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));
}