OpenSSL公钥私钥加密解密程序


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

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


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


  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <openssl/pem.h>
  5. #include <openssl/rsa.h>

  6. int main()
  7. {
  8.     // 原始明文
  9.     char plain[256]="测试测试,hello123";

  10.     // 用来存放密文
  11.     char encrypted[1024];

  12.     // 用来存放解密后的明文
  13.     char decrypted[1024];

  14.     // 公钥和私钥文件
  15.     const char* pub_key="public.pem";
  16.     const char* priv_key="private.pem";

  17.     // -------------------------------------------------------
  18.     // 利用公钥加密明文的过程
  19.     // -------------------------------------------------------

  20.     // 打开公钥文件
  21.     FILE* pub_fp=fopen(pub_key,"r");
  22.     if(pub_fp==NULL){
  23.         printf("failed to open pub_key file %s!\n", pub_key);
  24.         return -1;
  25.     }

  26.     // 从文件中读取公钥
  27.     RSA* rsa1=PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL);
  28.     if(rsa1==NULL){
  29.         printf("unable to read public key!\n");
  30.         return -1; 
  31.     }
  32.     
  33.     if(strlen(plain)>=RSA_size(rsa1)-41){
  34.         printf("failed to encrypt\n");
  35.         return -1;
  36.     }
  37.     fclose(pub_fp);

  38.     // 用公钥加密
  39.     int len=RSA_public_encrypt(strlen(plain), plain, encrypted, rsa1, RSA_PKCS1_PADDING);
  40.     if(len==-){
  41.         printf("failed to encrypt\n");
  42.         return -1;
  43.     }
  44.     
  45.     // 输出加密后的密文
  46.     FILE* fp=fopen("out.txt","w");
  47.     if(fp){
  48.         fwrite(encrypted,len,1,fp);
  49.         fclose(fp);
  50.     }
  51.     // -------------------------------------------------------
  52.     // 利用私钥解密密文的过程
  53.     // -------------------------------------------------------
  54.     // 打开私钥文件
  55.     FILE* priv_fp=fopen(priv_key,"r");
  56.     if(priv_fp==NULL){
  57.         printf("failed to open priv_key file %s!\n", priv_key);
  58.         return -1;
  59.     }
  60.    

  61.     // 从文件中读取私钥
  62.     RSA *rsa2 = PEM_read_RSAPrivateKey(priv_fp, NULL, NULL, NULL);
  63.     if(rsa2==NULL){
  64.         printf("unable to read private key!\n");
  65.         return -1; 
  66.     }
  67.     
  68.     // 用私钥解密
  69.     len=RSA_private_decrypt(len, encrypted, decrypted, rsa2, RSA_PKCS1_PADDING);
  70.     if(len==-1){
  71.         printf("failed to decrypt!\n");
  72.         return -1;
  73.     }
  74.     fclose(priv_fp);


  75.     // 输出解密后的明文
  76.     decrypted[len]=0;
  77.     printf("%s\n",decrypted);


  78. }
http://blog.chinaunix.net/uid-23686726-id-3413979.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值