自己封裝Crypto++的RSA類

 //頭文件

#pragma once
//#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
//#include <afx.h>
#include <iostream>
//#include <winioctl.h>
#include <Windows.h>
#include "rsa.h"
#include "hex.h"
#include "files.h"
#include "rng.h"
#include "default.h"
#include "randpool.h"
#include "ida.h"
#include "base64.h"
#include "des.h"
#include "modes.h"
//#include "socketft.h"
//#include "wait.h"
#include "factory.h"
#include "whrlpool.h"
#include "validate.h"
#include "osrng.h"

//#include "computerInfo.h"
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)

#pragma comment(lib, "cryptlib.lib")

class RSAInterface
{
public:

 RSA::PrivateKey m_privateKey;
 RSA::PublicKey m_publicKey;
 Integer n;
 Integer e;
 Integer d; 

public:
 RSAInterface(void);
 ~RSAInterface(void);

 //n,d,e必須是10進制數,當用RSA-TOOL生成N,D,E時Number Base要選10
 RSA::PrivateKey  GenerateRSAPrivateKey(const Integer &n, const Integer &d,const Integer &e);
 RSA::PublicKey   GenerateRSAPublicKey(const Integer &n, const Integer &e);//n,d,e必須是10進制數
 string RSAEncryptString(string plain);
 string RSADecryptString(string cipher);
 bool RSASet_n(Integer &nn);
 bool RSASet_e(Integer &ee);
 bool RSASet_d(Integer &dd);

 
};
////////////////////////////////////////////////////////////////////////////////////

//C++文件


#include "RsaInterface.h"
using namespace std;
RSAInterface::RSAInterface(void)
: n("")
, d("")
, e("")
{

 // 初始化公鑰和私鑰
 m_privateKey=GenerateRSAPrivateKey(n, d, e);
 m_publicKey=GenerateRSAPublicKey(n, e);

}

RSAInterface::~RSAInterface(void)
{
}

RSA::PrivateKey  RSAInterface::GenerateRSAPrivateKey(const Integer &n, const Integer &d, const Integer &e)
{

 InvertibleRSAFunction params;
 params.Initialize(n,e,d);
 RSA::PrivateKey m_privateKey( params );
 return m_privateKey;

}
RSA::PublicKey  RSAInterface::GenerateRSAPublicKey(const Integer &n, const Integer &e)
{
 RSAFunction params;
 params.Initialize(n,e);
 RSA::PublicKey m_publicKey( params );
 return m_publicKey;

}

string RSAInterface::RSAEncryptString(string plain)
{

 AutoSeededRandomPool rng;
 // Encryption

 string cipher;

 RSAES_OAEP_SHA_Encryptor en( m_publicKey );

 StringSource(  plain, true,
  new PK_EncryptorFilter( rng, en,
  new HexEncoder(new StringSink(cipher ))

  ) // PK_EncryptorFilter
  ); // StringSource

 return cipher;
}
string RSAInterface::RSADecryptString(string cipher)
{
 AutoSeededRandomPool rng;

 // Decryption

 string plain;

 RSAES_OAEP_SHA_Decryptor de( m_privateKey );

 StringSource( cipher, true,
  new HexDecoder(new PK_DecryptorFilter( rng, de,
  new StringSink( plain ))
  ) // PK_DecryptorFilter
  ); // StringSource

 return plain;

}

bool RSAInterface::RSASet_n(Integer &nn)
{
 n=nn;
 return true;
}
bool RSAInterface::RSASet_e(Integer &ee)
{
 e=ee;
 return true;
}
bool RSAInterface::RSASet_d(Integer &dd)
{
 d=dd;
 return true;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章