可能看到我有三篇<>可能很奇怪,其实是有不少人向我要RSA加密解的代码,如果每次都给他们一样的,可能会被老师发觉,所以我就写了不同的语言实现,一来可以加强自己适应不同语言编程的能力,另一方面,则给他们“鱼”。当然如果他们问我“渔”,我也肯定会耐心地一行一行代码解释的,但大多情况都是取"鱼“的。
上代码:
#include "big.h"
#include
#include
using namespace std;
Miracl precision(10000,2);
int main()
{
int bits;
Big n,e,d;
cout<
cin>>bits;
int half = bits/2;
Big p,q,fn,tmp;
tmp = rand(half,2);
p = nextprime(tmp);
tmp = rand(half,2);
q = nextprime(tmp);
n = p*q;
fn = (p-1)*(q-1);
do{
e = rand(16,2);
e = nextprime(e);
if(gcd(e,fn)==1)
break;
}while(true);
d = inverse(e,fn);
cout<
cout<
cout<
cin>>tmp;
tmp = pow(tmp,e,n);
cout<
tmp = pow(tmp,d,n);
cout<
cout<
string a,b="q";
cin>>a;
if (a==b)
return 0;
else{
main();
}
return 0;
}
此代码需要加入miracl大数库,miracl大数库就度娘吧。
运行环境为linux。
给个运行例子:
ioiu@vovoat ~ $ cd miracl/ ioiu@vovoat ~/miracl $ ./rsa 请输入公钥大数的位数:120 公钥:(33937, 581391457270455374350986417085840243) 私钥:(42366180682730828799917814124458985, 581391457270455374350986417085840243) 请输入加密数据:13123132123 加密结果:562883886171478657222537176357508675 解密结果:13123132123 退出按"q",其他任意键继续:continue 请输入公钥大数的位数:1024 公钥:(37097, 63365584111760012867117869373986248445997539263932411135871142763322559310982732048644492202831432012570698516627561293221730960180262325318767651996871305524296598425358192458573368193348675103036418050678720953231816470495130955506447034349964560585395757071144229636045715778655771304114389514210042446689) 私钥:(35784807050202772988816329174461867669721229414221743356511320076868954836377287554764593138240787682652401378099237380192340718003517689177782093143231353373469268526806259649023818118415817753640906856939745089707816179234742312412061191058666694500310213325231276881602082309476273320885155361504897997433, 63365584111760012867117869373986248445997539263932411135871142763322559310982732048644492202831432012570698516627561293221730960180262325318767651996871305524296598425358192458573368193348675103036418050678720953231816470495130955506447034349964560585395757071144229636045715778655771304114389514210042446689) 请输入加密数据:8051734895710895701489571038945719038457103489571034895710894570138457083457018345701893457018934751389475 加密结果:29322019958141054256886049528306158652742812828885213005768833838672882592080550556761580487462440224815699574681790924154583771670997225196809594748660784352317441364620561664658750803053773291898411342248702146749498749378190900922872573240815467730236791929053638759670378941960608483494996147707590139897 解密结果:8051734895710895701489571038945719038457103489571034895710894570138457083457018345701893457018934751389475 退出按"q",其他任意键继续: