From b14cdc80529f5c376a3131405a84415fb4dea61c Mon Sep 17 00:00:00 2001 From: orignal Date: Thu, 20 Feb 2014 12:25:28 -0500 Subject: [PATCH] ElGamalEncryptor added --- ElGamal.h | 82 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 64 insertions(+), 18 deletions(-) diff --git a/ElGamal.h b/ElGamal.h index 387e02bb..ca82f19a 100644 --- a/ElGamal.h +++ b/ElGamal.h @@ -12,6 +12,70 @@ namespace i2p { namespace crypto { + + class ElGamalEncryptor + { + public: + + ElGamalEncryptor (const uint8_t * key, bool zeroPadding = false): + y (key, 256), k (rnd, CryptoPP::Integer::One(), elgp-1), + a (a_exp_b_mod_c (elgg, k, elgp)), b1 (a_exp_b_mod_c (y, k, elgp)), + m_ZeroPadding (zeroPadding) + { + } + + void Encrypt (const uint8_t * data, int len, uint8_t * encrypted) + { + // calculate b = b1*m mod p + uint8_t m[255]; + m[0] = 0xFF; + memcpy (m+33, data, len); + CryptoPP::SHA256().CalculateDigest(m+1, m+33, 222); + CryptoPP::Integer b (a_times_b_mod_c (b1, CryptoPP::Integer (m, 255), elgp)); + + // copy a and b + if (m_ZeroPadding) + { + encrypted[0] = 0; + a.Encode (encrypted + 1, 256); + encrypted[257] = 0; + b.Encode (encrypted + 258, 256); + } + else + { + a.Encode (encrypted, 256); + b.Encode (encrypted + 256, 256); + } + } + + private: + + CryptoPP::AutoSeededRandomPool rnd; + CryptoPP::Integer y, k, a, b1; + bool m_ZeroPadding; + }; + + inline bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted, + uint8_t * data, bool zeroPadding = false) + { + CryptoPP::Integer x(key, 256), a(zeroPadding? encrypted +1 : encrypted, 256), + b(zeroPadding? encrypted + 258 :encrypted + 256, 256); + uint8_t m[255], hash[32]; + a_times_b_mod_c (b, a_exp_b_mod_c (a, elgp - x - 1, elgp), elgp).Encode (m, 255); + CryptoPP::SHA256().CalculateDigest(hash, m+33, 222); + for (int i = 0; i < 32; i++) + if (hash[i] != m[i+1]) + { + LogPrint ("ElGamal decrypt hash doesn't match"); + return false; + } + memcpy (data, m + 33, 222); + return true; + } + + +// deprecated + inline void ElGamalEncrypt (const uint8_t * key, const uint8_t * data, int len, uint8_t * encrypted, bool zeroPadding = false) // 514 with padding and 512 without { @@ -31,24 +95,6 @@ namespace crypto a_times_b_mod_c (a_exp_b_mod_c (y, k, elgp), CryptoPP::Integer (m, 255), elgp).Encode (zeroPadding ? encrypted + 258 : encrypted + 256, 256); } - - inline bool ElGamalDecrypt (const uint8_t * key, const uint8_t * encrypted, - uint8_t * data, bool zeroPadding = false) - { - CryptoPP::Integer x(key, 256), a(zeroPadding? encrypted +1 : encrypted, 256), - b(zeroPadding? encrypted + 258 :encrypted + 256, 256); - uint8_t m[255], hash[32]; - a_times_b_mod_c (b, a_exp_b_mod_c (a, elgp - x - 1, elgp), elgp).Encode (m, 255); - CryptoPP::SHA256().CalculateDigest(hash, m+33, 222); - for (int i = 0; i < 32; i++) - if (hash[i] != m[i+1]) - { - LogPrint ("ElGamal decrypt hash doesn't match"); - return false; - } - memcpy (data, m + 33, 222); - return true; - } } }