21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

7.4 Manipulating Big Numbers<br />

<strong>Problem</strong><br />

You need to do integer-based arithmetic on numbers that are too large to represent<br />

in 32 (or 64) bits. For example, you may need to implement a public key algorithm<br />

that isn’t supported by the library you’re using.<br />

Solution<br />

Use a preexisting library for arbitrary-precision integer math, such as the BIGNUM<br />

library that comes with OpenSSL(discussed here) or the GNU Multi-Precision (gmp)<br />

library.<br />

Discussion<br />

Most of the world tends to use a small set of public key primitives, and the popular<br />

libraries reflect that fact. There are a lot of interesting things you can do with public<br />

key cryptography that are in the academic literature but not in real libraries, such as<br />

a wide variety of different digital signature techniques.<br />

If you need such a primitive and there aren’t good free libraries that implement it,<br />

you may need to strike off on your own, which will generally require doing math<br />

with very large numbers.<br />

In general, arbitrary-precision libraries work by keeping an array of words that represents<br />

the value of a number, then implementing operations on that representation in<br />

software. Math on very large numbers tends to be slow, and software implementation<br />

of such math tends to be even slower. While there are tricks that occasionally<br />

come in handy (such as using a fast Fourier transform for multiplication instead of<br />

longhand multiplication when the numbers are large enough to merit it), such libraries<br />

still tend to be slow, even though the most speed-critical parts are often implemented<br />

in hand-optimized assembly. For this reason, it’s a good idea to stick with a<br />

preexisting library for arbitrary-precision arithmetic if you have general-purpose<br />

needs.<br />

In this recipe, we’ll cover the OpenSSLBIGNUM library, which supports arbitrary<br />

precision math, albeit with a very quirky interface.<br />

Initialization and cleanup<br />

The BIGNUM library generally lives in libcrypto, which comes with OpenSSL. Its<br />

API is defined in openssl/bn.h. This library exports the BIGNUM type. BIGNUM objects<br />

always need to be initialized before use, even if they’re statically declared. For example,<br />

here’s how to initialize a statically allocated BIGNUM object:<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Manipulating Big Numbers | 315

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!