生成一个md5加密的C语言函数
时间: 2024-05-06 19:19:59 浏览: 19
以下是一个生成MD5加密的C语言函数的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
void md5_hash(char *input, char *output) {
MD5_CTX ctx;
unsigned char digest[MD5_DIGEST_LENGTH];
MD5_Init(&ctx);
MD5_Update(&ctx, input, strlen(input));
MD5_Final(digest, &ctx);
for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
sprintf(&output[i * 2], "%02x", (unsigned int)digest[i]);
}
}
int main() {
char input[] = "hello world";
char output[MD5_DIGEST_LENGTH * 2 + 1];
md5_hash(input, output);
printf("MD5 hash of '%s': %s\n", input, output);
return 0;
}
```
该函数使用OpenSSL库中的MD5函数来计算输入字符串的MD5哈希值。函数接受两个参数:输入字符串和输出字符串。输出字符串必须具有足够的空间来存储MD5哈希值,其大小为MD5_DIGEST_LENGTH * 2 + 1。函数通过循环遍历MD5哈希值数组并将其转换为十六进制字符串来生成输出字符串。在上面的示例中,我们使用“hello world”字符串作为输入字符串,并打印输出的MD5哈希值。