Chinaunix首页 | 论坛 | 博客
  • 博客访问: 694801
  • 博文数量: 85
  • 博客积分: 1797
  • 博客等级: 上尉
  • 技术积分: 1238
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-02 08:53
个人简介

职位:技术总监 1、精通c++(linux平台、vc++Mfc、qt)、java、php、unity3d,略懂python 2、用c++开发过嵌入式产品,用c++开发过大型银行运维产品 3、用java开发大型银行运维产品,学校教务系统 4、用php开发进销存系统(在销售中),用php开发淘宝小程序 5、用unity3d开发衣柜设计软件,在运营中

文章分类

全部博文(85)

分类: 网络与安全

2011-08-27 00:21:10

 

 

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;

}


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