Chinaunix首页 | 论坛 | 博客
  • 博客访问: 646918
  • 博文数量: 329
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 693
  • 用 户 组: 普通用户
  • 注册时间: 2015-01-05 23:37
个人简介

Do not panic!

文章存档

2021年(1)

2018年(3)

2017年(7)

2016年(98)

2015年(220)

我的朋友

分类: 网络与安全

2015-07-05 00:22:26

原文地址:rsa加解密 作者:ehyyngp

 

 

int test_rsa_encry()
{
#define RSA_KEY_FILE "rsakey.txt"
    // > openssl genrsa -out rsakey.txt 1024


    RSA* key;
    char msg[]="i, i have no data to enc";
    char msg2[256];
    char msg3[256];
    int r;
    
    //SSL_library_init();


    //SSL_load_error_strings();


    //OpenSSL_add_all_algorithms();


    
    //key = RSA_new();


    

    puts("genrsa...(maybe a few seconds)");
    key = RSA_generate_key(1024, 65537, NULL, NULL);
/*
    //测试写私钥
   FILE *fp = fopen("private.txt", "w");
   if (!PEM_write_RSAPrivateKey(fp, key, NULL, NULL, 0, 0, NULL))
   {
       
   }

   FILE *fppublic = fopen("public.txt", "w");
   if (!PEM_write_RSAPublicKey(fppublic, key))
   {
       
   }
*/

   
   //der格式:


   //公钥


   unsigned char der[5000]={0};
   int len=0;
    len = i2d_RSAPublicKey(key,NULL);
   len = i2d_RSAPublicKey(key, (unsigned char**)&der);
   //得到私钥 保存


   len = i2d_RSAPrivateKey(key, (unsigned char**)&der);

   FILE *fpder1 = fopen("publicKey-der.txt", "wb");

    fwrite(der, 1, len, fpder1);
    fclose(fpder1);

    
    FILE *fpder2 = fopen("privateKey-der.txt", "wb");
    
    fwrite(der, 1, len, fpder2);
    fclose(fpder2);

    puts("ok");
    
    r = RSA_public_encrypt(strlen(msg), (unsigned char *)msg, (unsigned char *)msg2,
        key, RSA_PKCS1_PADDING); // or RSA_PKCS1_OAEP_PADDING



    FILE *fp1 = fopen("msg2.txt", "w");
    fwrite(msg2,sizeof(unsigned char),r, fp1);
    printf("\nmsg2:\n");

    
    for(int i=0; i<r; i++)
    {
        printf("%02x", (unsigned char)msg2[i]);
    }

    if (!r)
        puts("error in enc");
    

    r = RSA_private_decrypt(r, (unsigned char *)msg2, (unsigned char *)msg3,
        key, RSA_PKCS1_PADDING);
    if (!r)
        puts("error in dec");
    
    if (memcmp(msg, msg3, strlen(msg)))
        puts("ERROR! text2 != text");
    else
    {
        msg3[strlen(msg)] = 0;
        printf("\n解密后的明文:%s", msg3);
    }
    
    puts("\nis there errs? no? ok!");
    
    RSA_free(key);
    
    return 0;

}


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