Skip to content

Instantly share code, notes, and snippets.

@maciektr
Last active June 7, 2018 10:13
Show Gist options
  • Save maciektr/603ff453f7dc4cdda70441387b43e0da to your computer and use it in GitHub Desktop.
Save maciektr/603ff453f7dc4cdda70441387b43e0da to your computer and use it in GitHub Desktop.
A simple RSA implementation for small numbers
#include<iostream>
#include <vector>
using namespace std;
using LLong = long long int;
LLong gcd(LLong a, LLong b){
return (b ? gcd(b,a%b):a);
}
LLong odwr_mod(LLong a, LLong mod){
for(LLong i = 0; i<mod; i++)
if(a*i % mod ==1)
return i;
return -1;
}
LLong power_mod(LLong value, LLong exp, LLong mod){
if(exp == 0)
return 1;
if(exp % 2 == 0){
LLong a = (power_mod(value,exp/2, mod))%mod;
return (a*a)%mod;
}
return (power_mod(value, (exp-1), mod)*(value%mod))%mod;
}
int main(){
const int p=17,q=11;
LLong n = p*q;
LLong phi = (p-1)*(q-1);
LLong e = 3;
while(gcd(e,phi)!=1)
e++;
LLong d = odwr_mod(e,phi);
cout<<"Public key = "<<e<<endl<<"Private key = "<<d<<endl<<"Modulo = "<<n<<endl;
auto print_tab = [](vector<LLong>&tab){
for(auto i : tab)
cout<<i<<" ";
cout<<endl;
};
vector<LLong> tab({9,60,43,65,53,22,1});
cout<<"Value: "; print_tab(tab);
for(auto& i : tab){
i = power_mod(i,e,n);
}
cout<<"Encrypted: ";print_tab(tab);
for(auto& i : tab){
i = power_mod(i,d,n);
}
cout<<"Decrypted: ";print_tab(tab);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment