2011年6月14日星期二

  用OpenSSL实现RSA算法加密(转)

 1: #include <openssl/err.h>
 2:  
 3: #define MODULUS "C8FBCF21"
 4: #define PUBLIC_EXPONENT RSA_F4
 5: #define PRIVATE_EXPONENT "97B55D7D"
 6:  
 7: int main()
 8: {
 9:  int ret, flen;
 10: BIGNUM *bnn, *bne, *bnd;
 11: unsigned char *in = "abc";
 12: unsigned char *out;
 13:  
 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:  
 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:  
 27: flen = RSA_size(r);// - 11;
 28:  out = (char *)malloc(flen);
 29: bzero(out, flen);
 30:  //memset(out, 0, flen);
 31:  
 32: printf("Begin encrypt... ");
 33: ret = RSA_private_encrypt(flen, in, out, r, RSA_NO_PADDING);
 34:  if (ret < 0)
 35: {
 36: printf("Encrypt failed! ");
 37:  return 1;
 38: }
 39:  
 40: printf("Size:%d ", ret);
 41: printf("ClearText:%s ", in);
 42: printf("CipherText(Hex):");
 43:  int i;
 44:  for (i=0; i<ret; i++)
 45: {
 46: printf("0x%02x, ", *out);
 47:  out++;
 48: }
 49: printf(" ");
 50:  
 51:  //free(out);
 52: RSA_free(r);
 53:  return 0;
 54: }
 1: #include <openssl/err.h>
 2: 
 3: #define MODULUS "C8FBCF21"
 4: #define PUBLIC_EXPONENT RSA_F4
 5: #define PRIVATE_EXPONENT "97B55D7D"
 6: 
 7: int main()
 8: {
 9: int ret, flen;
 10: BIGNUM *bnn, *bne, *bnd;
 11: unsigned char *in = "abc";
 12: unsigned char *out;
 13: 
 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: 
 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: 
 27: flen = RSA_size(r);// - 11;
 28: out = (char *)malloc(flen);
 29: bzero(out, flen);
 30: //memset(out, 0, flen);
 31: 
 32: printf("Begin encrypt... ");
 33: ret = RSA_private_encrypt(flen, in, out, r, RSA_NO_PADDING);
 34: if (ret < 0)
 35: {
 36: printf("Encrypt failed! ");
 37: return 1;
 38: }
 39: 
 40: printf("Size:%d ", ret);
 41: printf("ClearText:%s ", in);
 42: printf("CipherText(Hex):");
 43: int i;
 44: for (i=0; i<ret; i++)
 45: {
 46: printf("0x%02x, ", *out);
 47: out++;
 48: }
 49: printf(" ");
 50: 
 51: //free(out);
 52: RSA_free(r);
 53: return 0;
 54: }

没有评论:

发表评论