Chinaunix首页 | 论坛 | 博客
  • 博客访问: 308428
  • 博文数量: 27
  • 博客积分: 758
  • 博客等级: 军士长
  • 技术积分: 369
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 23:10
文章分类

全部博文(27)

文章存档

2014年(1)

2012年(26)

我的朋友

分类: 网络与安全

2012-11-19 22:46:49



生成私钥:
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==-1 ){
  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. }


阅读(18104) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

wf8902022014-07-14 16:10:17

非常感谢