本例子通过输入rsa密钥参数,即n、e、d三个密钥参数,然后对数据进行加解密得到结果。
其中加解密操作包括,公钥加密、私钥解密、私钥加密、公钥解密。
如下例子是在vs2010中配置好OpenSSL环境,能够直接运行的。少废话,直接上代码:
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#include <openssl/rsa.h>
void debug_printf(char* title, const char* buf, const int len)
{
int i = 0;
if (title) {
printf(title);
printf(" ");
}
printf("total %d bytes\n", len);
for (i = 0; i < len; i++) {
printf("%02X ", (unsigned char)buf[i]);
if ((i % 16) == 15) {
printf("\n");
}
}
if ((i % 16) != 15) {
printf("\n");
}
}
static char *RSA_E = "03";
static char *RSA_D = "0127CBDB5880A09C1CA5F34B7748039D11CF7FBE12BCB0E8737C244EAC7C604F86D947A42EE524C83AAE2C248366AF249522DFAD6DE625045BCB7FD43D0B1EDEE60C3B24FAF3EE2DC941E884D5EB067732E9ABB17705B8FAD8445E584067AD08E88353FF0DD41219C5D9E8AE5A602B756D4A480EB0813BCC0BE23F003942A5F6D54157E0A445FFABD1A8BE3613687D194872AEC331B1A930E3A0266159D1947674802E959C6B0E163005CECC1AF280CB4A80E73802EF8C087A0985CDE8B9309891597B3A36BE37C3A218F03A0130304F86DCE7827FDA93E0F118D0676B83E4E7B5FFA6699ABB1026218F182C4E9401C88E112BC17E608E05954EF7A25302B913";
static char *RSA_N = "01BBB1C904C0F0EA2AF8ECF132EC056B9AB73F9D1C1B095CAD3A367602BA90774A45EB764657B72C58054236C51A06B6DFB44F8424D9378689B13FBE5B90AE4E591258B7786DE544ADE2DCC740E089B2CC5E818A3288957844668D84609B838D5CC4FDFE94BE1B26A8C6DD058790413023EF6C1608C1D9B211D35E8055E3F8F27BE5098596362B41639CDAB1DEDB90CBB3408183AA0FB284A29EB89538AF0A82779888232BEFD67B1C983C2B862A39C1FB0899D0E92A92CDD4F15D1BA0B6F6BF582B5789F8ED7DD881C30052483719AA91D88863FF7580CFAA99D8960C8F188BA264E42D89037CBA2455B7794D853E236C7FA378D0F3B72D8F9219800BCCB85D";
void main()
{
char buf[1024];
char reBuf[1024];
int len = 0;
RSA* r = NULL;
BIGNUM *bne,*bnn,*bnd;
memset(buf, 0, sizeof(buf));
r = RSA_new();
bne = BN_new();
bnd = BN_new();
bnn = BN_new();
BN_hex2bn(&bne, RSA_E);
BN_hex2bn(&bnd, RSA_D);
BN_hex2bn(&bnn, RSA_N);
r->e=bne;
r->d=bnd;
r->n=bnn;
printf("rsa size = %d\n", RSA_size(r));
memset(reBuf, 0, sizeof(buf));
len = RSA_public_encrypt(10, (unsigned char*)"1234567890", (unsigned char*)reBuf, r, RSA_PKCS1_PADDING);
printf("RSA_public_encrypt re = %d\n", len);
debug_printf(NULL, reBuf, len);
memset(buf, 0, sizeof(buf));
len = RSA_private_decrypt(len, (unsigned char*)reBuf, (unsigned char*)buf, r, RSA_PKCS1_PADDING);
debug_printf(NULL, buf, len);
memset(reBuf, 0, sizeof(buf));
len = RSA_private_encrypt(10, (unsigned char*)"9876543210", (unsigned char*)reBuf, r, RSA_PKCS1_PADDING);
printf("RSA_public_encrypt re = %d\n", len);
debug_printf(NULL, reBuf, len);
memset(buf, 0, sizeof(buf));
len = RSA_public_decrypt(len, (unsigned char*)reBuf, (unsigned char*)buf, r, RSA_PKCS1_PADDING);
debug_printf(NULL, buf, len);
BN_free(bne);
BN_free(bnd);
BN_free(bnn);
RSA_free(r);
}
觉得好就点赞,欢迎转载,转载请说明出处。