OpenSSL中RSA的简易加解密流程

RSA是公钥密码体制的典范,在本实验中,我们的将使用OpenSSL自带的RSA相关函数生成RSA加密体系。下面是可能要使用到的一些函数说明。
(1)RSA *RSA_generate_key(int bits,
unsigned long e_value,
void (callback)(int, int, void ),
void *cb_arg)
函数功能:生成RSA密钥对。
参数说明:
bits:int数据类型,表示模数比特数,目前至少应使用1024或2048。
e_value:unsigned long数据类型,表示公钥指数e,建议该值使用OpenSSL提供的两个常数RSA_3或者RSA_F4。
callback回调函数由用户实现,用于报告密钥生成状态的回调函数,可为空。
其中RSA的结构为:
struct rsa_st
{
/* 其他 */
const RSA_METHOD *meth;
ENGINE *engine;
BIGNUM *n; //参数n
BIGNUM *e; //参数e
BIGNUM *d; //参数d
BIGNUM *p;
BIGNUM *q;
BIGNUM *dmp1;
BIGNUM *dmq1;
BIGNUM *iqmp;
CRYPTO_EX_DATA ex_data;
int references;
/* 其他数据项 */
}RSA;
(2)RSA_public_encrypt(int flen,unsigned char * from,unsigned char * to ,RSA *rsa,in padding);
函数功能:公钥加密,使用rsa里面的公钥,加密从from(通常是一个会话密钥)来的flen字节到to里面
参数说明:
flen:待加密的明文长度
from:待加密的明文
to:存储密文的指针
rsa:提供加密过程使用到的公钥等参数
padding:加密模式,最常用的加密模式是RSA_PKCS1_PADDING
返回值:加密得到的密文的字节数
(3)RSA_private_decrypt(int flen,unsigned char * from,unsigned char * to ,RSA *rsa,in padding);
函数功能:私钥加密,使用rsa里面的私钥,解密从from(通常是一个会话密钥)来的flen字节到to里面
参数说明:
flen:待解密的密文长度
from:待解密的密文
to:存储加密后明文的指针
rsa:提供解密过程使用到的私钥等参数
padding:解密密模式,需要与加密模式保持一致,最常用的加密模式是RSA_PKCS1_PADDING
返回值:解密得到的明文字节数
(4)void RSA_free(RSA *rsa);
函数功能:释放RSA对象
参数说明:
rsa待释放的对象指针


#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <vector>
#include <openssl/rsa.h>
using namespace std;
int main()
{
    RSA * rsa =RSA_generate_key(1024,RSA_3,NULL,NULL);
    unsigned char plain[512]="Y I love you.";
    unsigned char cipper[512]={0},newplain[512]={0};
    size_t outl=512,outl2;
    cout<<"明文:"<<plain<<endl;
    for(int i =0;i<strlen((char*)plain);i++)
    {
        printf("%0.2X ",plain[i]);
    }
    printf("\n");
    outl=RSA_public_encrypt(strlen((char*)plain),plain,cipper,rsa,RSA_PKCS1_OAEP_PADDING);
    cout<<"密文:"<<cipper<<endl;
    cout<<"hex:";
    for(int i =0;i<outl;i++)
    {
        printf("%0.2X ",cipper[i]);
    }
    printf("\n");
    outl2=RSA_private_decrypt(outl,cipper,newplain,rsa,RSA_PKCS1_OAEP_PADDING);
    cout<<"解密后明文:"<<newplain<<endl;
    cout<<"hex:";
    for(int i =0;i<outl2;i++)
    {
        printf("%0.2X ",newplain[i]);
    }
    printf("\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值