C++实现RSA加密解密算法

2024-11-27 01:16:57
推荐回答(2个)
回答1:

#include
using namespace std;

template
HugeInt Power( const HugeInt & x, const HugeInt & n, // 求x^n mod p
const HugeInt & p )
{
if( n == 0 )
return 1;

HugeInt tmp = Power( ( x * x ) % p, n / 2, p );

if( n % 2 != 0 )
tmp = ( tmp * x ) % p;

return tmp;
}

template
void fullGcd( const HugeInt & a, const HugeInt & b, //
HugeInt & x, HugeInt & y )
{
HugeInt x1, y1;

if( b == 0 )
{
x = 1;
y = 0;
}
else
{
fullGcd( b, a % b, x1, y1 );
x = y1;
y = x1 - ( a / b ) * y1;
}
}

template
HugeInt inverse( const HugeInt & p, const HugeInt & q, // 求d
const HugeInt & e )
{
int fyn = ( 1 - p ) * ( 1 - q );
HugeInt x, y;

fullGcd( fyn, e, x, y );
return x > 0 ? x : x + e;
}

int main( )
{
cout << "Please input the plaintext: " << endl;
int m;
cin >> m;
cout << "Please input p,q and e: " << endl;
int p, q, e;
cin >> p >> q >> e;
int n = p * q;
int d = inverse( p, q, e );
int C = Power( m, e, n );
cout << "The ciphertext is: " << C << endl;
cout << "\n\nPlease input the ciphertext: " << endl;
cin >> C;
cout << "\n\nPlease input p, q and d: " << endl;
cin >> p >> q >> d;
n = p * q;
m = Power( C, d, n );
cout <<"The plaintext is: " << m << endl << endl;

system( "pause" );
return 0;
}

这就是RSA加密解密算法

回答2:

你的程序直接运行结束了,所以你什么都看不见。
你可以在你的MAIN函数最后一行加一句:
getchar();
或者
system("pause");

另外如果你输出的内容是非可见字符,那你也看不见,你下个断点,看看变量的值就看见了。