linux下使用openssl 加解密
2016-01-19 10:13
483 查看
先附上Linux下安装配置openssl的过程
/article/9296448.html
安装完成后,产生RSA公钥和私钥
输入openssl进入程序
OpenSSL> genrsa -out test.key 1024
产生了1024bit的私钥,然后根据该私钥产生公钥
rsa -in test.key -pubout -out rsatest_pub.key
创建rsatest.c代码如下
vim rsatest.c
检验结果,gcc rsatest.c -o hello -lssl
最后-lssl 是为了引入共享库ssl
/article/9296448.html
安装完成后,产生RSA公钥和私钥
输入openssl进入程序
OpenSSL> genrsa -out test.key 1024
产生了1024bit的私钥,然后根据该私钥产生公钥
rsa -in test.key -pubout -out rsatest_pub.key
创建rsatest.c代码如下
vim rsatest.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<openssl/rsa.h> #include<openssl/pem.h> #include<openssl/err.h> #define OPENSSLKEY "test.key" #define PUBLICKEY "test_pub.key" #define BUFFSIZE 1024 char* my_encrypt(char *str,char *path_key);//加密 char* my_decrypt(char *str,char *path_key);//解密 int main(void){ char *source="i like dancing !"; char *ptr_en,*ptr_de; printf("source is :%s\n",source); ptr_en=my_encrypt(source,PUBLICKEY); printf("after encrypt:%s\n",ptr_en); ptr_de=my_decrypt(ptr_en,OPENSSLKEY); printf("after decrypt:%s\n",ptr_de); if(ptr_en!=NULL){ free(ptr_en); } if(ptr_de!=NULL){ free(ptr_de); } return 0; } char *my_encrypt(char *str,char *path_key){ char *p_en; RSA *p_rsa; FILE *file; int flen,rsa_len; if((file=fopen(path_key,"r"))==NULL){ perror("open key file error"); return NULL; } if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){ ERR_print_errors_fp(stdout); return NULL; } flen=strlen(str); rsa_len=RSA_size(p_rsa); p_en=(unsigned char *)malloc(rsa_len+1); memset(p_en,0,rsa_len+1); if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){ return NULL; } RSA_free(p_rsa); fclose(file); return p_en; } char *my_decrypt(char *str,char *path_key){ char *p_de; RSA *p_rsa; FILE *file; int rsa_len; if((file=fopen(path_key,"r"))==NULL){ perror("open key file error"); return NULL; } if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){ ERR_print_errors_fp(stdout); return NULL; } rsa_len=RSA_size(p_rsa); p_de=(unsigned char *)malloc(rsa_len+1); memset(p_de,0,rsa_len+1); if(RSA_private_decrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING)<0){ return NULL; } RSA_free(p_rsa); fclose(file); return p_de; }
检验结果,gcc rsatest.c -o hello -lssl
最后-lssl 是为了引入共享库ssl
相关文章推荐
- Linux下FreeTDS使用及问题总结
- centos7.2怎样连接WiFi?
- Linux下防火墙开启相关端口及查看已开启端口
- Java开发必会的Linux命令
- linux 使用笔记3
- linux 使用笔记2
- Linux下chkconfig命令详解
- linux 使用笔记1
- linux下开发c第一弹--相关环境需求
- linux下XAMP集成开发环境搭建流程总结
- 与 Linux 一起学习:物理模拟
- Centos下:/usr/bin/ld: cannot find -lXext
- Linux学习27_每天一个linux命令(28):tar命令
- linux分区模式之GPT分区
- manjao linux下玩转arduino
- 哪个文件系统最适合你的 Linux 系统?
- (实用)拿到一个新的阿里云64位centOS系统后,手把手教你编译安装PHP生产环境(lnmp)
- linux locale属性的设置
- 2015年 Linux 世界的十个大事件
- linux 内核 编译 makefile menuconfig过程讲解