diff options
author | tomsmeding <tom.smeding@gmail.com> | 2016-10-06 20:21:16 +0200 |
---|---|---|
committer | tomsmeding <tom.smeding@gmail.com> | 2016-10-06 20:21:16 +0200 |
commit | aa5365666bb17299035a3d857bcce962004bda1e (patch) | |
tree | 5381d1aa601812662eed0611c223785945502542 /rsa.cpp | |
parent | 053d2e76ad5848c8d95d7d56bfe7f8a6a324c229 (diff) |
Base64 and import/export keys
Diffstat (limited to 'rsa.cpp')
-rw-r--r-- | rsa.cpp | 65 |
1 files changed, 59 insertions, 6 deletions
@@ -1,12 +1,65 @@ +#include <cstdint> #include <cassert> +#include "base64.h" #include "numalgo.h" +#include "primes.h" +#include "rng.h" #include "rsa.h" -Bigint encrypt(const PublicKey &pubkey,Bigint msg){ - assert(msg>1&&msg<pubkey.mod); - return expmod(msg,pubkey.exp,pubkey.mod); -} +using namespace std; + +namespace RSA{ + + Bigint encrypt(const PublicKey &pubkey,Bigint msg){ + assert(msg>1&&msg<pubkey.mod); + return expmod(msg,pubkey.exp,pubkey.mod); + } + + Bigint decrypt(const PrivateKey &privkey,Bigint encr){ + return expmod(encr,privkey.pexp,privkey.pub.mod); + } + + PrivateKey genkey(int nbits,Rng &rng){ + pair<Bigint,Bigint> pq=genprimepair(rng,nbits); + PrivateKey key; + key.pub.mod=pq.first*pq.second; + key.pub.exp=65537; + Bigint x; + egcd((pq.first-Bigint::one)*(pq.second-Bigint::one),key.pub.exp,x,key.pexp); + return key; + } + + PrivateKey genkey(int nbits){ + Arc4Rng rng; + return genkey(nbits,rng); + } + + PrivateKey genkey(int nbits,const string &password){ + KeyRng rng(password); + return genkey(nbits,rng); + } + + pair<string,string> exportkey(const PrivateKey &key){ + string modser=key.pub.mod.serialiseMantissa(); + int32_t modlen=modser.size(); + string modlenstr{(char)(modlen&0xff),(char)((modlen>>8)&0xff),(char)((modlen>>16)&0xff),(char)((modlen>>24)&0xff)}; + return make_pair( + Base64::encode(modlenstr + modser + key.pub.exp.serialiseMantissa()), + Base64::encode(modlenstr + modser + key.pexp.serialiseMantissa())); + } + + PrivateKey importkey(const string &pub,const string &priv){ + string pubdeser=Base64::decode(pub); + assert(pubdeser.size()>4); + int modlen=(unsigned char)(pubdeser[0])+(unsigned char)(pubdeser[1]<<8)+ + (unsigned char)(pubdeser[2]<<16)+(unsigned char)(pubdeser[3]<<24); + assert((int)pubdeser.size()-4>modlen); + PrivateKey key; + key.pub.mod.deserialiseMantissa(string(pubdeser.begin()+4,pubdeser.begin()+(4+modlen))); + key.pub.exp.deserialiseMantissa(string(pubdeser.begin()+(4+modlen),pubdeser.end())); + string privdeser=Base64::decode(priv); + key.pexp.deserialiseMantissa(string(privdeser.begin()+(4+modlen),privdeser.end())); + return key; + } -Bigint decrypt(const PrivateKey &privkey,Bigint encr){ - return expmod(encr,privkey.pexp,privkey.pub.mod); } |