常用加解密的C语言实现,持续更新...

目前只有MD5、SHA256;以下代码可以计算文件、字符串的MD5值

MD5

#include <stdio.h>
#include <stdlib.h>
#include "Green_CryptLib_MD5.h"


int main(int argc, char *argv[])
{
    int ret = 0;
    char md5[64] = {0};
    char dst_md5[64] = {0};
    char *file_path = "../md5_test.c";
    char *src = "123456";
    
    ret = Get_FileMd5(file_path, 32, md5, sizeof(md5));
    if (0 != ret)
    {
        printf("md5_file fail\n");
        return 1;
    }
    
    printf("md5 32byte:%s\n", md5);

    ret = Get_StringMd5(src, dst_md5, sizeof(dst_md5));
    if (0 != ret)
    {
        printf("md5_string fail\n");
        return 1;
    }
    
    printf("md5 32byte:%s\n", dst_md5);
    
    return 0;
}  

SHA256

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "Green_CryptLib_Sha256.h"


int main (int ArgC, char **ArgV)
{
    char*           string;
    Sha256Context   sha256Context;
    SHA256_HASH     sha256Hash;
    uint16_t        i;
    char buf[65] = {0};
    
    if( 2 != ArgC )
    {
        printf(
            "Syntax\n"
            "   Sha256String <String>\n" );
        return 1;
    }

    string = ArgV[1];

    Sha256Calculate((unsigned char*)string, (uint32_t)strlen(string), buf, 65);
    
    printf( "result:%s\n" , buf);

    return 0;
}

Green_CryptLib_MD5.c

/******************************************************************************
 * 模块名称: MD5-MD5加密模块
 * 修改记录: 2009-03-13 V1.0.0
 *****************************************************************************/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "Green_CryptLib_MD5.h"
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>

static unsigned char PADDING[64] =
{
    (char)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
};

/* Constants for MD5Transform routine. */
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21

/* F, G, H and I are basic MD5 functions. */
#define F(x, y, z)          (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z)          (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z)          ((x) ^ (y) ^ (z))
#define I(x, y, z)          ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n)   (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation. */
#define FF(a, b, c, d, x, s, ac) { (a) += F ((b), (c), (d)) + (x) + (unsigned int)(ac);  (a) = ROTATE_LEFT ((a), (s)); (a) += (b);  }
#define GG(a, b, c, d, x, s, ac) { (a) += G ((b), (c), (d)) + (x) + (unsigned int)(ac);  (a) = ROTATE_LEFT ((a), (s)); (a) += (b);  }
#define HH(a, b, c, d, x, s, ac) { (a) += H ((b), (c), (d)) + (x) + (unsigned int)(ac);  (a) = ROTATE_LEFT ((a), (s)); (a) += (b);  }
#define II(a, b, c, d, x, s, ac) { (a) += I ((b), (c), (d)) + (x) + (unsigned int)(ac);  (a) = ROTATE_LEFT ((a), (s)); (a) += (b);  }

/* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */
#define Encode(to, from, size) memcpy(to, from, size)

/* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */
#define Decode(to, from, size) memcpy(to, from, size)

#define MD5_memcpy(to, from, size) memcpy(to, from, size)
#define MD5_memset(buf, val, size) memset(buf, val, size)

/* MD5 basic transformation. Transforms state based on block. */
static void MD5Transform(unsigned int state[4], unsigned char block[64])
{
    unsigned int a = state[0], b = state[1], c = state[2], d = state[3], x[16];

    Decode (x, block, 64);
    /* Round 1 */
    FF(a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
    FF(d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
    FF(c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
    FF(b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
    FF(a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
    FF(d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
    FF(c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
    FF(b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
    FF(a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
    FF(d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
    FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
    FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
    FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
    FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
    FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
    FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
    /* Round 2 */
    GG(a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
    GG(d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
    GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
    GG(b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
    GG(a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
    GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */
    GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
    GG(b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
    GG(a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
    GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
    GG(c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
    GG(b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
    GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
    GG(d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
    GG(c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
    GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
    /* Round 3 */
    HH(a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
    HH(d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
    HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
    HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
    HH(a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
    HH(d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
    HH(c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
    HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
    HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
    HH(d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
    HH(c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
    HH(b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
    HH(a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
    HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
    HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
    HH(b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
    /* Round 4 */
    II(a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
    II(d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
    II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
    II(b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
    II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
    II(d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
    II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
    II(b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
    II(a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
    II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
    II(c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
    II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
    II(a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
    II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
    II(c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
    II(b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
    state[0] += a;
    state[1] += b;
    state[2] += c;
    state[3] += d;
    /* Zeroize sensitive information.
    */
    MD5_memset(x, 0, sizeof (x));
}

/* MD5 initialization. Begins an MD5 operation, writing a new context. */
void MD5Init(MD5_CTX *context)                                         /* context */
{
    context->count[0] = context->count[1] = 0;
    /* Load magic initialization constants.*/
    context->state[0] = 0x67452301;
    context->state[1] = 0xefcdab89;
    context->state[2] = 0x98badcfe;
    context->state[3] = 0x10325476;
}

/* MD5 block update operation. Continues an MD5 message-digest
  operation, processing another message block, and updating the  context. */
void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen)
{
    unsigned int i, index, partLen; /* Compute number of bytes mod 64 */
    MD5_CTX *context_tmp=context;
    index = (context_tmp->count[0] >> 3) & 0x3F;
    /* Update number of bits */
    if ((context_tmp->count[0] += (inputLen << 3)) < (inputLen << 3))
        context_tmp->count[1]++;

    context_tmp->count[1] += (inputLen >> 29);
    partLen = 64 - index;

    /* Transform as many times as possible.*/
    if (inputLen >= partLen) {
        MD5_memcpy(context_tmp->buffer+index, input, partLen);
        MD5Transform(context_tmp->state, context_tmp->buffer);

        for (i = partLen; i + 63 < inputLen; i += 64)
            MD5Transform(context_tmp->state, input+i);
        index = 0;
    }
    else
        i = 0;

    /* Buffer remaining input */
    MD5_memcpy(context_tmp->buffer+index, input+i,  inputLen-i);
}

/* MD5 finalization. Ends an MD5 message-digest operation, writing the
  the message digest and zeroizing the context. */
void MD5Final(unsigned char* digest, MD5_CTX *context)
{
    unsigned char bits[8];
    unsigned int index, padLen;  /* Save number of bits */

    Encode(bits, context->count, 8);  /* Pad out to 56 mod 64.*/
    index = (context->count[0] >> 3) & 0x3f;
    padLen = (index < 56) ? (56 - index) : (120 - index);
    MD5Update(context, PADDING, padLen);  /* Append length (before padding) */
    MD5Update(context, bits, 8);
    /* Store state in digest */
    Encode(digest, context->state, 16);
    /* Zeroize sensitive information.*/
    MD5_memset(context, 0, sizeof (*context));
}

int MDString(unsigned char *string, int nLen, unsigned char *digest)
{
    MD5_CTX context;

    MD5Init(&context);
    MD5Update(&context, string, nLen);
    MD5Final(digest, &context);

    return 0;
}

#define MAXMD5SOURCESTRINGLEN 128
#define MD5STRINGLEN 16
#define PADLEN 64

int MD5Encode(unsigned char *szEncoded, const unsigned char *szData,
    int nSize, unsigned char *szKey, int nKeyLen)
{
    // See rfc2104
    int i = 0;
    unsigned char firstPad[PADLEN + MAXMD5SOURCESTRINGLEN + 1];
    unsigned char K[PADLEN], midResult[PADLEN + 16];

    memset(firstPad, 0, sizeof(firstPad));
    memset(K, 0, PADLEN);
    memcpy(K, szKey, nKeyLen);

    for (i = 0; i < PADLEN; i++)
    {
        firstPad[i] = 0x36 ^ K[i];
        midResult[i] = 0x5c ^ K[i];
    }

    memcpy(firstPad + PADLEN, szData, nSize);
    firstPad[PADLEN + nSize] = '\0';
    MDString(firstPad, PADLEN + nSize, midResult + PADLEN);
    MDString(midResult, PADLEN + 16, szEncoded);

    return 16;
}

int chap_auth(char *hash, char id, char *pwd, int pwd_size, char *chal, int chal_size)
{
    MD5_CTX context;

  MD5Init (&context);
  MD5Update(&context, (unsigned char *)&id, 1);
  MD5Update(&context, (unsigned char *)pwd, pwd_size);
  MD5Update(&context, (unsigned char *)chal, chal_size);
  MD5Final((unsigned char *)hash, &context);

  return 16;
}

/*input:id--用户登录的ID号,网络包头部的第5个字节,开始PC传给DVR的加密密码的ID号保证为0
  pwd:需要加密的密码
  pwdlen:密码的长度
output:hash:加密后的密码(默认长度为16个字节)
*/

static int MD5_enc(char id, char *pwd, char pwdlen, char *hash)
{
  unsigned char chal[] = {0x50,0xfd,0xfd,0x87,0x1c,0x1b,0xd1,0x44,0x9b,0x67,0xdb,0x0d,0x7e,0xed,0xd9,0x1e};
  return chap_auth(hash, id, pwd, pwdlen,(char *)chal, 16);
}

typedef unsigned char HASH[HASHLEN];
typedef char          HASHHEX[HASHHEXLEN+1];
static  const char    hex_chars[] = "0123456789abcdef";

static char int2hex(char c)
{
    return hex_chars[(c & 0x0F)];
}

static void CvtHex(HASH Bin, HASHHEX Hex)
{
    unsigned short i;

    for (i = 0; i < HASHLEN; i++) {
        Hex[i*2] = int2hex((Bin[i] >> 4) & 0xf);
        Hex[i*2+1] = int2hex(Bin[i] & 0xf);
    }
    Hex[HASHHEXLEN] = '\0';
}

/****************************************************************
函数名 :    Get_StringMd5
参   数 : [IN] src_str 需要计算MD5值的字符串
         [IN] desc_str 存储计算得到的MD5值
        
返回值 :  1 成功
说   明 :计算一段字符串的MD5值
******************************************************************/
int Get_StringMd5(IN char *src_str, INOUT char *desc_str, IN int DestbufLen)
{
    MD5_CTX Md5Ctx;
    HASH HA1;

    if ((NULL == src_str) || (NULL == desc_str) || (DestbufLen < 64))
    {
        printf("invalid params\n");
        return ERR_COMMON_INVALID_PARAM;
    }

    /* 初始化 */
    MD5Init(&Md5Ctx);

    /* md5加密 */
    MD5Update(&Md5Ctx, (unsigned char *)src_str, strlen(src_str));

    /* 加密 */
    MD5Final(HA1, &Md5Ctx);

    /* 转换为字符串 */
    CvtHex(HA1, desc_str);
    
    return 0;
}

/****************************************************************
函数名 :    GET_FileMd5
参   数 : [IN] path 需要计算MD5值得文件路径
         [IN] md5_len 需要计算的MD5值长度,16/32
        
返回值 :  MD5值字符串
说   明 :计算一个给定文件的MD5值
******************************************************************/
int Get_FileMd5 (IN char *pcFilePath, IN int md5_len, OUT char *pcDestBuf, IN int DestbufLen)
{
    int i;
    int bytes;
    HASH HA1;
    MD5_CTX mdContext;
    unsigned char data[1024] = {0};
    char *file_md5 = NULL; 
    FILE *fp = NULL;
    
    if ((NULL == pcFilePath) || (0 != access(pcFilePath, F_OK)) || (NULL == pcDestBuf) || (DestbufLen < 64))
    {
        printf("invalid params\n");
        return ERR_COMMON_INVALID_PARAM;
    }

    fp = fopen (pcFilePath, "rb");
    if (fp == NULL)
    {
        printf("fopen %s failed\n", pcFilePath);
        return ERR_COMMON_FILE_CANT_OPEN;
    }  

    MD5Init (&mdContext);
    
    while ((bytes = fread (data, 1, 1024, fp)) != 0)
    {
        MD5Update (&mdContext, data, bytes);
    }
    
    MD5Final (HA1, &mdContext);
    
    fclose (fp);

    if(md5_len == 16)
    {  
        for(i=4; i<12; i++)
        {  
            sprintf(&pcDestBuf[(i-4)*2], "%02x", HA1[i]);
        }
    }
    else if(md5_len == 32)
    {  
        for(i=0; i<16; i++)
        {
            sprintf(&pcDestBuf[i*2], "%02x", HA1[i]);
        }
    }
    
    return 0;
}

Green_CryptLib_MD5.h

#ifndef _GREEN_CRYPTO_MD5_H
#define _GREEN_CRYPTO_MD5_H

#include "errcode.h"

typedef struct
{
    unsigned int state[4]; /* state (ABCD) */
    unsigned int count[2]; /* number of bits, modulo 2^64 (lsb first) */
    unsigned char buffer[64]; /* input buffer */
} MD5_CTX, *PMD5_CTX;

#define HASHLEN       16
#define HASHHEXLEN    32

void MD5Init(MD5_CTX *context);
void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen);
void MD5Final(unsigned char* digest, MD5_CTX *context);
int MD5Encode(unsigned char *szEncoded, const unsigned char *szData,
    int nSize, unsigned char *szKey, int nKeyLen);
int chap_auth(char *hash, char id, char *pwd, int pwd_size, char *chal, int chal_size);

int Get_StringMd5(IN char *src_str, INOUT char *desc_str, IN int DestbufLen);
int Get_FileMd5 (IN char *pcFilePath, IN int md5_len, OUT char *pcDestBuf, IN int DestbufLen);

#endif /* _GREEN_CRYPTO_MD5_H */

Green_CryptLib_Sha256.c


#include "Green_CryptLib_Sha256.h"
#include <memory.h>

#define ror(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits))))

#define MIN(x, y) (((x)<(y))?(x):(y))

#define STORE32H(x, y)                                                                     \
     { (y)[0] = (uint8_t)(((x)>>24)&255); (y)[1] = (uint8_t)(((x)>>16)&255);   \
       (y)[2] = (uint8_t)(((x)>>8)&255); (y)[3] = (uint8_t)((x)&255); }

#define LOAD32H(x, y)                            \
     { x = ((uint32_t)((y)[0] & 255)<<24) | \
           ((uint32_t)((y)[1] & 255)<<16) | \
           ((uint32_t)((y)[2] & 255)<<8)  | \
           ((uint32_t)((y)[3] & 255)); }

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (uint8_t)(((x)>>56)&255); (y)[1] = (uint8_t)(((x)>>48)&255);     \
     (y)[2] = (uint8_t)(((x)>>40)&255); (y)[3] = (uint8_t)(((x)>>32)&255);     \
     (y)[4] = (uint8_t)(((x)>>24)&255); (y)[5] = (uint8_t)(((x)>>16)&255);     \
     (y)[6] = (uint8_t)(((x)>>8)&255); (y)[7] = (uint8_t)((x)&255); }


// The K array
static const uint32_t K[64] = {
    0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
    0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
    0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
    0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
    0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
    0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
    0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
    0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
    0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
    0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
    0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
    0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
    0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};

#define BLOCK_SIZE          64


// Various logical functions
#define Ch(x, y, z)     (z ^ (x & (y ^ z)))
#define Maj(x, y, z)    (((x | y) & z) | (x & y))
#define S(x, n)         ror((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))

#define Sha256Round(a, b, c, d, e, f, g, h, i)       \
     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                    \
     d += t0;                                          \
     h  = t0 + t1;

static void TransformFunction(INOUT Sha256Context *Context, uint8_t const *Buffer)
{
    int i;
    uint32_t t0;
    uint32_t t1;
    uint32_t t;
    uint32_t S[8];
    uint32_t W[64];

    // Copy state into S
    for (i = 0; i < 8; i++)
    {
        S[i] = Context->state[i];
    }

    // Copy the state into 512-bits into W[0..15]
    for (i = 0; i < 16; i++)
    {
        LOAD32H(W[i], Buffer + (4*i));
    }

    // Fill W[16..63]
    for (i = 16; i < 64; i++)
    {
        W[i] = Gamma1(W[i-2]) + W[i-7] + Gamma0(W[i-15]) + W[i-16];
    }

    // Compress
    for (i = 0; i < 64; i++)
    {
        Sha256Round(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i);
        t = S[7];
        S[7] = S[6];
        S[6] = S[5];
        S[5] = S[4];
        S[4] = S[3];
        S[3] = S[2];
        S[2] = S[1];
        S[1] = S[0];
        S[0] = t;
    }

    // Feedback
    for (i = 0; i < 8; i++)
    {
        Context->state[i] = Context->state[i] + S[i];
    }
    
    return;
}

void Sha256Initialise(OUT Sha256Context *Context)
{
    Context->curlen = 0;
    Context->length = 0;
    Context->state[0] = 0x6A09E667UL;
    Context->state[1] = 0xBB67AE85UL;
    Context->state[2] = 0x3C6EF372UL;
    Context->state[3] = 0xA54FF53AUL;
    Context->state[4] = 0x510E527FUL;
    Context->state[5] = 0x9B05688CUL;
    Context->state[6] = 0x1F83D9ABUL;
    Context->state[7] = 0x5BE0CD19UL;
    
    return;
}

void Sha256Update(INOUT Sha256Context *Context, IN void const *Buffer, IN uint32_t BufferSize)
{
    uint32_t n;

    if (Context->curlen > sizeof(Context->buf))
    {
       return;
    }

    while (BufferSize > 0)
    {
        if (Context->curlen == 0 && BufferSize >= BLOCK_SIZE)
        {
           TransformFunction(Context, (uint8_t*)Buffer);
           Context->length += BLOCK_SIZE * 8;
           Buffer = (uint8_t*)Buffer + BLOCK_SIZE;
           BufferSize -= BLOCK_SIZE;
        }
        else
        {
           n = MIN(BufferSize, (BLOCK_SIZE - Context->curlen));
           memcpy(Context->buf + Context->curlen, Buffer, (size_t)n);
           Context->curlen += n;
           Buffer = (uint8_t*)Buffer + n;
           BufferSize -= n;
           if (Context->curlen == BLOCK_SIZE)
           {
              TransformFunction(Context, Context->buf);
              Context->length += 8*BLOCK_SIZE;
              Context->curlen = 0;
           }
       }
    }
    
    return;
}

void Sha256Finalise(INOUT Sha256Context *Context, OUT SHA256_HASH *Digest)
{
    int i;

    if (Context->curlen >= sizeof(Context->buf))
    {
       return;
    }

    // Increase the length of the message
    Context->length += Context->curlen * 8;

    // Append the '1' bit
    Context->buf[Context->curlen++] = (uint8_t)0x80;

    // if the length is currently above 56 bytes we append zeros
    // then compress.  Then we can fall back to padding zeros and length
    // encoding like normal.
    if (Context->curlen > 56)
    {
        while (Context->curlen < 64)
        {
            Context->buf[Context->curlen++] = (uint8_t)0;
        }
        TransformFunction(Context, Context->buf);
        Context->curlen = 0;
    }

    // Pad up to 56 bytes of zeroes
    while (Context->curlen < 56)
    {
        Context->buf[Context->curlen++] = (uint8_t)0;
    }

    // Store length
    STORE64H(Context->length, Context->buf+56);
    TransformFunction(Context, Context->buf);

    // Copy output
    for (i = 0; i < 8; i++)
    {
        STORE32H(Context->state[i], Digest->bytes+(4*i));
    }
    
    return;
}

void Sha256Calculate(IN void const *Buffer, IN uint32_t BufferSize, INOUT char *pcDigest, IN int DigestLen)
{
    int i =0;
    int iOffset =0;
    SHA256_HASH Digest;
    Sha256Context context;
    
    memset(&Digest, 0, sizeof(Digest));
    memset(&context, 0, sizeof(context));
    
    Sha256Initialise(&context);
    Sha256Update(&context, Buffer, BufferSize);
    Sha256Finalise(&context, &Digest);

    for(i = 0; i < sizeof(Digest); i++)
    {
        snprintf(pcDigest + iOffset, DigestLen - iOffset, "%2.2x", Digest.bytes[i]);
        iOffset = strlen(pcDigest);
    }

    return;
}

Green_CryptLib_Sha256.h

#ifndef _GREEN_CRYPTO_SHA256_H
#define _GREEN_CRYPTO_SHA256_H

#include <stdint.h>
#include <stdio.h>
#include "errcode.h"

typedef struct
{
    uint64_t length;
    uint32_t state[8];
    uint32_t curlen;
    uint8_t buf[64];
} Sha256Context;

#define SHA256_HASH_SIZE           ( 256 / 8 )

typedef struct
{
    uint8_t bytes [SHA256_HASH_SIZE];
} SHA256_HASH;

void Sha256Initialise(OUT Sha256Context *      Context);
void Sha256Update(INOUT Sha256Context *      Context, IN void const *Buffer, IN uint32_t BufferSize);
void Sha256Finalise    (  INOUT  Sha256Context *Context, OUT SHA256_HASH *Digest);
void Sha256Calculate(IN void const *Buffer, IN uint32_t BufferSize, INOUT char *pcDigest, IN int DigestLen);

#ifdef __cplusplus
    }
#endif
    
#endif // _GREEN_CRYPTO_SHA256_H
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值