⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rsa.cpp

📁 详细的AESRSASHA1实现原理
💻 CPP
字号:
// RSA.cpp: implementation of the CRSA class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Cryptology.h"
#include "RSA.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Extended Euclid
//////////////////////////////////////////////////////////////////////
typedef struct tagTRIPLE
{
    CHuge gcd;
    CHuge x;
    CHuge y;
}Triple;

Triple Extended_Euclid( CHuge a, CHuge b)
{
    Triple r;
    if(b==0)
    {
        r.gcd = a;
        r.x   = 1;
        r.y   = 0;
    }
    else
    {
        Triple e = Extended_Euclid(b, a%b);
        r.gcd = e.gcd;
        r.x   = e.y;
        r.y   = e.x-a/b*e.y;
    }
    
    return r;
}

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CRSA::CRSA()
{
    srand((unsigned)time(NULL));
    
    CreateRandomHugePrime( m_cP, 1+(RSA_BLOCK_BIT_SIZE>>1) );
    CreateRandomHugePrime( m_cQ, RSA_BLOCK_BIT_SIZE>>1 );
    
    m_cN  = m_cP*m_cQ;
    m_cFN = (m_cP-1)*(m_cQ-1);
    m_cE  = 0x10001;
    
    Triple tri;
    do
    {
        tri = Extended_Euclid( m_cE, m_cFN );
    }
    while ( tri.gcd != 1 );
    
    m_cD = tri.x;
    if ( m_cD.IsMinus() )   m_cD = m_cD + m_cFN;
}

CRSA::~CRSA()
{
    
}

//////////////////////////////////////////////////////////////////////
// Transform
//////////////////////////////////////////////////////////////////////
void CRSA::TransRSABlockToHuge( CHuge &n, RSA_BLOCK b )
{
    n.CreateFromBytes( (BYTE*)b, RSA_BLOCK_BYTE_SIZE+1 );
}

void CRSA::TransHugeToRSABlock( CHuge n, RSA_BLOCK b )
{
    n.TransToBytes( (BYTE*)b, RSA_BLOCK_BYTE_SIZE+1 );
}

void CRSA::Encrypt( RSA_BLOCK b )
{
    CHuge msg;
    
    TransRSABlockToHuge( msg, b );
    msg = PowerMod( msg, m_cE, m_cN );
    TransHugeToRSABlock( msg, b );
}

void CRSA::Decrypt( RSA_BLOCK b )
{	
    CHuge decry;
    
    TransRSABlockToHuge( decry, b );
    decry = PowerMod( decry, m_cD, m_cN );
    TransHugeToRSABlock( decry, b );
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -