OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。
要使用openssl,首先安装openssl库:
apt-get install openssl libssl-dev libssl-doc libcurl4-openssl-dev
源代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/hmac.h>
#include<openssl/md5.h>
int output(char *p, unsigned char* pwd, int len) {
int i;
printf("%s", p);
for (i = 0; i < len; i++) {
printf("%x", pwd[i]);
}
printf("\n");
return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "%s <original password><salt password><hash length>\n",
argv[0]);
return 1;
}
int i, hashLen;
unsigned char *originalPwd;
unsigned char *saltPwd;
originalPwd = (unsigned char *) malloc(strlen(argv[1]) + 1); //argv[1]是初始密码
saltPwd = (unsigned char *) malloc(strlen(argv[2]) + 1); //argv[2]是加盐:是指通过在密码任意固定位置插入特定的字符串,让散列后的结果和使用原始密码的散列结果不相符
strcpy(originalPwd, argv[1]);
strcpy(saltPwd, argv[2]);
hashLen = atoi(argv[3]);//设置加密密码的长度
unsigned char encryptPwd[hashLen];
printf("Before add salt into the original password:\n");
MD5((unsigned char *) originalPwd, strlen(originalPwd), encryptPwd);//使用MD5算法对密码进行加密(不加盐),并输出加密前后密码
output("Original Password = ", (unsigned char *) originalPwd,
strlen(originalPwd));
output("Encrypt Password = ", (unsigned char *) encryptPwd, hashLen);
printf("\nAfter add salt into the original password:\n");
memset(encryptPwd, 0, sizeof(encryptPwd));
strcat(originalPwd, saltPwd);
MD5((unsigned char *) originalPwd, strlen(originalPwd), encryptPwd);//使用MD5算法对密码进行加密(加盐),并输出加密前后密码
output("Original Password = ", (unsigned char *) originalPwd,
strlen(originalPwd));
output("Encrypt Password = ", (unsigned char *) encryptPwd, hashLen);
return 0;
}
使用openssl命令行构建CA及证书:http://www.linuxdiyf.com/linux/15338.html
建立你自己的CA服务:OpenSSL命令行CA操作快速指南:http://www.linuxdiyf.com/linux/12152.html
Ubuntu编译环境构建(openssl):http://www.linuxdiyf.com/linux/13751.html
Linux下使用OpenSSL生成证书:http://www.linuxdiyf.com/linux/11951.html
Linux下OpenSSL安装图文详解:http://www.linuxdiyf.com/linux/8744.html