2 * Copyright (c) 2001 Dima Dorfman.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * This is the traditional Berkeley MP library implemented in terms of
29 * the OpenSSL BIGNUM library. It was written to replace libgmp, and
30 * is meant to be as compatible with the latter as feasible.
32 * There seems to be a lack of documentation for the Berkeley MP
33 * interface. All I could find was libgmp documentation (which didn't
34 * talk about the semantics of the functions) and an old SunOS 4.1
35 * manual page from 1989. The latter wasn't very detailed, either,
36 * but at least described what the function's arguments were. In
37 * general the interface seems to be archaic, somewhat poorly
38 * designed, and poorly, if at all, documented. It is considered
41 * Miscellaneous notes on this implementation:
43 * - The SunOS manual page mentioned above indicates that if an error
44 * occurs, the library should "produce messages and core images."
45 * Given that most of the functions don't have return values (and
46 * thus no sane way of alerting the caller to an error), this seems
47 * reasonable. The MPERR and MPERRX macros call warn and warnx,
48 * respectively, then abort().
50 * - All the functions which take an argument to be "filled in"
51 * assume that the argument has been initialized by one of the *tom()
52 * routines before being passed to it. I never saw this documented
53 * anywhere, but this seems to be consistent with the way this
56 * - msqrt() is the only routine which had to be implemented which
57 * doesn't have a close counterpart in the OpenSSL BIGNUM library.
58 * It was implemented by hand using Newton's recursive formula.
59 * Doing it this way, although more error-prone, has the positive
60 * sideaffect of testing a lot of other functions; if msqrt()
61 * produces the correct results, most of the other routines will as
64 * - Internal-use-only routines (i.e., those defined here statically
65 * and not in mp.h) have an underscore prepended to their name (this
66 * is more for aesthetical reasons than technical). All such
67 * routines take an extra argument, 'msg', that denotes what they
68 * should call themselves in an error message. This is so a user
69 * doesn't get an error message from a function they didn't call.
72 #include <sys/cdefs.h>
73 __FBSDID("$FreeBSD$");
82 #include <openssl/crypto.h>
83 #include <openssl/err.h>
87 #define MPERR(s) do { warn s; abort(); } while (0)
88 #define MPERRX(s) do { warnx s; abort(); } while (0)
89 #define BN_ERRCHECK(msg, expr) do { \
90 if (!(expr)) _bnerr(msg); \
93 static void _bnerr(const char *);
94 static MINT *_dtom(const char *, const char *);
95 static MINT *_itom(const char *, short);
96 static void _madd(const char *, const MINT *, const MINT *, MINT *);
97 static int _mcmpa(const char *, const MINT *, const MINT *);
98 static void _mdiv(const char *, const MINT *, const MINT *, MINT *, MINT *,
100 static void _mfree(const char *, MINT *);
101 static void _moveb(const char *, const BIGNUM *, MINT *);
102 static void _movem(const char *, const MINT *, MINT *);
103 static void _msub(const char *, const MINT *, const MINT *, MINT *);
104 static char *_mtod(const char *, const MINT *);
105 static char *_mtox(const char *, const MINT *);
106 static void _mult(const char *, const MINT *, const MINT *, MINT *, BN_CTX *);
107 static void _sdiv(const char *, const MINT *, short, MINT *, short *, BN_CTX *);
108 static MINT *_xtom(const char *, const char *);
111 * Report an error from one of the BN_* functions using MPERRX.
114 _bnerr(const char *msg)
117 ERR_load_crypto_strings();
118 MPERRX(("%s: %s", msg, ERR_reason_error_string(ERR_get_error())));
122 * Convert a decimal string to an MINT.
125 _dtom(const char *msg, const char *s)
129 mp = malloc(sizeof(*mp));
135 BN_ERRCHECK(msg, BN_dec2bn(&mp->bn, s));
140 * Compute the greatest common divisor of mp1 and mp2; result goes in rmp.
143 mp_gcd(const MINT *mp1, const MINT *mp2, MINT *rmp)
152 BN_ERRCHECK("gcd", BN_gcd(&b, mp1->bn, mp2->bn, c));
153 _moveb("gcd", &b, rmp);
159 * Make an MINT out of a short integer. Return value must be mfree()'d.
162 _itom(const char *msg, short n)
167 asprintf(&s, "%x", n);
179 return (_itom("itom", n));
183 * Compute rmp=mp1+mp2.
186 _madd(const char *msg, const MINT *mp1, const MINT *mp2, MINT *rmp)
191 BN_ERRCHECK(msg, BN_add(&b, mp1->bn, mp2->bn));
192 _moveb(msg, &b, rmp);
197 mp_madd(const MINT *mp1, const MINT *mp2, MINT *rmp)
200 _madd("madd", mp1, mp2, rmp);
204 * Return -1, 0, or 1 if mp1<mp2, mp1==mp2, or mp1>mp2, respectivley.
207 mp_mcmp(const MINT *mp1, const MINT *mp2)
210 return (BN_cmp(mp1->bn, mp2->bn));
214 * Same as mcmp but compares absolute values.
217 _mcmpa(const char *msg __unused, const MINT *mp1, const MINT *mp2)
220 return (BN_ucmp(mp1->bn, mp2->bn));
224 * Compute qmp=nmp/dmp and rmp=nmp%dmp.
227 _mdiv(const char *msg, const MINT *nmp, const MINT *dmp, MINT *qmp, MINT *rmp,
234 BN_ERRCHECK(msg, BN_div(&q, &r, nmp->bn, dmp->bn, c));
235 _moveb(msg, &q, qmp);
236 _moveb(msg, &r, rmp);
242 mp_mdiv(const MINT *nmp, const MINT *dmp, MINT *qmp, MINT *rmp)
249 _mdiv("mdiv", nmp, dmp, qmp, rmp, c);
254 * Free memory associated with an MINT.
257 _mfree(const char *msg __unused, MINT *mp)
273 * Read an integer from standard input and stick the result in mp.
274 * The input is treated to be in base 10. This must be the silliest
275 * API in existence; why can't the program read in a string and call
276 * xtom()? (Or if base 10 is desires, perhaps dtom() could be
286 line = fgetln(stdin, &linelen);
289 nline = malloc(linelen + 1);
292 memcpy(nline, line, linelen);
293 nline[linelen] = '\0';
294 rmp = _dtom("min", nline);
295 _movem("min", rmp, mp);
301 * Print the value of mp to standard output in base 10. See blurb
302 * above min() for why this is so useless.
305 mp_mout(const MINT *mp)
309 s = _mtod("mout", mp);
315 * Set the value of tmp to the value of smp (i.e., tmp=smp).
318 mp_move(const MINT *smp, MINT *tmp)
321 _movem("move", smp, tmp);
326 * Internal routine to set the value of tmp to that of sbp.
329 _moveb(const char *msg, const BIGNUM *sbp, MINT *tmp)
332 BN_ERRCHECK(msg, BN_copy(tmp->bn, sbp));
336 * Internal routine to set the value of tmp to that of smp.
339 _movem(const char *msg, const MINT *smp, MINT *tmp)
342 BN_ERRCHECK(msg, BN_copy(tmp->bn, smp->bn));
346 * Compute the square root of nmp and put the result in xmp. The
347 * remainder goes in rmp. Should satisfy: rmp=nmp-(xmp*xmp).
349 * Note that the OpenSSL BIGNUM library does not have a square root
350 * function, so this had to be implemented by hand using Newton's
353 * x = (x + (n / x)) / 2
355 * where x is the square root of the positive number n. In the
356 * beginning, x should be a reasonable guess, but the value 1,
357 * although suboptimal, works, too; this is that is used below.
360 mp_msqrt(const MINT *nmp, MINT *xmp, MINT *rmp)
371 tolerance = _itom("msqrt", 1);
372 x = _itom("msqrt", 1);
373 ox = _itom("msqrt", 0);
374 z1 = _itom("msqrt", 0);
375 z2 = _itom("msqrt", 0);
376 z3 = _itom("msqrt", 0);
378 _movem("msqrt", x, ox);
379 _mdiv("msqrt", nmp, x, z1, z2, c);
380 _madd("msqrt", x, z1, z2);
381 _sdiv("msqrt", z2, 2, x, &i, c);
382 _msub("msqrt", ox, x, z3);
383 } while (_mcmpa("msqrt", z3, tolerance) == 1);
384 _movem("msqrt", x, xmp);
385 _mult("msqrt", x, x, z1, c);
386 _msub("msqrt", nmp, z1, z2);
387 _movem("msqrt", z2, rmp);
388 _mfree("msqrt", tolerance);
398 * Compute rmp=mp1-mp2.
401 _msub(const char *msg, const MINT *mp1, const MINT *mp2, MINT *rmp)
406 BN_ERRCHECK(msg, BN_sub(&b, mp1->bn, mp2->bn));
407 _moveb(msg, &b, rmp);
412 mp_msub(const MINT *mp1, const MINT *mp2, MINT *rmp)
415 _msub("msub", mp1, mp2, rmp);
419 * Return a decimal representation of mp. Return value must be
423 _mtod(const char *msg, const MINT *mp)
427 s = BN_bn2dec(mp->bn);
430 asprintf(&s2, "%s", s);
438 * Return a hexadecimal representation of mp. Return value must be
442 _mtox(const char *msg, const MINT *mp)
447 s = BN_bn2hex(mp->bn);
450 asprintf(&s2, "%s", s);
456 * This is a kludge for libgmp compatibility. The latter's
457 * implementation of this function returns lower-case letters,
458 * but BN_bn2hex returns upper-case. Some programs (e.g.,
459 * newkey(1)) are sensitive to this. Although it's probably
460 * their fault, it's nice to be compatible.
463 for (p = s2; p < s2 + len; p++)
470 mp_mtox(const MINT *mp)
473 return (_mtox("mtox", mp));
477 * Compute rmp=mp1*mp2.
480 _mult(const char *msg, const MINT *mp1, const MINT *mp2, MINT *rmp, BN_CTX *c)
485 BN_ERRCHECK(msg, BN_mul(&b, mp1->bn, mp2->bn, c));
486 _moveb(msg, &b, rmp);
491 mp_mult(const MINT *mp1, const MINT *mp2, MINT *rmp)
498 _mult("mult", mp1, mp2, rmp, c);
503 * Compute rmp=(bmp^emp)mod mmp. (Note that here and above rpow() '^'
504 * means 'raise to power', not 'bitwise XOR'.)
507 mp_pow(const MINT *bmp, const MINT *emp, const MINT *mmp, MINT *rmp)
516 BN_ERRCHECK("pow", BN_mod_exp(&b, bmp->bn, emp->bn, mmp->bn, c));
517 _moveb("pow", &b, rmp);
523 * Compute rmp=bmp^e. (See note above pow().)
526 mp_rpow(const MINT *bmp, short e, MINT *rmp)
536 emp = _itom("rpow", e);
537 BN_ERRCHECK("rpow", BN_exp(&b, bmp->bn, emp->bn, c));
538 _moveb("rpow", &b, rmp);
545 * Compute qmp=nmp/d and ro=nmp%d.
548 _sdiv(const char *msg, const MINT *nmp, short d, MINT *qmp, short *ro,
559 BN_ERRCHECK(msg, BN_div(&q, &r, nmp->bn, dmp->bn, c));
560 _moveb(msg, &q, qmp);
561 _moveb(msg, &r, rmp);
564 *ro = strtol(s, NULL, 16);
566 MPERR(("%s underflow or overflow", msg));
575 mp_sdiv(const MINT *nmp, short d, MINT *qmp, short *ro)
582 _sdiv("sdiv", nmp, d, qmp, ro, c);
587 * Convert a hexadecimal string to an MINT.
590 _xtom(const char *msg, const char *s)
594 mp = malloc(sizeof(*mp));
600 BN_ERRCHECK(msg, BN_hex2bn(&mp->bn, s));
605 mp_xtom(const char *s)
608 return (_xtom("xtom", s));