md5、sha1实例
2015-12-30 16:07
239 查看
md5、sha1都是一种hash算法,对于任意长度的数据,经过运算之后得到结果长度都是固定的,并且是不可逆的,也就是说在不知道原始数据的情况下破解是非常困难的,通常用于密码的加密存储、数字签名、文件完整性校验等等,代码如下:
注:md5的计算结果长度是128bit,也就是16字节。
在Linux上对文件的加密计算可以使用md5sum、sha1sum命令的。
注意对于文本文件的计算结果可能和在代码中直接输入字符串计算得到结果不一样,那是因为文本文件末尾带了回车符,可以使用hexdump命令看一下。
注意,编译的时候需要链接openssl库,使用下面的命令:
gcc -Wall -o test sha1.c -lcrypto -lssl
#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
相关文章推荐
- 论文编辑细节
- unity制作2d游戏(捕鱼达人)优化
- 阶跃函数和符号函数的傅里叶变换
- apache+mod_wsgi应用WSGI
- 开源动画框架Facebook的Pop
- kafka java 实现消息队列demo
- 从集合中找出满足条件的元素,apache的CollectionUtils
- web.xml最简模板
- Azure Redis Cache作为ASP.NET Session状态提供程序
- 简单的前端验证码
- sailsjs
- SSH2框架搭建
- 使用GridView表格显示多张图片
- LATEX错误「Unknown graphics extension: .eps」
- 命令 与 bash shell脚本
- Hadoop基础教程之搭建开发环境及编写Hello World
- 详解Activity的四种启动模式
- jmeter
- openlayer常见问题
- 序列化(Serialization)概念