www.pudn.com > sanpack_rsa_vs2003sln_src.rar > rsa_draft.cpp
#include "stdafx.h"
// This is a draft version of RSA encryption
// Improved by sanicle,2006.1
// 3mn@3mn.net
#include "rsa_draft.h"
class prime_factory
{
unsigned np;
unsigned *pl;
public:
prime_factory();
~prime_factory();
vlong find_prime( vlong & start );
};
// prime factory implementation
static int is_probable_prime( const vlong &p )
{
// Test based on Fermats theorem a**(p-1) = 1 mod p for prime p
// For 1000 bit numbers this can take quite a while
const rep = 4;
const unsigned any[rep] = { 2,3,5,7 };
for ( unsigned i=0; i q ) { vlong tmp = p; p = q; q = tmp; }
}
// Calculate public key
{
m = p*q;
e = 50001; // must be odd since p-1 and q-1 are even
while ( gcd(p-vlong(1),e) != vlong(1) || gcd(q-vlong(1),e) != vlong(1) ) e += 2;
}
}
vlong public_key::encrypt( const vlong& plain )
{
return modexp( plain, e, m );
}
vlong private_key::decrypt( const vlong& cipher )
{
// Calculate values for performing decryption
// These could be cached, but the calculation is quite fast
vlong d = modinv( e, (p-vlong(1))*(q-vlong(1)) );
vlong u = modinv( p, q );
vlong dp = d % (p-vlong(1));
vlong dq = d % (q-vlong(1));
// Apply chinese remainder theorem
vlong a = modexp( cipher % p, dp, p );
vlong b = modexp( cipher % q, dq, q );
if ( b < a ) b += q;
return a + p * ( ((b-a)*u) % q );
}