适合单片机的MD5源码
时间: 2023-08-05 08:05:00 浏览: 37
以下是适用于单片机的MD5算法的C语言源代码示例:
```
#include <stdint.h>
#define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c))))
void md5_transform(uint32_t state[4], const uint8_t block[64]) {
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], x[16];
for (int i = 0; i < 16; i++) {
x[i] = (uint32_t)block[i * 4] |
((uint32_t)block[i * 4 + 1] << 8) |
((uint32_t)block[i * 4 + 2] << 16) |
((uint32_t)block[i * 4 + 3] << 24);
}
// Round 1
for (int i = 0; i < 16; i++) {
uint32_t f = (b & c) | ((~b) & d);
int g = i;
uint32_t tmp = d;
d = c;
c = b;
b = b + LEFTROTATE((a + f + x[g]), 7);
a = tmp;
}
// Round 2
for (int i = 0; i < 16; i++) {
uint32_t f = (d & b) | ((~d) & c);
int g = (5 * i + 1) % 16;
uint32_t tmp = d;
d = c;
c = b;
b = b + LEFTROTATE((a + f + x[g] + 0x5A827999), 12);
a = tmp;
}
// Round 3
for (int i = 0; i < 16; i++) {
uint32_t f = b ^ c ^ d;
int g = (3 * i + 5) % 16;
uint32_t tmp = d;
d = c;
c = b;
b = b + LEFTROTATE((a + f + x[g] + 0x6ED9EBA1), 17);
a = tmp;
}
// Round 4
for (int i = 0; i < 16; i++) {
uint32_t f = c ^ (b | (~d));
int g = (7 * i) % 16;
uint32_t tmp = d;
d = c;
c = b;
b = b + LEFTROTATE((a + f + x[g] + 0x8F1BBCDC), 22);
a = tmp;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
void md5(const uint8_t *initial_msg, size_t initial_len, uint8_t *digest) {
// These vars will contain the hash
uint32_t h0, h1, h2, h3;
// Initialize variables - simple count in nibbles:
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
// Pre-processing:
uint8_t *msg = NULL;
size_t new_len, offset;
for (new_len = initial_len + 1; new_len % 64 != 56; new_len++);
msg = (uint8_t*)calloc(new_len + 8, 1);
memcpy(msg, initial_msg, initial_len);
msg[initial_len] = 0x80; // append the "1" bit; most significant bit is "first"
for (offset = 0; offset < 8; offset++) {
msg[new_len + offset] = initial_len >> (offset * 8); // append length in bits
}
// Process the message in successive 512-bit chunks:
for (int i = 0; i < new_len; i += 64) {
md5_transform((uint32_t*)(msg + i), h0, h1, h2, h3);
}
// Produce the final hash value (little-endian):
uint8_t buf[16];
memcpy(buf, &h0, 4);
memcpy(buf + 4, &h1, 4);
memcpy(buf + 8, &h2, 4);
memcpy(buf + 12, &h3, 4);
memcpy(digest, buf, 16);
free(msg);
}
```
这段代码实现了MD5算法的核心部分,可以在单片机上使用。需要注意的是,这段代码只提供了算法的核心部分,需要结合具体的应用场景和需求进行修改和补充。