From aa5365666bb17299035a3d857bcce962004bda1e Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Thu, 6 Oct 2016 20:21:16 +0200 Subject: Base64 and import/export keys --- rsa.cpp | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 6 deletions(-) (limited to 'rsa.cpp') diff --git a/rsa.cpp b/rsa.cpp index 11bf0eb..ec79e72 100644 --- a/rsa.cpp +++ b/rsa.cpp @@ -1,12 +1,65 @@ +#include #include +#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&&msg1&&msg 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 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); } -- cgit v1.2.3-70-g09d2