写一段sha256,c语言,输入输出都是16进制的程序
时间: 2023-07-16 11:13:16 浏览: 45
以下是一个简单的 SHA256 实现的 C 语言代码,输入和输出都是 16 进制格式:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#define SHR(x, n) ((x) >> (n))
#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define EP1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define SIG0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))
#define SIG1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))
#define BLOCK_SIZE 64
#define WORD_SIZE 4
#define HASH_SIZE 8
uint32_t h[HASH_SIZE] = {
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
};
void sha256_transform(uint32_t *state, const uint8_t *data)
{
uint32_t w[64];
uint32_t a, b, c, d, e, f, g, h, i, j, t1, t2;
for (i = 0, j = 0; i < 16; ++i, j += WORD_SIZE) {
w[i] = ((uint32_t)data[j] << 24) | ((uint32_t)data[j + 1] << 16) |
((uint32_t)data[j + 2] << 8) | ((uint32_t)data[j + 3]);
}
for (; i < 64; ++i) {
w[i] = SIG1(w[i - 2]) + w[i - 7] + SIG0(w[i - 15]) + w[i - 16];
}
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
for (i = 0; i < 64; ++i) {
t1 = h + EP1(e) + CH(e, f, g) + sha256_k[i] + w[i];
t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
void sha256(const uint8_t *data, size_t len, uint8_t *hash)
{
uint8_t block[BLOCK_SIZE];
uint32_t state[HASH_SIZE];
uint32_t i, j;
state[0] = 0x6a09e667;
state[1] = 0xbb67ae85;
state[2] = 0x3c6ef372;
state[3] = 0xa54ff53a;
state[4] = 0x510e527f;
state[5] = 0x9b05688c;
state[6] = 0x1f83d9ab;
state[7] = 0x5be0cd19;
for (i = 0; i < len / BLOCK_SIZE; ++i) {
memcpy(block, data + i * BLOCK_SIZE, BLOCK_SIZE);
sha256_transform(state, block);
}
j = i * BLOCK_SIZE;
memset(block, 0, BLOCK_SIZE);
memcpy(block, data + j, len - j);
block[len - j] = 0x80;
if (len - j > BLOCK_SIZE - 9) {
sha256_transform(state, block);
memset(block, 0, BLOCK_SIZE);
}
block[BLOCK_SIZE - 1] = len * 8;
sha256_transform(state, block);
for (i = 0, j = 0; i < HASH_SIZE; ++i, j += WORD_SIZE) {
hash[j] = (state[i] >> 24) & 0xff;
hash[j + 1] = (state[i] >> 16) & 0xff;
hash[j + 2] = (state[i] >> 8) & 0xff;
hash[j + 3] = state[i] & 0xff;
}
}
int main()
{
uint8_t data[] = {0xde, 0xad, 0xbe, 0xef};
uint8_t hash[32];
sha256(data, sizeof(data), hash);
printf("Input: 0x");
for (int i = 0; i < sizeof(data); i++) {
printf("%02x", data[i]);
}
printf("\nOutput: 0x");
for (int i = 0; i < sizeof(hash); i++) {
printf("%02x", hash[i]);
}
printf("\n");
return 0;
}
```
这个程序将 0xdeadbeef 作为输入,计算其 SHA256 哈希值,并以 16 进制格式输出。