您的位置:首页 > 运维架构

OpenSSL公钥私钥加密解密程序

2013-10-10 17:49 337 查看
生成私钥:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: