Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1695808
  • 博文数量: 584
  • 博客积分: 13857
  • 博客等级: 上将
  • 技术积分: 11883
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-16 09:34

分类: WINDOWS

2011-05-05 09:27:52

[转]OPENSSL RSA 加密 解密问题

1 C

加密:

  1. /*
  2. gcc -o rsa-encrypt rsa-encrypt.c -lcrypto
  3. */
  4. #include <openssl/rsa.h>
  5. #include <openssl/err.h>

  6. #define MODULUS "C8FBCF21"
  7. #define PUBLIC_EXPONENT RSA_F4
  8. #define PRIVATE_EXPONENT "97B55D7D"

  9. int main()
  10. {
  11.     int ret, flen;
  12.      BIGNUM *bnn, *bne, *bnd;
  13.     unsigned char *in = "abc";
  14.     unsigned char *out;

  15.      bnn = BN_new();
  16.      bne = BN_new();
  17.      bnd = BN_new();
  18.      BN_hex2bn(&bnn, MODULUS);
  19.      BN_set_word(bne, PUBLIC_EXPONENT);
  20.      BN_hex2bn(&bnd, PRIVATE_EXPONENT);

  21.      RSA *r = RSA_new();
  22.      r->n = bnn;
  23.      r->e = bne;
  24.      r->d = bnd;
  25.      RSA_print_fp(stdout, r, 5);

  26.      flen = RSA_size(r);// - 11;

  27.      out = (char *)malloc(flen);
  28.      bzero(out, flen);
  29.     //memset(out, 0, flen);


  30.     printf("Begin encrypt...\n");
  31.      ret = RSA_public_encrypt(flen, in, out, r, RSA_NO_PADDING);
  32.     if (ret < 0)
  33.     {
  34.         printf("Encrypt failed!\n");
  35.         return 1;
  36.     }

  37.     printf("Size:%d\n", ret);
  38.     printf("ClearText:%s\n", in);
  39.     printf("CipherText(Hex):\n");
  40.     int i;
  41.     for (i=0; i<ret; i++)
  42.     {
  43.         printf("0x%02x, ", *out);
  44.          out++;
  45.     }
  46.     printf("\n");

  47.     //free(out);

  48.      RSA_free(r);
  49.     return 0;
  50. }





解密:

  1. /*
  2. gcc -o rsa-decrypt rsa-decrypt.c -lcrypto
  3. */
  4. #include <openssl/rsa.h>

  5. #define MODULUS "C8FBCF21"
  6. #define PUBLIC_EXPONENT RSA_F4
  7. #define PRIVATE_EXPONENT "97B55D7D"

  8. int main()
  9. {
  10.     int ret, flen;
  11.      BIGNUM *bnn, *bne, *bnd;
  12.     unsigned char in[] = {0x51, 0xc2, 0x8d, 0xc6};
  13.     unsigned char *out;

  14.      bnn = BN_new();
  15.      bne = BN_new();
  16.      bnd = BN_new();
  17.      BN_hex2bn(&bnn, MODULUS);
  18.      BN_set_word(bne, PUBLIC_EXPONENT);
  19.      BN_hex2bn(&bnd, PRIVATE_EXPONENT);

  20.      RSA *r = RSA_new();
  21.      r->n = bnn;
  22.      r->e = bne;
  23.      r->d = bnd;
  24.      RSA_print_fp(stdout, r, 5);

  25.      flen = RSA_size(r);
  26.      out = (unsigned char *)malloc(flen);
  27.      bzero(out, flen);

  28.     printf("Begin decrypt...\n");
  29.      ret = RSA_private_decrypt(sizeof(in), in, out, r, RSA_NO_PADDING);
  30.     if (ret < 0)
  31.     {
  32.         printf("Decrypt failed!\n");
  33.         return 1;
  34.     }

  35.     printf("Size:%d\n", ret);
  36.     printf("ClearText:%s\n", out);

  37.     free(out);
  38.      RSA_free(r);
  39.     return 0;
  40. }


2

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