在openssl使用rsa进行加解密

加密:

/*
gcc -o rsa-encrypt rsa-encrypt.c -lcrypto
*/
#include
#include

#define MODULUS "C8FBCF21"
#define PUBLIC_EXPONENT RSA_F4
#define PRIVATE_EXPONENT "97B55D7D"

int main()
{
int ret, flen;
BIGNUM *bnn, *bne, *bnd;
unsigned char *in = "abc";
unsigned char *out;

bnn = BN_new();
bne = BN_new();
bnd = BN_new();
BN_hex2bn(&bnn, MODULUS);
BN_set_word(bne, PUBLIC_EXPONENT);
BN_hex2bn(&bnd, PRIVATE_EXPONENT);

RSA *r = RSA_new();
r->n = bnn;
r->e = bne;
r->d = bnd;
RSA_print_fp(stdout, r, 5);

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

out = (char *)malloc(flen);
bzero(out, flen);
//memset(out, 0, flen);


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

printf("Size:%d\n", ret);
printf("ClearText:%s\n", in);
printf("CipherText(Hex):\n");
int i;
for (i=0; i{
printf("0x%02x, ", *out);
out++;
}
printf("\n");

//free(out);

RSA_free(r);
return 0;
}





解密:

/*
gcc -o rsa-decrypt rsa-decrypt.c -lcrypto
*/
#include

#define MODULUS "C8FBCF21"
#define PUBLIC_EXPONENT RSA_F4
#define PRIVATE_EXPONENT "97B55D7D"

int main()
{
int ret, flen;
BIGNUM *bnn, *bne, *bnd;
unsigned char in[] = {0x51, 0xc2, 0x8d, 0xc6};
unsigned char *out;

bnn = BN_new();
bne = BN_new();
bnd = BN_new();
BN_hex2bn(&bnn, MODULUS);
BN_set_word(bne, PUBLIC_EXPONENT);
BN_hex2bn(&bnd, PRIVATE_EXPONENT);

RSA *r = RSA_new();
r->n = bnn;
r->e = bne;
r->d = bnd;
RSA_print_fp(stdout, r, 5);

flen = RSA_size(r);
out = (unsigned char *)malloc(flen);
bzero(out, flen);

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

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

free(out);
RSA_free(r);
return 0;
}





34-23-BA-A9-05-75

相关主题
相关文档
最新文档