sha是典型的哈希算法,我曾经在博客中写过源码来实现,现在只需要读懂源码就可以了。
这是安全相关的函数,其实,很多安全函数都是挺难读懂的,里面各种奇奇怪怪的数字。
- void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len)
 - {
 - 	WORD i;
 -  
 - 	for (i = 0; i < len; ++i) {
 - 		ctx->data[ctx->datalen] = data[i];
 - 		ctx->datalen++;
 - 		if (ctx->datalen == 64) {
 - 			sha256_transform(ctx, ctx->data);
 - 			ctx->bitlen += 512;
 - 			ctx->datalen = 0;
 - 		}
 - 	}
 - }
 -  
 - void sha256_final(SHA256_CTX *ctx, BYTE hash[])
 - {
 - 	WORD i;
 -  
 - 	i = ctx->datalen;
 -  
 - 	// Pad whatever data is left in the buffer.
 - 	if (ctx->datalen < 56) {
 - 		ctx->data[i++] = 0x80;
 - 		while (i < 56)
 - 			ctx->data[i++] = 0x00;
 - 	}
 - 	else {
 - 		ctx->data[i++] = 0x80;
 - 		while (i < 64)
 - 			ctx->data[i++] = 0x00;
 - 		sha256_transform(ctx, ctx->data);
 - 		memset(ctx->data, 0, 56);
 - 	}
 -  
 - 	// Append to the padding the total message's length in bits and transform.
 - 	ctx->bitlen += ctx->datalen * 8;
 - 	ctx->data[63] = ctx->bitlen;
 - 	ctx->data[62] = ctx->bitlen >> 8;
 - 	ctx->data[61] = ctx->bitlen >> 16;
 - 	ctx->data[60] = ctx->bitlen >> 24;
 - 	ctx->data[59] = ctx->bitlen >> 32;
 - 	ctx->data[58] = ctx->bitlen >> 40;
 - 	ctx->data[57] = ctx->bitlen >> 48;
 - 	ctx->data[56] = ctx->bitlen >> 56;
 - 	sha256_transform(ctx, ctx->data);
 -  
 - 	// Since this implementation uses little endian byte ordering and SHA uses big endian,
 - 	// reverse all the bytes when copying the final state to the output hash.
 - 	for (i = 0; i < 4; ++i) {
 - 		hash[i]      = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 4]  = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 8]  = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff;
 - 		hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff;
 - 	}
 - }
 
                
                

















