OpenSSL公钥私钥加密解密程序

来源:互联网 发布:泸州2017年网络春晚 编辑:程序博客网 时间:2024/04/28 01:15

生成私钥:
openssl genrsa -out private.key 2048

生成公钥:
openssl rsa -in privkey.pem -pubout > public.pem


C代码如下所示。
在Linux下的编译:gcc test.c -lcrypto -o test

#include <stdlib.h>#include <stdio.h>#include <string.h>#include "openssl/pem.h"#include "openssl/rsa.h"int main(){// 原始明文char *plain="测试测试,hello123";// 用来存放密文char *encrypted = new char[1024];// 用来存放解密后的明文char *decrypted = new char[1024];// 公钥和私钥文件const char* pub_key="public.pem";const char* priv_key="private.pem";// -------------------------------------------------------// 利用公钥加密明文的过程// -------------------------------------------------------// 打开公钥文件FILE* pub_fp=fopen(pub_key,"r");if(pub_fp==NULL){printf("failed to open pub_key file %s!\n", pub_key);return -1;}// 从文件中读取公钥RSA* rsa1=PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL);if(rsa1==NULL){printf("unable to read public key!\n");return -1; }if(strlen(plain)>=RSA_size(rsa1)-41){printf("failed to encrypt\n");return -1;}fclose(pub_fp);// 用公钥加密int len=RSA_public_encrypt(strlen(plain),(const unsigned char*)plain, (unsigned char*)encrypted, rsa1, RSA_PKCS1_PADDING);if(len==-1 ){printf("failed to encrypt\n");return -1;}// 输出加密后的密文FILE* fp=fopen("out.txt","w");if(fp){fwrite(encrypted,len,1,fp);fclose(fp);}// -------------------------------------------------------// 利用私钥解密密文的过程// -------------------------------------------------------// 打开私钥文件FILE* priv_fp=fopen(priv_key,"r");if(priv_fp==NULL){printf("failed to open priv_key file %s!\n", priv_key);return -1;}// 从文件中读取私钥 RSA *rsa2 = PEM_read_RSAPrivateKey(priv_fp, NULL, NULL, NULL);if(rsa2==NULL){ printf("unable to read private key!\n");return -1; }// 用私钥解密len=RSA_private_decrypt(len, (const unsigned char*)encrypted, (unsigned char*)decrypted, rsa2, RSA_PKCS1_PADDING);if(len==-1){printf("failed to decrypt!\n");return -1;}fclose(priv_fp);// 输出解密后的明文decrypted[len]=0;printf("%s\n",decrypted);}


注意这里要设置包含路径,导入需要的头文件才可以。

不过还是有个编译不过去的问题,在解决。。。。。

>opensslTest.obj : error LNK2019: unresolved external symbol _RSA_private_decrypt referenced in function _main
1>opensslTest.obj : error LNK2019: unresolved external symbol _PEM_read_RSAPrivateKey referenced in function _main
1>opensslTest.obj : error LNK2019: unresolved external symbol _RSA_public_encrypt referenced in function _main
1>opensslTest.obj : error LNK2019: unresolved external symbol _RSA_size referenced in function _main
1>opensslTest.obj : error LNK2019: unresolved external symbol _PEM_read_RSA_PUBKEY referenced in function _main
1>D:\Test\opensslTest\Debug\opensslTest.exe : fatal error LNK1120: 5 unresolved externals

原创粉丝点击