www.pudn.com > sanpack_rsa_vs2003sln_src.rar > rsa_san.cpp


#include "stdafx.h" 
// This is a slow but easy RSA encryption class 
// By sanicle,2005.12  
// 3mn@3mn.net 
 
#include "stdio.h" 
#include "rsa_san.h" 
 
class Prime_factory_san 
{ 
  unsigned np; 
  unsigned *pl; 
  public: 
  Prime_factory_san(); 
  ~Prime_factory_san(); 
  vlong find_prime( vlong & start ); 
}; 
 
// prime factory implementation 
 
static int is_probable_prime_san( 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; } 
} 
 
void RSA_san::random_e() 
{ 
	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; 
} 
 
void RSA_san::calculate_d() 
{ 
	d = modinv(e,(p-vlong(1))*(q-vlong(1))); 
} 
vlong RSA_san::encrypt( const vlong& x ) 
{ 
	return modexp(x,e,n); 
} 
 
vlong RSA_san::decrypt( const vlong& y ) 
{ 
	return modexp(y,d,n); 
} 
 
int RSA_san::RSA_san_en(char * s,unsigned n) 
{ 
	vlong t = 0; 
	result = 0; 
	for(unsigned i=0;i=0;i--) 
	{ 
		t=v.get(i); 
		//t to hex and save in char s[] 
		for(int m=0;m<8;m++)st[m]='\0'; 
		sprintf(st,"%X",t); 
		l=(unsigned)strlen(st); 
		if(l!=8) 
		{ 
			for(int m=0;m<8;m++)st[m]='0'; 
			sprintf(st+8-l,"%X",t); 
		}	 
		for(int k=0;k<8;k++) 
		{ 
			if(st[k]=='\0')st[k]='0'; 
			s[j]=st[k]; 
			j++; 
		} 
	} 
	s[j]='\0'; 
 
	ps=s; 
	while(*ps=='0')ps++; 
 
	if(*ps=='\0')ps--; 
 
	return ps; 
} 
 
/* 
unsigned* RSA_san::vlong2ints( const vlong& v ) 
{ 
	unsigned z,j; 
	j=0; 
	z=v.get_z()-1; 
	for(int i=z;i>=0;i--,j++) 
	{ 
		u[j]=v.get(i); 
	} 
	u[j]=0; 
	return u; 
} 
*/ 
 
char* RSA_san::vlong2shortints( const vlong& v ) 
{ 
	// use this function only when RSA result has no '\0' in it! 
	unsigned z,j; 
	char *pi; 
	j=0; 
	z=v.get_z()-1; 
	for(int i=z;i>=0;i--,j++) 
	{ 
		u[j]=v.get(i); 
	} 
	u[j]=0; 
	pi=(char *)u; 
	while(!*pi)pi++; 
	return pi; 
}