Visual C++ BigInt and SecureRandom? Is there a BigInt library with modPow?
I have to port some crypto code to visual c++ from java which (visual c++) I am not very familiar with. I found a library at http://sourcefor开发者_Python百科ge.net/projects/cpp-bigint/ that I can use for big integers.
However it does not have an equivalent to javas SecureRandom class. I did find a project in c++ called beecrypt but could not get it to work with Visual Studio 2008.
Does anyone have any experience with these types of libraries? I saw gmp too but couldn't find one that worked with visual studio off the bat.
Before I head down the wrong road any advice?
Thanks!
----UPDATE-------
I seem to have a proof of concept working with the cpp-bigint from above with small numbers. In the library there is no modPow function. For now I created a for loop like:
for(RossiBigInt i("0",DEC_DIGIT); i< r; i++)
{ x = x * g; x = x % p; }
This gives me x = g^r mod p but it is very slow. Does anyone know of other BitInteger libraries with the modPow function or know a faster way for me to compute this?
Thanks!
The modPow function can be evaluated efficiently with a "square and multiply" algorithm. In Java it would look like this (if Java's BigInteger did not already have it):
/* Compute x^n mod m. */
static BigInteger modPow(BigInteger x, BigInteger n, BigInteger m)
{
if (n.signum() < 0)
throw new IllegalArgumentException("bwah, negative exponent");
BigInteger r = BigInteger.ONE;
for (int i = n.bitLength() - 1; i >= 0; i --) {
if (n.testBit(i))
r = r.multiply(x).mod(m);
if (i > 0)
r = r.multiply(r).mod(m);
}
return r;
}
With this, the number of loop iteration is equal to the length, in bits, of the exponent, so that the computational time is acceptable.
You still get one or two modular reductions per iteration, so this will not be the fastest exponentiation algorithm ever (modular reductions are substantially more expensive than multiplication). Typical modPow() implementations use Montgomery reduction, which is a clever trick which merges all modular reduction into a single similar operation at the end.
If you have time, implementing your own modular exponentiation would be very pedagogical; you would start by reading chapter 14 of the "Handbook of Applied Cryptography", freely downloadable from this site. However, in this harsh world where mundane considerations of budget often limit creativity and free time, you would probably be happy with an already implemented library. GMP is known to be quite good, but somewhat difficult to use on Windows. You may have better luck with NTL.
For generating random data on Windows you can also use CryptoAPI, specifically the CryptGenRandom method.
精彩评论