您的位置:首页 > 其它

md5、sha1实例

2015-12-30 16:07 239 查看
md5、sha1都是一种hash算法,对于任意长度的数据,经过运算之后得到结果长度都是固定的,并且是不可逆的,也就是说在不知道原始数据的情况下破解是非常困难的,通常用于密码的加密存储、数字签名、文件完整性校验等等,代码如下:
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>

void bufdump(char *buf, int len)
{
while (len--) {
printf("%02x", *(unsigned char *)buf++);
}
printf("\n");
}

int main(void)
{
MD5_CTX c;
char md[16];
char *data = "hello";

MD5_Init(&c);
MD5_Update(&c, data, strlen(data));
MD5_Final(md, &c);

bufdump(md, sizeof(md));

return 0;
}

注:md5的计算结果长度是128bit,也就是16字节。

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

void bufdump(char *buf, int len)
{
while (len--) {
printf("%02x", *(unsigned char *)buf++);
}
printf("\n");
}

int main(void)
{
SHA_CTX c;
char md[20];
char *data = "hello";

SHA1_Init(&c);
SHA1_Update(&c, data, strlen(data));
SHA1_Final(md, &c);

bufdump(md, sizeof(md));

return 0;
}
上面代码是160bit的sha1计算,除此之外openssl还提供了224bit(SHA224)、256bit(SHA256)、384bit(SHA384)和512bit(SHA512)。

在Linux上对文件的加密计算可以使用md5sum、sha1sum命令的。

注意对于文本文件的计算结果可能和在代码中直接输入字符串计算得到结果不一样,那是因为文本文件末尾带了回车符,可以使用hexdump命令看一下。

注意,编译的时候需要链接openssl库,使用下面的命令:

gcc -Wall -o test sha1.c -lcrypto -lssl
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: