RSA and Elgamal signatures

Started by
1 comment, last by l3mon 16 years, 10 months ago
Hi. I'm looking for simple RSA and Elgamal sources in c# or c++. Everything i've found on the net was uncommented or just has miles of code. It's for my friend so i don't really need (and don't want) to start from scratch, plus program should be done in few days. Thanx for your help.
i make the game so i be ballin
Advertisement
RSA itself isn't that much code.
The problem is the large numbers that you need to use to make it secure.
I'd look for a big-num library that can handle the number of bits that you need, it probably already got the functions needed for RSA if not there's only a few that need to be implemented (and they are not that complicated).
The "problem" with all the implementations out there is that they are based on some quite heavy-weight big-num libraries (often written in C with a C++ wrapper).
I actually wrote my own library in a few days, only supporting basic operations and only unsigned numbers (wich is fine for RSA).

I'm sorry but I'm not allowed to give away my code, but it's got quite a few dependecies on the rest of the code base so it's not that suitable anyway.

But my recommendation is to search for a light-weight big-num libary instead (maybe C# have one built in?).

Once you have that the RSA part is fairly easy, this is my implementation:
class Rsa{public:	template <class T> struct Key	{		T m_exponent;		T m_modulo;	};	template <class T> static void genKeys(Key<T>& publicKey, Key<T>& privateKey, Random* const rng = null)	{		static const unsigned int maxBits = (sizeof(T) * 4);		static const unsigned int minBits = ((sizeof(T) * 33) >> 4);		static const unsigned int eBits = ((minBits + 3) >> 2) + 1;		T e = PrimeSearch::find<T>(eBits, maxBits, rng);		T p;		do {			p = PrimeSearch::find<T>(minBits, maxBits, rng);		}while ((p % e) == T(1));		unsigned int bits = p.highestUsedBit();		T q;		do {			q = PrimeSearch::find<T>(maxBits - bits + 1, maxBits - bits + 24, rng);		}while (((q % e) == T(1)) && ((p * q).highestUsedBit() <= maxBits) && ((p * q).highestUsedBit() >= (maxBits + 24)));		T n = p * q;		T m = (q - T(1)) * (p - T(1));		T d = e.inv(m);		T nd = m - d;		T test = q + T(7);		T k = test.powModN(e, n);		T de = k.powModN(d, n);		if (de != test)			d = nd;		publicKey.m_exponent = e;		publicKey.m_modulo = n;		privateKey.m_exponent = d;		privateKey.m_modulo = n;	}	template <class T> static T crypt(const T& m, const Key<T>& key)	{		return (m + (key.m_modulo >> T(2))).powModN(key.m_exponent, key.m_modulo);	}	template <class T> static T decrypt(const T& m, const Key<T>& key)	{		return m.powModN(key.m_exponent, key.m_modulo) - (key.m_modulo >> T(2));	}};
Check out the Crypto Toolset for Python. I can't recall, but I guess you'll find the C sources there as well.

This topic is closed to new replies.

Advertisement