1. 程式人生 > >OpenSSL中RSA的簡易加解密流程

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; }