Files Classes Functions Hierarchy
00001 #include <cassert> 00002 #include <iostream> 00003 #include <sstream> 00004 #include <fstream> 00005 #include <string> 00006 using namespace std; 00007 00008 #include <NTL/ZZ.h> 00009 using namespace NTL; 00010 00011 #include <rsa.h> 00012 00013 00014 void rsaE::operator()( string & c, string const & m ) const 00015 { 00016 ZZ m2; 00017 conv(m2,m.c_str()); 00018 00019 ZZ c2; 00020 PowerMod(c2,m2,e,n); 00021 00022 stringstream ss; 00023 ss << c2; 00024 c = ss.str(); 00025 } 00026 00027 00028 00029 void rsaD::init() 00030 { 00031 n = p*q; 00032 00033 ZZ n2 = (p-1)*(q-1); 00034 00035 InvMod(d,e,n2); 00036 00037 // cout << "d=" << d << endl; 00038 } 00039 00040 00041 void rsaD::operator()( string & m, string const & c ) const 00042 { 00043 ZZ c2; 00044 conv(c2,c.c_str()); 00045 00046 ZZ m2; 00047 PowerMod(m2,c2,d,n); 00048 stringstream ss; 00049 ss << m2; 00050 m = ss.str(); 00051 } 00052 00053 00054 void rsaGenKey::finde() 00055 { 00056 for ( ; ; ) 00057 { 00058 RandomBits(e,nbits); 00059 lpg.ensurenbits(e,nbits); 00060 00061 if (GCD(e,n2)==1) 00062 return; 00063 } 00064 } 00065 00066 rsaGenKey::rsaGenKey 00067 ( 00068 uintc _nbits, 00069 string const & _p, 00070 string const & _q 00071 ) 00072 : nbits(_nbits) 00073 { 00074 conv(p,_p.c_str()); 00075 conv(q,_q.c_str()); 00076 00077 lpg.findprime_sequentially(p,nbits); 00078 lpg.findprime_sequentially(q,nbits); 00079 00080 genkey(); 00081 } 00082 00083 void rsaGenKey::genkey() 00084 { 00085 n= p*q; 00086 n2 = (p-1)*(q-1); 00087 00088 finde(); 00089 00090 blocksizecalc(); 00091 00092 //print(); 00093 00094 { 00095 ofstream f1("encrypt.txt"); 00096 f1 << "encrypt=true" << endl; 00097 f1 << "n=" << n << endl; 00098 f1 << "e=" << e << endl; 00099 f1 << "blocksize=" << blocksize << endl; 00100 } 00101 00102 { 00103 ofstream f2("decrypt.txt"); 00104 f2 << "decrypt=true" << endl; 00105 f2 << "p=" << p << endl; 00106 f2 << "q=" << q << endl; 00107 f2 << "e=" << e << endl; 00108 } 00109 } 00110 00111 00112 rsaGenKey::rsaGenKey(uintc _nbits) 00113 : nbits(_nbits) 00114 { 00115 assert(nbits>10); // Really want large primes! 00116 00117 lpg.findprime_randomly(p,nbits); 00118 lpg.findprime_randomly(q,nbits); 00119 00120 genkey(); 00121 } 00122 00123 void rsaGenKey::print() const 00124 { 00125 cout << SHOW(p) << endl; 00126 cout << SHOW(q) << endl; 00127 cout << SHOW(e) << endl; 00128 cout << SHOW(n) << endl; 00129 cout << SHOW(n2) << endl; 00130 cout << SHOW(nbits) << endl; 00131 cout << SHOW(blocksize) << endl; 00132 } 00133 00134 void rsaGenKey::blocksizecalc() 00135 { 00136 double x = nbits; 00137 double y; 00138 // y = 2.0*x*std::log10(2.0); 00139 y = x*std::log10(2.0)-1.0; 00140 y = std::floor(y); 00141 assert(y>1.0); 00142 blocksize = (uint)y; 00143 } 00144 00145
1.5.8