Created
September 3, 2015 08:20
-
-
Save palloc/ee016258b80c447bb38e to your computer and use it in GitHub Desktop.
OldRSApgm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//RSA暗号化プログラム | |
#include <iostream> | |
#include <vector> | |
#include <random> | |
#include <time.h> | |
#define unsigned unsigned long long | |
using namespace std; | |
//最大公約数を求める | |
unsigned gcd(unsigned m, unsigned n) | |
{ | |
// 引数に0がある際は例外処理をする。 | |
try{ | |
if ((0==m)||(0==n)) throw m; | |
} | |
catch(...){ | |
cout<<"there has 0."<<endl; | |
return 0; | |
} | |
// ユークリッド互除法 | |
while(m!=n) | |
{ | |
if(m>n){m=m-n;} | |
else{n = n - m;} | |
} | |
return m; | |
} | |
class key{ | |
public: | |
unsigned publickey; | |
unsigned rule; | |
}; | |
int main(int argc, char* argv[]) | |
{ | |
//乱数作成器 | |
random_device rnd; | |
//素数格納オブジェクト | |
vector<unsigned> prime; | |
int flag=0; | |
//公開鍵オブジェクト | |
key openkey; | |
//vectorに3ケタの素数を格納 | |
for(unsigned i=10;i<100;i++){ | |
for(unsigned j=2;j<i/2;j++){ | |
if(i%j==0){ | |
flag=1; | |
} | |
} | |
if(flag==0){ | |
prime.push_back(i); | |
} | |
flag=0; | |
} | |
unsigned a,b; | |
//2つの素数をランダムにvectorから選出 | |
do{ | |
a=prime[rnd()%prime.size()]; | |
b=prime[rnd()%prime.size()]; | |
}while(a==b); | |
//公開鍵の一つとなるルールを作成 | |
openkey.rule=a*b; | |
//もう一つの公開鍵を求める | |
while(1){ | |
openkey.publickey=rnd()%((unsigned)openkey.rule-1); | |
if(gcd(openkey.publickey,(a-1)*(b-1))==1){ | |
break; | |
} | |
openkey.publickey=0; | |
} | |
//秘密鍵を求める | |
unsigned privatekey; | |
for(int i=2;(int)openkey.publickey*i%((a-1)*(b-1))!=1;i++){ | |
privatekey=i+1; | |
} | |
cout<<"public key1: "<<openkey.publickey<<endl; | |
cout<<"private key: "<<privatekey<<endl; | |
cout<<"public key2: "<<openkey.rule<<endl; | |
cout<<"prime numbers: "<<a<<" "<<b<<endl<<endl; | |
cout<<"example:"<<endl; | |
//実行例(1〜100) | |
unsigned abb=rnd()%100+1; | |
unsigned encryption=abb; | |
cout<<"original number: "<<abb<<endl; | |
//暗号化 | |
for(unsigned i=1;i<openkey.publickey;i++){ | |
abb*=encryption; | |
while(abb>=openkey.rule)abb-=openkey.rule; | |
} | |
cout<<"after encryption: "<<abb<<endl; | |
cout<<"start decryption"<<endl; | |
clock_t start=clock(); | |
//複合化 | |
unsigned decryption=abb; | |
for(unsigned i=1;i<privatekey;i++){ | |
abb*=decryption; | |
while(abb>=openkey.rule)abb-=openkey.rule; | |
} | |
clock_t end=clock(); | |
cout<<"after decryption: "<<abb<<endl; | |
cout<<"passed time between decryption:"<<(double)(end-start)/CLOCKS_PER_SEC<<"seconds"<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment