home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume27 / calc-2.9.0 / part16 < prev    next >
Text File  |  1993-12-07  |  60KB  |  1,805 lines

  1. Newsgroups: comp.sources.unix
  2. From: dbell@canb.auug.org.au (David I. Bell)
  3. Subject: v27i143: calc-2.9.0 - arbitrary precision C-like programmable calculator, Part16/19
  4. References: <1.755316719.21314@gw.home.vix.com>
  5. Sender: unix-sources-moderator@gw.home.vix.com
  6. Approved: vixie@gw.home.vix.com
  7.  
  8. Submitted-By: dbell@canb.auug.org.au (David I. Bell)
  9. Posting-Number: Volume 27, Issue 143
  10. Archive-Name: calc-2.9.0/part16
  11.  
  12. #!/bin/sh
  13. # this is part 16 of a multipart archive
  14. # do not concatenate these parts, unpack them in order with /bin/sh
  15. # file calc2.9.0/lib/README continued
  16. #
  17. CurArch=16
  18. if test ! -r s2_seq_.tmp
  19. then echo "Please unpack part 1 first!"
  20.      exit 1; fi
  21. ( read Scheck
  22.   if test "$Scheck" != $CurArch
  23.   then echo "Please unpack part $Scheck next!"
  24.        exit 1;
  25.   else exit 0; fi
  26. ) < s2_seq_.tmp || exit 1
  27. echo "x - Continuing file calc2.9.0/lib/README"
  28. sed 's/^X//' << 'SHAR_EOF' >> calc2.9.0/lib/README
  29. X
  30. X    qpi(epsilon)
  31. X
  32. X    Calculate pi within the specified epsilon using the quartic convergence
  33. X    iteration.
  34. X
  35. X
  36. Xpollard.cal
  37. X
  38. X    factor(N, N, ai, af)
  39. X
  40. X    Factor using Pollard's p-1 method.
  41. X
  42. X
  43. Xpoly.cal    
  44. X
  45. X    Calculate with polynomials of one variable.  There are many functions.
  46. X    Read the documentation in the library file.
  47. X
  48. X
  49. Xpsqrt.cal    
  50. X
  51. X    psqrt(u, p)
  52. X
  53. X    Calculate square roots modulo a prime
  54. X
  55. X
  56. Xquat.cal
  57. X
  58. X    quat(a, b, c, d)
  59. X    quat_print(a)
  60. X    quat_norm(a)
  61. X    quat_abs(a, e)
  62. X    quat_conj(a)
  63. X    quat_add(a, b)
  64. X    quat_sub(a, b)
  65. X    quat_inc(a)
  66. X    quat_dec(a)
  67. X    quat_neg(a)
  68. X    quat_mul(a, b)
  69. X    quat_div(a, b)
  70. X    quat_inv(a)
  71. X    quat_scale(a, b)
  72. X    quat_shift(a, b)
  73. X
  74. X    Calculate using quaternions of the form: a + bi + cj + dk.  In these
  75. X    functions, quaternians are manipulated in the form: s + v, where
  76. X    s is a scalar and v is a vector of size 3.
  77. X
  78. X
  79. Xregress.cal    
  80. X
  81. X    Test the correct execution of the calculator by reading this library file.
  82. X    Errors are reported with '****' mssages, or worse.  :-)
  83. X
  84. X
  85. Xsolve.cal    
  86. X
  87. X    solve(low, high, epsilon)
  88. X
  89. X    Solve the equation f(x) = 0 to within the desired error value for x.
  90. X    The function 'f' must be defined outside of this routine, and the low
  91. X    and high values are guesses which must produce values with opposite signs.
  92. X
  93. X
  94. Xsumsq.cal    
  95. X
  96. X    ss(p)
  97. X
  98. X    Determine the unique two positive integers whose squares sum to the
  99. X    specified prime.  This is always possible for all primes of the form
  100. X    4N+1, and always impossible for primes of the form 4N-1.
  101. X
  102. X
  103. Xsurd.cal    
  104. X
  105. X    surd(a, b)
  106. X    surd_print(a)
  107. X    surd_conj(a)
  108. X    surd_norm(a)
  109. X    surd_value(a, xepsilon)
  110. X    surd_add(a, b)
  111. X    surd_sub(a, b)
  112. X    surd_inc(a)
  113. X    surd_dec(a)
  114. X    surd_neg(a)
  115. X    surd_mul(a, b)
  116. X    surd_square(a)
  117. X    surd_scale(a, b)
  118. X    surd_shift(a, b)
  119. X    surd_div(a, b)
  120. X    surd_inv(a)
  121. X    surd_sgn(a)
  122. X    surd_cmp(a, b)
  123. X    surd_rel(a, b)
  124. X
  125. X    Calculate using quadratic surds of the form: a + b * sqrt(D).
  126. X
  127. X
  128. Xunitfrac.cal
  129. X
  130. X    unitfrac(x)
  131. X
  132. X    Represent a fraction as sum of distinct unit fractions.
  133. X
  134. X
  135. Xvarargs.cal
  136. X
  137. X    sc(a, b, ...)
  138. X
  139. X    Example program to use 'varargs'.  Program to sum the cubes of all 
  140. X    the specified numbers.
  141. SHAR_EOF
  142. echo "File calc2.9.0/lib/README is complete"
  143. chmod 0644 calc2.9.0/lib/README || echo "restore of calc2.9.0/lib/README fails"
  144. set `wc -c calc2.9.0/lib/README`;Sum=$1
  145. if test "$Sum" != "5516"
  146. then echo original size 5516, current size $Sum;fi
  147. echo "x - extracting calc2.9.0/lib/bernoulli.cal (Text)"
  148. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/bernoulli.cal &&
  149. X/*
  150. X * Copyright (c) 1993 David I. Bell
  151. X * Calculate the Nth Bernoulli number B(n).
  152. X * This uses the following symbolic formula to calculate B(n):
  153. X *
  154. X *    (b+1)^(n+1) - b^(n+1) = 0
  155. X *
  156. X * where b is a dummy value, and each power b^i gets replaced by B(i).
  157. X * For example, for n = 3:
  158. X *    (b+1)^4 - b^4 = 0
  159. X *    b^4 + 4*b^3 + 6*b^2 + 4*b + 1 - b^4 = 0
  160. X *    4*b^3 + 6*b^2 + 4*b + 1 = 0
  161. X *    4*B(3) + 6*B(2) + 4*B(1) + 1 = 0
  162. X *    B(3) = -(6*B(2) + 4*B(1) + 1) / 4
  163. X *
  164. X * The combinatorial factors in the expansion of the above formula are
  165. X * calculated interatively, and we use the fact that B(2i+1) = 0 if i > 0.
  166. X * Since all previous B(n)'s are needed to calculate a particular B(n), all
  167. X * values obtained are saved in an array for ease in repeated calculations.
  168. X */
  169. Xstatic Bnmax;
  170. Xstatic mat Bn[1001];
  171. X
  172. X
  173. Xdefine B(n)
  174. X{
  175. X    local    nn, np1, i, sum, mulval, divval, combval;
  176. X
  177. X    if (!isint(n) || (n < 0))
  178. X        quit "Non-negative integer required for Bernoulli";
  179. X
  180. X    if (n == 0)
  181. X        return 1;
  182. X    if (n == 1)
  183. X        return -1/2;
  184. X    if (isodd(n))
  185. X        return 0;
  186. X    if (n > 1000)
  187. X        quit "Very large Bernoulli";
  188. X
  189. X    if (n <= Bnmax)
  190. X        return Bn[n];
  191. X
  192. X    for (nn = Bnmax + 2; nn <= n; nn+=2) {
  193. X        np1 = nn + 1;
  194. X        mulval = np1;
  195. X        divval = 1;
  196. X        combval = 1;
  197. X        sum = 1 - np1 / 2;
  198. X        for (i = 2; i < np1; i+=2) {
  199. X            combval = combval * mulval-- / divval++;
  200. X            combval = combval * mulval-- / divval++;
  201. X            sum += combval * Bn[i];
  202. X        }
  203. X        Bn[nn] = -sum / np1;
  204. X    }
  205. X    Bnmax = n;
  206. X    return Bn[n];
  207. X}
  208. X
  209. Xglobal lib_debug;
  210. Xif (lib_debug >= 0) {
  211. X    print "B(n) defined";
  212. X}
  213. SHAR_EOF
  214. chmod 0644 calc2.9.0/lib/bernoulli.cal || echo "restore of calc2.9.0/lib/bernoulli.cal fails"
  215. set `wc -c calc2.9.0/lib/bernoulli.cal`;Sum=$1
  216. if test "$Sum" != "1492"
  217. then echo original size 1492, current size $Sum;fi
  218. echo "x - extracting calc2.9.0/lib/bigprime.cal (Text)"
  219. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/bigprime.cal &&
  220. X/*
  221. X * Copyright (c) 1993 David I. Bell
  222. X * Permission is granted to use, distribute, or modify this source,
  223. X * provided that this copyright notice remains intact.
  224. X *
  225. X * A prime test, base a, on p*2^x+1 for even x>m.
  226. X */
  227. X
  228. Xdefine bigprime(a, m, p)
  229. X{
  230. X    local n1, n;
  231. X
  232. X    n1 = 2^m * p;
  233. X    for (;;) {
  234. X        m++;
  235. X        n1 += n1;
  236. X        n = n1 + 1;
  237. X        if (isodd(m))
  238. X            continue;
  239. X        print m;
  240. X        if (pmod(a, n1 / 2, n) != n1)
  241. X            continue;
  242. X        if (pmod(a, n1 / p, n) == 1)
  243. X            continue;
  244. X        print "    " : n;
  245. X    }
  246. X}
  247. X
  248. Xglobal lib_debug;
  249. Xif (lib_debug >= 0) {
  250. X    print "bigprime(a, m, p) defined";
  251. X}
  252. SHAR_EOF
  253. chmod 0644 calc2.9.0/lib/bigprime.cal || echo "restore of calc2.9.0/lib/bigprime.cal fails"
  254. set `wc -c calc2.9.0/lib/bigprime.cal`;Sum=$1
  255. if test "$Sum" != "555"
  256. then echo original size 555, current size $Sum;fi
  257. echo "x - extracting calc2.9.0/lib/bindings (Text)"
  258. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/bindings &&
  259. X# Default key bindings for calc line editing functions
  260. X
  261. Xmap    base-map
  262. Xdefault    insert-char
  263. X^@    set-mark
  264. X^A    start-of-line
  265. X^B    backward-char
  266. X^D    delete-char
  267. X^E    end-of-line
  268. X^F    forward-char
  269. X^H    backward-kill-char
  270. X^J    new-line
  271. X^K    kill-line
  272. X^L    refresh-line
  273. X^M    new-line
  274. X^N    forward-history
  275. X^O    save-line
  276. X^P    backward-history
  277. X^R    reverse-search
  278. X^T    swap-chars
  279. X^U    flush-input
  280. X^V    quote-char
  281. X^W    kill-region
  282. X^Y    yank
  283. X^?    backward-kill-char
  284. X^[    ignore-char    esc-map
  285. X
  286. Xmap    esc-map
  287. Xdefault    ignore-char    base-map
  288. XG    start-of-line
  289. XH    backward-history
  290. XP    forward-history
  291. XK    backward-char
  292. XM    forward-char
  293. XO    end-of-line
  294. XS    delete-char
  295. Xg    goto-line
  296. Xs    backward-word
  297. Xt    forward-word
  298. Xd    forward-kill-word
  299. Xu    uppercase-word
  300. Xl    lowercase-word
  301. Xh    list-history
  302. X^[    flush-input
  303. X[    arrow-key
  304. SHAR_EOF
  305. chmod 0644 calc2.9.0/lib/bindings || echo "restore of calc2.9.0/lib/bindings fails"
  306. set `wc -c calc2.9.0/lib/bindings`;Sum=$1
  307. if test "$Sum" != "730"
  308. then echo original size 730, current size $Sum;fi
  309. echo "x - extracting calc2.9.0/lib/chrem.cal (Text)"
  310. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/chrem.cal &&
  311. X/*
  312. X * chrem - Chinese remainder theorem/problem solver
  313. X *
  314. X * When possible, chrem finds solutions for x of a set of congruences
  315. X * of the form:
  316. X *
  317. X *            x = r1 (mod m1)
  318. X *            x = r2 (mod m2)
  319. X *               ...
  320. X *
  321. X * where the residues r1, r2, ... and the moduli m1, m2, ... are
  322. X * given integers.  The Chinese remainder theorem states that if
  323. X * m1, m2, ... are relatively prime in pairs, the above congruences
  324. X * have a unique solution modulo  m1 * m2 * ...   If m1, m2, ...
  325. X * are not relatively prime in pairs, it is possible that no solution
  326. X * exists.  If solutions exist, the general solution is expressible as:
  327. X *
  328. X *                   x = r (mod m)
  329. X *
  330. X * where m = lcm(m1,m2,...), and if m > 0, 0 <= r < m.  This
  331. X * solution may be interpreted as:
  332. X *
  333. X *                  x = r + k * m            [[NOTE 1]]
  334. X *
  335. X * where k is an arbitrary integer.
  336. X *
  337. X ***
  338. X *
  339. X * usage:
  340. X *
  341. X *    chrem(r1,m1 [,r2,m2, ...])
  342. X *
  343. X *         r1, r2, ...      remainder integers or null values
  344. X *         m1, m2, ...      moduli integers
  345. X *
  346. X *    chrem(r_list, [m_list])
  347. X *
  348. X *        r_list    list (r1,r2, ...)
  349. X *        m_list    list (m1,m2, ...)
  350. X *
  351. X *         If m_list is omitted, then 'defaultmlist' is used.
  352. X *        This default list is a global value that may be changed
  353. X *        by the user.  Initially it is the first 8 primes.
  354. X *
  355. X * If a remainder is null(), then the corresponding congruence is 
  356. X * ignored.  This is useful when working with a fixed list of moduli.  
  357. X * 
  358. X * If there are more remainders than moduli, then the later moduli are 
  359. X * ignored.
  360. X *
  361. X * The moduli may be any integers, not necessarily relatively prime in 
  362. X * pairs (as required for the Chinese remainder theorem).  Any moduli 
  363. X * may be zero;  x = r (mod 0) has the meaning of x = r.
  364. X *
  365. X * returns:
  366. X *
  367. X *    If args were integer pairs:
  368. X *
  369. X *          r        ('r' is defined above, see [[NOTE 1]])
  370. X *
  371. X *    If 1 or 2 list args were given:
  372. X *
  373. X *      (r, m)    ('r' and 'm' are defined above, see [[NOTE 1]])
  374. X *
  375. X * NOTE: In all cases, null() is returned if there is no solution.
  376. X *
  377. X ***
  378. X *
  379. X * This function may be used to solve the following historical problems:
  380. X *
  381. X *   Sun-Tsu, 1st century A.D.  
  382. X *
  383. X *    To find a number for which the reminders after division by 3, 5, 7 
  384. X *    are 2, 3, 2, respectively:
  385. X *
  386. X *        chrem(2,3,3,5,2,7) ---> 23
  387. X *
  388. X *   Fibonacci, 13th century A.D.
  389. X *
  390. X *    To find a number divisible by 7 which leaves remainder 1 when 
  391. X *    divided by 2, 3, 4, 5, or 6:
  392. X *
  393. X *
  394. X *        chrem(list(0,1,1,1,1,1),list(7,2,3,4,5,6)) ---> (301,420)
  395. X *
  396. X *    i.e., any value that is 301 mod 420.
  397. X *
  398. X * Written by: Ernest W Bowen <ernie@neumann.une.edu.au>
  399. X * Interface by: Landon Curt Noll <chongo@toad.com>
  400. X */
  401. X
  402. Xstatic defaultmlist = list(2,3,5,7,11,13,17,19); /* The first eight primes */
  403. X
  404. Xdefine chrem()
  405. X{
  406. X    local argc;        /* number of args given */
  407. X    local rlist;    /* reminder list - ri */
  408. X    local mlist;    /* modulus list - mi */
  409. X    local list_args;      /* true => args given are lists, not r1,m1, ... */
  410. X    local m,z,r,y,d,t,x,u,i;
  411. X
  412. X    /* 
  413. X     * parse args 
  414. X     */
  415. X    argc = param(0);
  416. X    if (argc == 0) {
  417. X    quit "usage: chrem(r1,m1 [,r2,m2 ...]) or chrem(r_list, m_list)";
  418. X    }
  419. X    list_args = islist(param(1));
  420. X    if (list_args) {
  421. X    rlist = param(1);
  422. X    mlist = (argc == 1) ? defaultmlist : param(2);
  423. X    if (size(rlist) > size(mlist)) {
  424. X        quit "too many residues";
  425. X    }
  426. X    } else {
  427. X    if (argc % 2 == 1) {
  428. X        quit "odd number integers given";
  429. X    }
  430. X    rlist = list();
  431. X    mlist = list();
  432. X    for (i=1; i <= argc; i+=2) {
  433. X        push(rlist, param(i));
  434. X            push(mlist, param(i+1));
  435. X    }
  436. X    }
  437. X
  438. X    /* 
  439. X     * solve the problem found in rlist & mlist 
  440. X     */
  441. X    m = 1; 
  442. X    z = 0;
  443. X    while (size(rlist)) { 
  444. X    r=pop(rlist); 
  445. X    y=abs(pop(mlist));
  446. X    if (r==null()) 
  447. X        continue;
  448. X    if (m) {
  449. X        if (y) {
  450. X        d = t = z - r;
  451. X        m = lcm(x=m, y);
  452. X        while (d % y) { 
  453. X            u = x; 
  454. X            x %= y; 
  455. X            swap(x,y);
  456. X            if (y==0) 
  457. X            return;
  458. X            z += (t *= -u/y);
  459. X        }
  460. X        } else { 
  461. X        if ((r % m) != (z % m)) 
  462. X            return;
  463. X        else {
  464. X            m = 0; 
  465. X            z = r;
  466. X        }
  467. X        }
  468. X    } else if (((y) && (r % y != z % y)) || (r != z)) 
  469. X        return;
  470. X    }
  471. X    if (m) { 
  472. X    z %= m; 
  473. X    if (z < 0) 
  474. X        z += m;
  475. X    }
  476. X
  477. X    /* 
  478. X     * return information as required 
  479. X     */
  480. X    if (list_args) {
  481. X    return list(z,m);
  482. X    } else {
  483. X    return z;
  484. X    }
  485. X}
  486. X
  487. Xglobal lib_debug;
  488. Xif (lib_debug >= 0) {
  489. X    print "chrem(r1,m1 [,r2,m2 ...]) defined";
  490. X    print "chrem(rlist [,mlist]) defined";
  491. X}
  492. SHAR_EOF
  493. chmod 0644 calc2.9.0/lib/chrem.cal || echo "restore of calc2.9.0/lib/chrem.cal fails"
  494. set `wc -c calc2.9.0/lib/chrem.cal`;Sum=$1
  495. if test "$Sum" != "4346"
  496. then echo original size 4346, current size $Sum;fi
  497. echo "x - extracting calc2.9.0/lib/cryrand.cal (Text)"
  498. sed 's/^X//' << 'SHAR_EOF' > calc2.9.0/lib/cryrand.cal &&
  499. X/*
  500. X * cryrand - cryptographically strong pseudo-random number generator library
  501. X */
  502. X/*
  503. X * Copyright (c) 1993 by Landon Curt Noll.  All Rights Reserved.
  504. X *
  505. X * Permission to use, copy, modify, and distribute this software and
  506. X * its documentation for any purpose and without fee is hereby granted,
  507. X * provided that the above copyright, this permission notice and text
  508. X * this comment, and the disclaimer below appear in all of the following:
  509. X *
  510. X *    supporting documentation
  511. X *    source copies
  512. X *    source works derived from this source
  513. X *    binaries derived from this source or from derived source
  514. X *
  515. X * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  516. X * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
  517. X * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  518. X * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  519. X * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  520. X * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  521. X * PERFORMANCE OF THIS SOFTWARE.
  522. X *
  523. X * chongo was here    /\../\
  524. X */
  525. X
  526. X/*
  527. X * These routines are written in the calc language.  At the time of this
  528. X * notice, calc was at version 1.24.7 (We refer to calc, as in the C 
  529. X * program, not the Emacs subsystem).
  530. X *
  531. X * Calc is available by anonymous ftp from ftp.uu.net (137.39.1.9)
  532. X * under the directory /pub/calc.
  533. X *
  534. X * If you can't get calc any other way, Email a request to my Email
  535. X * address as shown below.
  536. X *
  537. X * Comments, suggestions, bug fixes and questions about these routines 
  538. X * are welcome.  Send Email to the address given below.
  539. X *
  540. X * Happy bit twiddling,
  541. X *
  542. X *            Landon Curt Noll
  543. X *
  544. X *            chongo@toad.com 
  545. X *            ...!{pyramid,sun,uunet}!hoptoad!chongo
  546. X */
  547. X
  548. X/*
  549. X * AN OVERVIEW OF THE FUNCTIONS:
  550. X *
  551. X * This calc library contains several pseudo-random number generators:
  552. X *
  553. X *   additive 55:
  554. X *
  555. X *    a55rand      - external interface to the additive 55 generator
  556. X *    sa55rand  - seed the additive 55 generator
  557. X *
  558. X *    This is a generator based on the additive 55 generator as
  559. X *    described in Knuth's "The Art of Computer Programming -
  560. X *    Seminumerical Algorithms", vol 2, 2nd edition (1981),
  561. X *    Section 3.2.2, page 27, Algorithm A.
  562. X *
  563. X *    The period and other properties of this generator make it very
  564. X *    useful to 'seed' other generators.  
  565. X *
  566. X *    This generator is used by other other generators to produce
  567. X *    various internal values.  In fact, the lower 64 bits of seed
  568. X *    given to other other generators is passed to sa55rand().
  569. X *
  570. X *   shuffle:
  571. X *
  572. X *    shufrand  - generate a pseudo-random value via a shuffle process
  573. X *    sshufrand - seed the shufrand generator
  574. X *    rand      - generate a pseudo-random value over a given range
  575. X *    srand     - seed the random stream generator
  576. X *
  577. X *    This is a generator based on the shuffle generator as described in
  578. X *    Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  579. X *    vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  580. X *
  581. X *    The shuffle generator is fast and serves as a fairly good standard 
  582. X *    pseudo-random generator.
  583. X *
  584. X *    The shuffle generator is feed random values by the additive 55
  585. X *    generator via a55rand().  Calling a55rand() or sa55rand() will
  586. X *    affect the shuffle generator output.
  587. X *
  588. X *    The rand function is really another interface to the shuffle
  589. X *    generator.  Unlike shufrand(), rand() can return a value of any
  590. X *    given size.  The value returned by rand() may be confined to
  591. X *    either a half open [0,a) (0 <= value < a) or closed interval
  592. X *    [a,b] (a <= value <= b).  By default, a 64 bit value is returned.
  593. X *
  594. X *    Calling srand() simply calls sshufrand() with the same seed.
  595. X *
  596. X *   crypto:
  597. X *
  598. X *    cryrand   - produce a cryptographically strong pseudo-random number
  599. X *    scryrand  - seed the crypto generator
  600. X *    random    - produce a cryptographically strong pseudo-random number
  601. X *            over a given range
  602. X *     srandom   - seed random
  603. X *
  604. X *    This generator is described in the papers:
  605. X *
  606. X *        Blum, Blum, and Shub, "Comparison of Two Pseudorandom Number
  607. X *        Generators", in Chaum, D. et. al., "Advances in Cryptology:
  608. X *        Proceedings Crypto 82", pp. 61-79, Plenum Press, 1983.
  609. X *
  610. X *        "Probabilistic Encryption", Journal of Computer & System
  611. X *        Sciences 28, pp. 270-299.
  612. X *
  613. X *    We also refer to this generator as the 'Blum' generator.
  614. X *
  615. X *    This generator is considered 'strong' in that it passes all
  616. X *    polynomial-time statistical tests.  This means that there
  617. X *    is no statistical test, which runs in polynomial time, that 
  618. X *    can distinguish the crypto generator from a truly random source.
  619. X *
  620. X *    The crypto generator is not as fast as most generators, though 
  621. X *    it is not painfully slow either.
  622. X *
  623. X *    One may fully seed this generator via scryrand().  Calling
  624. X *    scryrand() with 1 or 3 arguments will result in the additive
  625. X *    55 generator being seeded with the same seed.  Calling
  626. X *     scryrand() with 4 arguments, where the first argument 
  627. X *    is >= 0 will also result in the additive 55 generator
  628. X *    being seeded with the same seed.
  629. X *
  630. X *    The random() generator is really another interface to the
  631. X *    crypto generator.  Unlike cryrand(), random() can return a
  632. X *    value confined to either a half open (0 <= value < a) or closed
  633. X *    interval (a <= value <= b).  By default, a 64 bit value is
  634. X *    returned.
  635. X *
  636. X *    Calling srandom() simply calls scryrand(seed).  The additive
  637. X *    55 generator will be seeded with the same seed.
  638. X *
  639. X * All generators come already seeded with precomputed initial constants.
  640. X * Thus, it is not required to seed a generator before using it.
  641. X *
  642. X * Using a seed of '0' will reload generators with their initial states.
  643. X * In the case of scryrand(), lengths of -1 must also be supplied.
  644. X *
  645. X *    sa55rand(0)
  646. X *    sshufrand(0)
  647. X *    srand(0)
  648. X *    scryrand(0,-1,-1)
  649. X *    srandom(0)
  650. X *    scryrand(-1,ip,iq,ir)
  651. X *
  652. X * All of the above 'seed 0' calls are fairly fast.  In fact, passing
  653. X * seeding with a non-zero seed, in the above cases, where seed is
  654. X * not excessively large (many bits long), is also reasonably fast.
  655. X * The 4 arg scryrand() call is fairly fast because no checking is
  656. X * performed on the 'ip', 'iq', or 'ir' values.
  657. X *
  658. X * A call of scryrand(seed,len1,len2), with len1,len2 > 4, (3 args)
  659. X * is a somewhat slow as the length args increase.  This type of
  660. X * call selects 2 primes that are used internally by the crypto
  661. X * generator.  A call of scryrand(seed,ip,iq,ir) where seed >= 0
  662. X * is as slow as the 3 arg case.  See scryrand() for more information.
  663. X *
  664. X * A call of scryrand() (no args) may be used to quickly change the 
  665. X * internal state of the crypto and random generators.  Only one major 
  666. X * internal crypto generator value (a quadratic residue) is randomly 
  667. X * selected via the additive 55 generator.  The other 2 major internal 
  668. X * values (the 2 Blum primes) are preserved.  In this form, the additive 
  669. X * 55 is not seeded.
  670. X *
  671. X * Calling scryrand() with 1 or 3 args, or calling srandom() will leave
  672. X * the additive 55 generator in a seeded state as if sa55rand(seed) has
  673. X * been called.  Calling scryrand() with 4 args, where the first arg is 
  674. X * >0 will also leave the additive 55 generator in the same scryrand(seed)
  675. X * state.  Calling scryrand() with no args will not seed the additive
  676. X * 55 generator before or afterwards, however the additive 55 and shuffle
  677. X * generators will be changed as a side effect of that call.
  678. X *
  679. X * The states of all generators (additive 55, shuffle and crypto) can be 
  680. X * saved and restored via the randstate() function.  Saving the state just 
  681. X * after * seeding a generator and restoring it later as a very fast way 
  682. X * to reseed a generator.
  683. X *
  684. X * As a bonus, the function 'nxtprime' is provided to produce a probable
  685. X * prime number.
  686. X *
  687. X * TRUTH IN ADVERTISING:
  688. X *
  689. X * The word 'probable', in reference to the nxtprime() function, is used 
  690. X * because of an extremely extremely small chance that a composite (a
  691. X * non-prime) may be returned.  In no cases will a prime be skipped.  
  692. X * For our purposes, this is sufficient as the chance of returning a 
  693. X * composite is much smaller than the chance that a hardware glitch
  694. X * will cause nxtprime() to return a bogus result.
  695. X *
  696. X * Another "truth in advertising" issue is the use of the term 
  697. X * 'pseudo-random'.  All deterministic generators are pseudo random. 
  698. X * This is opposed to true random generators based on some special
  699. X * physical device.
  700. X *
  701. X * The crypto generator is 'pseudo-random'.  There is no statistical 
  702. X * test, which runs in polynomial time, that can distinguish the crypto 
  703. X * generator from a truly random source.
  704. X *
  705. X * A final "truth in advertising" issue deals with how the magic numbers
  706. X * found in this library were generated.  Detains can be found in the
  707. X * various functions, while a overview can be found in the SOURCE FOR
  708. X * MAGIC NUMBERS section below.
  709. X *
  710. X ****
  711. X *
  712. X * ON THE GENERATORS:
  713. X *
  714. X * The additive 55 generator has a good period, and is fast.  It is
  715. X * reasonable as generators go, though there are better ones available.
  716. X * We use it in seeding the crypto generator as its period and
  717. X * other statistical properties are good enough for our purposes.
  718. X *
  719. X * This shuffle generator has a very good period, and is fast.  It is
  720. X * fairly good as generators go, and is better than the additive 55 
  721. X * generator.  Casual direct use of the shuffle generator may be 
  722. X * acceptable.  Because of this, the interface to the shuffle generator,
  723. X * but not the additive 55 generator, is advertised when this file is 
  724. X * loaded.
  725. X *
  726. X * The shuffle generator functions, shufrand() and rand() use the same
  727. X * seed and tables.  The shuffle generator shuffles the values produced
  728. X * by the additive 55 generator.  Calling or seeding the additive 55
  729. X * generator will affect the output of the shuffle generator.
  730. X *
  731. X * The crypto generator is the best generator in this package.  It
  732. X * produces a cryptographically strong pseudo-random bit sequence.
  733. X * Internally, a fixed number of bits are generated after each
  734. X * generator iteration.  Any unused bits are saved for the next call
  735. X * to the generator.  The crypto generator is not too slow, though
  736. X * seeding the generator from scratch is slow.  Shortcuts and
  737. X * pre-computer seeds have been provided for this reason.  Use of
  738. X * crypto should be more than acceptable for many applications.
  739. X *
  740. X * The crypto seed is in 4 parts, the additive 55 seed (lower 64
  741. X * bits of seed), the shuffle seed (all but the lower 64 bits of
  742. X * seed), and two lengths.  The two lengths specifies the minimum
  743. X * bit size of two primes used internal to the crypto generator.
  744. X * Not specifying the lengths, or using -1 will cause crypto to
  745. X * use the default minimum lengths of 248 and 264 bits, respectively.
  746. X *
  747. X * The random() function just another interface to the crypto
  748. X * generator.  Like rand(), random() provides an interval capability
  749. X * (closed or open) as well as a 64 bit default return value.
  750. X * The random() function as good as crypto, and produces numbers
  751. X * that are equally cryptographically strong.  One may use the
  752. X * seed functions srandom() or scryrand() for either the random()
  753. X * or cryrand() functions.
  754. X *
  755. X * The seed for all of the generators may be of any size.  Only the 
  756. X * lower 64 bits of seed affect the additive 55 generator.  Bits 
  757. X * beyond the lower 64 bits affect the shuffle generators.  Excessively
  758. X * large values of seed will result in increased memory usage as
  759. X * well as a larger seed time for the shuffle and crypto generators.
  760. X * See REGARDING SEEDS below, for more information.
  761. X *
  762. X * One may save and restore the state of all generators via the
  763. X * randstate() function.
  764. X *
  765. X ****
  766. X *
  767. X * REGARDING SEEDS:
  768. X *
  769. X * Because the generators are interrelated, seeding one generator
  770. X * will directly or indirectly affect the other generators.  Seeding
  771. X * the shuffle generator seeds the additive 55 generator.  Seeding
  772. X * the crypto generator seeds the shuffle generator.
  773. X *
  774. X * The seed of '0' implies that a generator should be seeded back
  775. X * to its initial default state.
  776. X *
  777. X * For the moment, seeds < -1 are reserved for future use.  The
  778. X * value of -1 is used as a special indicator to the fourth form 
  779. X * of scryrand(), and it not a real seed.
  780. X *
  781. X * A seed may be of any size.  The additive 55 generator uses only
  782. X * the lower 64 bits, while the shuffle generator uses bytes beyond
  783. X * the lower 64 bits.
  784. X *
  785. X * To help make the generator produced by seed S, significantly
  786. X * different from S+1, seeds are scrambled prior to use.  The
  787. X * function randreseed64() maps [0,2^64) into [0,2^64) in a 1-to-1
  788. X * and onto fashion.
  789. X *
  790. X * The purpose of the randreseed64() is not to add security.  It
  791. X * simply helps remove the human perception of the relationship
  792. X * between the seed and the production of the generator.
  793. X *
  794. X * The randreseed64() process does not reduce the security of the
  795. X * generators.  Every seed is converted into a different unique seed.
  796. X * No seed is ignored or favored.
  797. X *
  798. X * There is no limit on the size of a seed.  On the other hand,
  799. X * extremely large seeds require large tables and long seed times.
  800. X * Using a seed in the range of [2^64, 2^64 * 128!) should be
  801. X * sufficient for most purposes.  An easy way to stay within this
  802. X * range to to use seeds that are between 21 and 215 digits, or 64 to
  803. X * 780 bits long.
  804. X *
  805. X ****
  806. X *
  807. X * SOURCE OF MAGIC NUMBERS:
  808. X *
  809. X * Most of the magic constants used on this library ultimately are
  810. X * based on the Rand book of random numbers.  The Rand book contains
  811. X * 10^6 decimal digits, generated by a physical process.  This book,
  812. X * produced by the Rand corporation in the 1950's is considered
  813. X * a standard against which other generators may be measured.
  814. X *
  815. X * The Rand book of numbers was groups into groups of 20 digits.
  816. X * The first 55 groups < 2^64 were used to initialize add55_init_tbl.
  817. X * The size of 20 digits was used because 2^64 is 20 digits long.
  818. X * The restriction of < 2^64 was used to prevent modulus biasing.
  819. X * (see the note on  modulus biasing in rand()).
  820. X *
  821. X * The additive 55 generator during seeding is used 128 times to help
  822. X * remove the initial seed state from the initial values produced.
  823. X * The loop count of 128 was a power of 2 that permits each of the
  824. X * 55 table entries to be processed at least twice.
  825. X *
  826. X * The function, randreseed64(), uses 4 primes to scramble 64 bits
  827. X * into 64 bits.  These primes were also extracted from the Rand
  828. X * book of numbers.  See sshufrand() for details.
  829. X *
  830. X * The default shuffle table size of 128 entries is the power of 2
  831. X * that is longer than the 100 entries recommended by Knuth for
  832. X * the shuffle algorithm (see the text cited in shufrand()).
  833. X * We use a power of 2 shuffle table length so that the shuffle
  834. X * process can select a table entry from a new additive 55 value
  835. X * by extracting its top most bits.
  836. X *
  837. X * The quadratic residue search performed by cryres() starts at
  838. X * a value that is in the interval [2^sqrpow,n-3), where 2^sqrpow 
  839. X * is the first power of 2 > n^(3/4) and n = p*q.  We look at 1009
  840. X * random numbers in this interval for a quadratic residue.  If
  841. X * none are found, sqrpow is decremented by 1 if sqrpow > 2.
  842. X * In practice, decrementing sqrpow never happens.
  843. X *
  844. X * The use of n^(3/4) insures that the quadratic residue is
  845. X * large, but not too large.  We want to avoid residues that are
  846. X * near the square root of 'n', and are nearly 'n' itself (hence 
  847. X * the n-3 upper limit) as such residues are trivial or semi-trivial.
  848. X *
  849. X * The '1009' trials is simply an attempt to look for a while before
  850. X * picking a new range.  The number '1009' comes from the first 4
  851. X * digits of the rand book of numbers.
  852. X *
  853. X * Keeping sqrpow > 2 means that we do not look for quadratic
  854. X * residues that are below 4.  This is in keeping with the
  855. X * n-3 in the [2^sqrpow,n-3) interval.
  856. X *
  857. X * The final magic numbers: '248' and '264' are the exponents the
  858. X * largest powers of 2 that are < the two default Blum primes 'p'
  859. X * and 'q' used by the crypto generator.  The values of '248' and
  860. X * '264' implies that the product n=p*q > 2^512.  Each iteration
  861. X * of the crypto generator produces log2(log2(n=p*q)) random bits.
  862. X * The crypto generator is the most efficient when n is slightly >
  863. X * 2^(2^b).  The product n > 2^(2^9)) produces 9 bits as efficiently
  864. X * as possible under the crypto generator process.
  865. X *
  866. X * Not being able to factor 'n=p*q' into 'p' and 'q' does not directly
  867. X * improve the crypto generator.  On the other hand, it can't hurt.
  868. X * The two len values differ slightly to avoid factorization attacks 
  869. X * that work on numbers that are a perfect square, or where the two 
  870. X * primes are nearly the same.  I elected to have the sizes differ 
  871. X * by 3% of the product size.  The difference between '248' and 
  872. X * '264', is '16', which is ~3.125% of '512'.  Now 3% of '512' is 
  873. X * '~15.36', and the next largest whole number is '16'.
  874. X *
  875. X * The product n=p*q > 2^512 implies a product if at least 155 digits.
  876. X * A product of two primes that is at least 155 digits is slightly
  877. X * beyond Number Theory and computer power of Nov 1992, though this
  878. X * will likely change in the future.
  879. X *
  880. X * Again, the ability (or lack thereof) to factor 'n=p*q' does not
  881. X * directly relate to the strength of the crypto generator.  We 
  882. X * selected n=p*q > 2^512 mainly because '512 was a power of 2 and 
  883. X * only slightly because it is up in the range where it is difficult
  884. X * to factor.
  885. X *
  886. X ****
  887. X *
  888. X * FOR THE PARANOID:
  889. X *
  890. X * The truly paranoid might suggest that my claims in the MAGIC NUMBERS
  891. X * section are a lie intended to entrap people.  Well they are not, but
  892. X * you need not take my word for it.
  893. X *
  894. X * The random numbers from the Rand book of random numbers can be
  895. X * verified by anyone who obtains the book.  As these numbers were
  896. X * created before I (Landon Curt Noll) was born (you can look up
  897. X * my birth record if you want), I claim to have no possible influence
  898. X * on their generation.
  899. X *
  900. X * There is a very slight chance that the electronic copy of the
  901. X * Rand book that I was given access to differs from the printed text.
  902. X * I am willing to provide access to this electronic copy should
  903. X * anyone wants to compare it to the printed text.
  904. X *
  905. X * One might object to the complexity of the seed scramble/mapping
  906. X * via the randreseed64() function.  The randreseed64() function maps:
  907. X *
  908. X *    1 ==> 4967126403401436567
  909. X *
  910. X * calling srand(1) with the randreseed64() process would be the same
  911. X * as calling srand(4967126403401436567) without it.  No extra security
  912. X * is gained or reduced by using the randreseed64() process.  The meaning
  913. X * of seeds are exchanged, but not lost or favored (used by more than
  914. X * one input seed).
  915. X *
  916. X * One could take issue with my selection of the default sizes '248'
  917. X * and '264'.   As far as I know, 155 digits (512 bits) is beyond the
  918. X * state of the art of Number Theory and Computation as of 01 Sep 92.
  919. X * It will likely be true that 155 digit products of two primes could
  920. X * come within reach in the next few years, but so what?  If you are
  921. X * truly paranoid, why would you want to use the default seed, which
  922. X * is well known?
  923. X *
  924. X * The paranoid today might consider using the lengths of at least '345'
  925. X * and '325' will produce a product of two primes that is 202 digits.
  926. X * (the 2nd and 3rd args of scryrand > 345 & >325 respectively)  Factoring
  927. X * 200+ digit product of two primes is well beyond the current hopes of
  928. X * Number Theory and Computer power, though even this limit may be passed
  929. X * someday.
  930. X *
  931. X * If all the above fails to pacify the truly paranoid, then one may 
  932. X * select by some independent means, 2 Blum primes (primes mod 4 == 3, 
  933. X * p < q), and a quadratic residue if p*q.  Then by calling:
  934. X *
  935. X *    scryrand(-1, p, q, r)
  936. X *
  937. X * and then calling cryrand() or random(), one may bypass all magic
  938. X * numbers and use the pure generator.
  939. X *
  940. X * Note that randstate() may also be used by the truly paranoid.
  941. X * Even though it holds state for the other generators, their states
  942. X * are independent.
  943. X *
  944. X ****
  945. X *
  946. X * GOALS:
  947. X *
  948. X * The goals of this package are:
  949. X *
  950. X *    all magic numbers are explained
  951. X *
  952. X *        I distrust systems with constants (magic numbers) and tables
  953. X *        that have no justification (e.g., DES).  I believe that I have
  954. X *        done my best to justify all of the magic numbers used.
  955. X *
  956. X *     full documentation
  957. X *
  958. X *        You have this source file, plus background publications,
  959. X *        what more could you ask?
  960. X *
  961. X *    large selection of seeds
  962. X *
  963. X *        Seeds are not limited to a small number of bits.  A seed
  964. X *        may be of any size.
  965. X *
  966. X *    the strength of the generators may be tuned to meet the application need
  967. X *
  968. X *        By using the appropriate seed arguments, one may increase
  969. X *        the strength of the generator to suit the need of the
  970. X *        application.  One does not have just a few levels.
  971. X *
  972. X * This calc lib file is intended for demonstration purposes.  Writing
  973. X * a C program (with possible assembly or libmp assist) would produce
  974. X * a faster generator.
  975. X *
  976. X * Even though I have done my best to implement a good system, you still
  977. X * must use these routines your own risk.
  978. X *
  979. X * Share and enjoy!  :-)
  980. X */
  981. X
  982. X
  983. X/*
  984. X * These constants are used by all of the generators in various direct and
  985. X * indirect forms.
  986. X */
  987. Xstatic cry_seed = 0;            /* master seed */
  988. Xstatic cry_mask = 0xffffffffffffffff;    /* 64 bit work mask */
  989. X
  990. X
  991. X/*
  992. X * Initial magic values for the additive 55 generator - used by sa55rand()
  993. X *
  994. X * These values were generated from the Rand book of random numbers.
  995. X * In groups of 20 digits, we took the first 55 groups < 2^64.
  996. X */
  997. Xstatic mat add55_init_tbl[55] = {
  998. X    10097325337652013586,    8422689531964509303,
  999. X    9376707153831131165,    12807999708015736147,
  1000. X    12171768336606574717,    2051656926866574818,
  1001. X    3529647783580834282,    13746700781847540610,
  1002. X    17468509505804776974,    14385537637435099817,
  1003. X    14225685144642756788,    11100020401286074697,
  1004. X    7207317906119690446,    15474452669527079953,
  1005. X    16868487670307112059,    4493524947524633824,
  1006. X    13021248927856520106,    15956600001874392423,
  1007. X    1758753794041921585,    1540354560501451176,
  1008. X    5335129695612719255,    9973334408846123356,
  1009. X    2295368703230757546,    15020099946907494138,
  1010. X    10518216150184876938,    9188200973282539527,
  1011. X    4220863048338987374,    682273982071453295,
  1012. X    7706178130835869910,    4618975533122308420,
  1013. X    397583911260717646,    5686731560708285046,
  1014. X    10123916228549657560,    1304775865627110086,
  1015. X    15501295782182641134,    3061180729620744156,
  1016. X    6958929830512809719,    10850627469959910507,
  1017. X    13499063195307571839,    6410193623982098952,
  1018. X    4111084083850807341,    17719042079595449953,
  1019. X    5462692006544395659,    18288274374963224041,
  1020. X    8337656769629990836,    7477446061798548911,
  1021. X    9815931464890815877,    6913451974267278601,
  1022. X    11883095286301198901,    14974403441045516019,
  1023. X    14210337129134237821,    12883973436502761184,
  1024. X    4285013921797415077,    16435915296724552670,
  1025. X    3742838738308012451
  1026. X};
  1027. X
  1028. X
  1029. X/*
  1030. X * additive 55 tables - used by a55rand() and sa55rand()
  1031. X */
  1032. Xstatic add55_j = 23;        /* the first walking table pointer */
  1033. Xstatic add55_k = 54;        /* the second walking table pointer */
  1034. Xstatic add55_seed64 = 0;    /* lower 64 bits of the reseeded seed */
  1035. Xstatic mat add55_tbl[55];    /* additive 55 state table */
  1036. X
  1037. X
  1038. X/*
  1039. X * cryobj - cryptographic pseudo-random state object
  1040. X */
  1041. Xobj cryobj {                            \
  1042. X    p,        /* first Blum prime (prime 3 mod 4) */        \
  1043. X    q,        /* second Blum prime (prime 3 mod 4) */        \
  1044. X    r,        /* quadratic residue of n=p*q */        \
  1045. X    exp,    /* used in computing crypto good bits */    \
  1046. X    left,    /* bits unused from the last cryrand() call */    \
  1047. X    bitcnt,    /* left contains bitcnt crypto good bits */    \
  1048. X    a55j,    /* 1st additive 55 table pointer */        \
  1049. X    a55k,    /* 2nd additive 55 table pointer */        \
  1050. X    seed,    /* last seed set by sa55rand() or 0 */        \
  1051. X    shufy,    /* Y (previous a55rand output for shuffle) */    \
  1052. X    shufsz,    /* size of the shuffle table */            \
  1053. X    shuftbl,    /* a matrix of shufsz entries */        \
  1054. X    a55tbl    /* additive 55 generator state table */        \
  1055. X}
  1056. X
  1057. X
  1058. X/*
  1059. X * initial cryptographic pseudo-random values - used by scryrand()
  1060. X *
  1061. X * These values are what the crypto generator is initialized with
  1062. X * with this library first read.  These values may be reproduced the
  1063. X * hard way by calling scryrand(0,248,264) or scryrand(0,-1,-1).
  1064. X *
  1065. X * We will build up these values a piece at a time to avoid long lines
  1066. X * that are difficult to send via Email.
  1067. X */
  1068. X/* p, first Blum prime */
  1069. Xstatic cryrand_init_p = 0x1aa9e726a735044;
  1070. Xcryrand_init_p <<= 200;
  1071. Xcryrand_init_p |= 0x73b7457c5297122310880fcbfa8d4e38380a00396d533300bb;
  1072. X/* q, second Blum prime */
  1073. Xstatic cryrand_init_q = 0xa62ee0481aa12059c3;
  1074. Xcryrand_init_q <<= 200;
  1075. Xcryrand_init_q |= 0x79ef44e72ff58ea70cacabbe9d264a0b16db72117d96f77e17;
  1076. X/* quadratic residue of n=p*q */
  1077. Xstatic cryrand_init_r = 0x3d214853f9a5bb4b12f467c9052129a9;
  1078. Xcryrand_init_r <<= 200;
  1079. Xcryrand_init_r |= 0xd215cc6b3c2eae8c7090591b16d8044a886b3c6a58759b1a07;
  1080. Xcryrand_init_r <<= 200;
  1081. Xcryrand_init_r |= 0x2b50a914b42e1b6f9703be86742837c4bc637804c2dc668c5b;
  1082. X
  1083. X/*
  1084. X * cryptographic pseudo-random values - used by cryrand() and scryrand()
  1085. X */
  1086. X/* p, first Blum prime */
  1087. Xstatic cryrand_p = cryrand_init_p;
  1088. X/* q, second Blum prime */
  1089. Xstatic cryrand_q = cryrand_init_q;
  1090. X/* n = p*q */
  1091. Xstatic cryrand_n = cryrand_p*cryrand_q;
  1092. X/* quad residue of n */
  1093. Xstatic cryrand_r = cryrand_init_r;
  1094. X/* this cryrand() running exp used in computing crypto good bits */
  1095. Xstatic cryrand_exp = cryrand_r;
  1096. X/* good crypto bits unused from the last cryrand() call */
  1097. Xstatic cryrand_left = 0;
  1098. X/* the value cryrand_left contains cryrand_bitcnt crypto good bits */
  1099. Xstatic cryrand_bitcnt = 0;
  1100. X
  1101. X
  1102. X/*
  1103. X * shufrand - shuffle generator constants
  1104. X */
  1105. Xstatic shuf_size = 128;            /* entries in shuffle table */
  1106. Xstatic shuf_shift = (64-highbit(shuf_size));    /* shift a55 value to get tbl indx */
  1107. Xstatic shuf_y;                /* Y value (previous output) */
  1108. Xstatic mat shuf_tbl[shuf_size];        /* shuffle state table */
  1109. X
  1110. X
  1111. X/*
  1112. X * products of consecutive primes - used by nxtprime()
  1113. X *
  1114. X * We compute these products now to avoid recalculating them on each call.
  1115. X * These values help weed out numbers that have a prime factor < 1000.
  1116. X */
  1117. Xstatic nxtprime_pfact10 = pfact(10);
  1118. Xstatic nxtprime_pfact100 = pfact(100)/nxtprime_pfact10;
  1119. Xstatic nxtprime_pfact1000 = pfact(1000)/nxtprime_pfact100;
  1120. X
  1121. X
  1122. X/*
  1123. X * a55rand - additive 55 pseudo-random number generator
  1124. X *
  1125. X * returns:
  1126. X *    A number in the half open interval [0,2^64)
  1127. X *
  1128. X * This function implements the additive 55 pseudo-random number generator.
  1129. X *
  1130. X * This is a generator based on the additive 55 generator as described in
  1131. X * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1132. X * vol 2, 2nd edition (1981), Section 3.2.2, page 27, Algorithm A.
  1133. X *
  1134. X * This function is called from the shuffle generator function shufrand().
  1135. X *
  1136. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1137. X *       generate some internal values.
  1138. X *
  1139. X * NOTE: If you are looking for a fast generator and do not need a crypto
  1140. X *      strong generator, you should not use this generator.  Use of
  1141. X *     the shuffle generator functions shufrand() and rand() should
  1142. X *     be considered instead.
  1143. X */
  1144. Xdefine
  1145. Xa55rand()
  1146. X{
  1147. X    local ret;            /* the pseudo-random number to return */
  1148. X
  1149. X    /* generate the next value using the additive 55 generator method */
  1150. X    ret = add55_tbl[add55_k] + add55_tbl[add55_j];
  1151. X    ret &= cry_mask;
  1152. X    add55_tbl[add55_k] = ret;
  1153. X
  1154. X    /* post-process out data with the seed */
  1155. X    ret = xor(ret, add55_seed64);
  1156. X
  1157. X    /* step the pointers */
  1158. X    --add55_j;
  1159. X    if (add55_j < 0) {
  1160. X    add55_j = 54;
  1161. X    }
  1162. X    --add55_k;
  1163. X    if (add55_k < 0) {
  1164. X    add55_k = 54;
  1165. X    }
  1166. X
  1167. X    /* return the new pseudo-random number */
  1168. X    return(ret);
  1169. X}
  1170. X
  1171. X
  1172. X/*
  1173. X * sa55rand - initialize the additive 55 pseudo-random generator
  1174. X *
  1175. X * given:
  1176. X *    seed
  1177. X *
  1178. X * returns:
  1179. X *    old_seed
  1180. X *
  1181. X * This function seeds the additive 55 pseudo-random generator.
  1182. X *
  1183. X * This is a generator based on the additive 55 generator as described in
  1184. X * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1185. X * vol 2, 2nd edition (1981), Section 3.2.2, page 27, Algorithm A.
  1186. X *
  1187. X * Unlike Knuth's description, we will let a seed post process our data.
  1188. X *
  1189. X * We do not apply the seed processing to the additive 55 table
  1190. X * data as this would disturb its pseudo-random generator properties.
  1191. X * Instead, we xor the output with the low 64 bits of seed.
  1192. X *
  1193. X * If seed == 0:
  1194. X *
  1195. X *    This function produces values in exactly the same way
  1196. X *    described by Knuth.
  1197. X *
  1198. X * else:
  1199. X *
  1200. X *    Each value produced is xor-ed by a 64 bit value.  This value
  1201. X *    is the result of randreseed64(rand), which produces a 64
  1202. X *    bit value.
  1203. X *
  1204. X * Anyone comfortable with seed == 0 should also be comfortable with
  1205. X * non-zero seeds.  A non-zero seeded sequence will produce a values
  1206. X * that have the exact same pseudo-random properties as the algorithm
  1207. X * described by Knuth.  I.e., the sequence, while different, is as good
  1208. X * (or bad) as the sequence produced by a seed of 0.
  1209. X *
  1210. X * This function updates both the cry_seed and a55_seed64 global values.
  1211. X *
  1212. X * This function is called from the shuffle generator seed function sshufrand().
  1213. X *
  1214. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1215. X *       generate some internal values.
  1216. X *
  1217. X * NOTE: If you are looking for a fast generator and do not need a crypto
  1218. X *      strong generator, you should not use this generator.  Use of the
  1219. X *     shuffle generator seed functions sshufrand() and srand() should
  1220. X *     be considered instead.
  1221. X */
  1222. Xdefine
  1223. Xsa55rand(seed)
  1224. X{
  1225. X    local oldseed;        /* previous seed */
  1226. X    local junk;            /* discards the first few numbers */
  1227. X    local j;
  1228. X
  1229. X    /* firewall */
  1230. X    if (!isint(seed)) {
  1231. X    quit "bad arg: arg must be an integer";
  1232. X    }
  1233. X    if (seed < 0) {
  1234. X    quit "bad arg: seed < 0 is reserved for future use";
  1235. X    }
  1236. X
  1237. X    /* misc table setup */
  1238. X    oldseed = cry_seed;                /* remember the previous seed */
  1239. X    cry_seed = seed;                /* save the new seed */
  1240. X    add55_tbl = add55_init_tbl;    /* reload the table */
  1241. X    add55_j = 23;               /* reset first walking table pointer */
  1242. X    add55_k = 54;               /* reset second walking table pointer */
  1243. X
  1244. X    /* obtain our 64 bit xor seed */
  1245. X    add55_seed64 = randreseed64(seed);
  1246. X
  1247. X    /* spin the pseudo-random number generator a while */
  1248. X    for (j=0; j < 128; ++j) {
  1249. X    junk = a55rand();
  1250. X    }
  1251. X
  1252. X    /* return the old seed */
  1253. X    return(oldseed);
  1254. X}
  1255. X
  1256. X
  1257. X/*
  1258. X * shufrand - implement the shuffle pseudo-random number generator
  1259. X *
  1260. X * returns:
  1261. X *    A number in the half open interval [0,2^64)
  1262. X *
  1263. X * This function implements the shuffle number generator.
  1264. X *
  1265. X * This is a generator based on the shuffle generator as described in
  1266. X * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1267. X * vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  1268. X *
  1269. X * The function rand() calls this function.
  1270. X *
  1271. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1272. X *       generate some internal values.
  1273. X *
  1274. X * NOTE: If you do not need a crypto strong pseudo-random generator
  1275. X *     this function may very well serve your needs.
  1276. X */
  1277. Xdefine
  1278. Xshufrand()
  1279. X{
  1280. X    local j;        /* table index to replace */
  1281. X
  1282. X    /*
  1283. X     * obtain a new random value
  1284. X     * determine the table entry to shuffle
  1285. X     * shuffle out the value we will return
  1286. X     */
  1287. X    shuf_y = shuf_tbl[j = (shuf_y >> shuf_shift)];
  1288. X
  1289. X    /* shuffle in the new random value */
  1290. X    shuf_tbl[j] = a55rand();
  1291. X
  1292. X    /* return the shuffled out value */
  1293. X    return (shuf_y);
  1294. X}
  1295. X
  1296. X
  1297. X/*
  1298. X * sshufrand - seed the shuffle pseudo-random generator
  1299. X *
  1300. X * given:
  1301. X *    a seed
  1302. X *
  1303. X * returns:
  1304. X *    the previous seed
  1305. X *
  1306. X * This function implements the shuffle number generator.
  1307. X *
  1308. X * This is a generator based on the shuffle generator as described in
  1309. X * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1310. X * vol 2, 2nd edition (1981), Section 3.2.2, page 32, Algorithm B.
  1311. X *
  1312. X * The low 64 bits of seed are used by the additive 55 generator.
  1313. X * See the sa55rand() function for details.  The remaining bits of seed
  1314. X * are used to perform an initial shuffle on the shuffle state table.
  1315. X * The size of the seed also determines the size of the shuffle table.
  1316. X *
  1317. X * The shuffle table size is always a power of 2, and is at least 128
  1318. X * entries long.  Let the table size be:
  1319. X *
  1320. X *    shuf_size = 2^shuf_pow
  1321. X *
  1322. X * The number of ways one could shuffle that table is:
  1323. X *
  1324. X *    (2^shuf_pow)!
  1325. X *
  1326. X * We select the smallest 'shuf_pow' (and thus the size of the shuffle table)
  1327. X * such that the following are true:
  1328. X *
  1329. X *    (2^shuf_pow)! >= (seed / 2^64)    and    2^shuf_pow >= 128
  1330. X *
  1331. X * Given that we now have the table size of 'shuf_size', we must go about
  1332. X * loading the table and shuffling it.
  1333. X *
  1334. X * Loading is easy, we will generate random values via the additive 55
  1335. X * generator (a55rand()) and load them into successive entries.
  1336. X *
  1337. X * We enumerate the (2^shuf_pow)! values via:
  1338. X *
  1339. X *    shuf_seed = 2*(U[2] + 3*(U[3] + 4*(U[4] + ...
  1340. X *              + (U[shuf_pow-1]*(shuf_pow-1)) ... )))
  1341. X *    0 <= U[j] < j
  1342. X *
  1343. X * We swap the swap table entries shuf_tbl[U[j]] & shuf_tbl[j-1] for all
  1344. X * 1 < j < shuf_pow.
  1345. X *
  1346. X * We will convert 'seed / 2^64' into shuf_seed, by applying the 64 bit
  1347. X * scramble function on 64 bit chunks of 'seed / 2^64'.
  1348. X *
  1349. X * The function srand() calls this function.
  1350. X *
  1351. X * There is no limit on the size of a seed.  On the other hand,
  1352. X * extremely large seeds require large tables and long seed times.
  1353. X * Using a seed in the range of [2^64, 2^64 * 128!) should be
  1354. X * sufficient for most purposes.  An easy way to stay within this
  1355. X * range to to use seeds that are between 21 and 215 digits long, or
  1356. X * 64 to 780 bits long.
  1357. X *
  1358. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1359. X *       generate some internal values.
  1360. X *
  1361. X * NOTE: If you do not need a crypto strong pseudo-random generator
  1362. X *     this function may very well serve your needs.
  1363. X */
  1364. Xdefine
  1365. Xsshufrand(seed)
  1366. X{
  1367. X    local shuf_pow;        /* power of two - log2(shuf_size) */
  1368. X    local shuf_seed;        /* seed bits beyond low 64 bits */
  1369. X    local oldseed;        /* previous seed */
  1370. X    local shift;        /* shift factor to access 64 bit chunks */
  1371. X    local swap_indx;        /* what to swap shuf_tbl[0] with */
  1372. X    local rval;            /* random value form additive 55 generator */
  1373. X    local j;
  1374. X
  1375. X    /* firewall */
  1376. X    if (!isint(seed)) {
  1377. X    quit "bad arg: seed must be an integer";
  1378. X    }
  1379. X    if (seed < 0) {
  1380. X    quit "bad arg: seed < 0 is reserved for future use";
  1381. X    }
  1382. X
  1383. X    /*
  1384. X     * seed the additive 55 generator
  1385. X     */
  1386. X    oldseed = sa55rand(seed);
  1387. X
  1388. X    /*
  1389. X     * form the shuffle table size and constants
  1390. X     */
  1391. X    shuf_seed = seed >> 64;
  1392. X    for (shuf_pow = 7; shuf_seed > (j=fact(1<<(shuf_pow))) && shuf_pow < 64; \
  1393. X     ++shuf_pow) {
  1394. X    }
  1395. X    shuf_size = (1 << shuf_pow);
  1396. X    shuf_shift = 64 - shuf_pow;
  1397. X    /* reallocate the shuffle table */
  1398. X    mat shuf_tbl[shuf_size];
  1399. X
  1400. X    /*
  1401. X     * scramble the seed above the low 64 bits
  1402. X     */
  1403. X    if (shuf_seed > 0) {
  1404. X    j = 0;
  1405. X    for (shift=0; shift < highbit(shuf_seed)+1; shift += 64) {
  1406. X        j |= (randreseed64(shuf_seed >> shift) << shift);
  1407. X    }
  1408. X    shuf_seed = j;
  1409. X    }
  1410. X
  1411. X    /*
  1412. X     * load the shuffle table
  1413. X     */
  1414. X    for (j=0; j < shuf_size; ++j) {
  1415. X    shuf_tbl[j] = a55rand();
  1416. X    }
  1417. X    shuf_y = a55rand();        /* get the next Y value */
  1418. X
  1419. X    /*
  1420. X     * We will shuffle based the process outlined in:
  1421. X     *
  1422. X     * Knuth's "The Art of Computer Programming - Seminumerical Algorithms",
  1423. X     * vol 2, 2nd edition (1981), Section 3.4.2, page 139, Algorithm P.
  1424. X     *
  1425. X     * Here, we will let j run over the range [0,shuf_size) instead of
  1426. X     * [shuf_size,0) as outlined in algorithm P.  We will also generate
  1427. X     * U values from shuf_seed.
  1428. X     */
  1429. X    j = 0;
  1430. X    while (shuf_seed > 0 && ++j < shuf_size) {
  1431. X
  1432. X    /* determine what index we will swap with the '0' index */
  1433. X    quomod(shuf_seed, (j+1), shuf_seed, swap_indx);
  1434. X
  1435. X    /* swap table entries, if needed */
  1436. X    if (swap_indx != j) {
  1437. X        swap(shuf_tbl[j], shuf_tbl[swap_indx]);
  1438. X    }
  1439. X    }
  1440. X
  1441. X    /*
  1442. X     * run the generator for twice the table size
  1443. X     */
  1444. X    for (j=0; j < shuf_size*2; ++j) {
  1445. X    rval = shufrand();
  1446. X    }
  1447. X
  1448. X    /* return the old seed */
  1449. X    return (oldseed);
  1450. X}
  1451. X
  1452. X
  1453. X/*
  1454. X * rand - generate a pseudo-random value over a given range via additive 55
  1455. X *
  1456. X * usage:
  1457. X *    rand()         - generate a pseudo-random integer >=0 and < 2^64
  1458. X *    rand(a)     - generate a pseudo-random integer >=0 and < a
  1459. X *    rand(a,b)    - generate a pseudo-random integer >=a and <= b
  1460. X *
  1461. X * returns:
  1462. X *    a large pseudo-random integer over a give range (see usage)
  1463. X *
  1464. X * When no arguments are given, a pseudo-random number in the half open
  1465. X * interval [0,2^64) is produced.  This form is identical to calling 
  1466. X * shufrand().
  1467. X *
  1468. X * When 1 argument is given, a pseudo-random number in the half open interval
  1469. X * [0,a) is produced.
  1470. X *
  1471. X * When 2 arguments are given, a pseudo-random number in the closed interval
  1472. X * [a,b] is produced.
  1473. X *
  1474. X * The input values a and b, if given, must be integers.
  1475. X *
  1476. X * This generator is simply a different interface to the shuffle generator.
  1477. X * calling shufrand(), or seeding via sshufrand() will affect the output
  1478. X * of this function.
  1479. X *
  1480. X * NOTE: Unlike cryrand(), this function does not preserve unused bits for
  1481. X *     use by the next function call.
  1482. X *
  1483. X * NOTE: The Un*x rand() function returns only 16 bit or 31 bits, while we
  1484. X *     return a number of any given size (default is 64 bits).
  1485. X *
  1486. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1487. X *       generate some internal values.
  1488. X *
  1489. X * NOTE: If you do not need a crypto strong pseudo-random generator
  1490. X *     this function may very well serve your needs.
  1491. X */
  1492. Xdefine
  1493. Xrand(a,b)
  1494. X{
  1495. X    local range;        /* we must generate [0,range) first */
  1496. X    local offset;        /* what to add to get a adjusted range */
  1497. X    local ret;            /* pseudo-random value */
  1498. X    local fullwords;        /* number of full 64 bit chunks in ret */
  1499. X    local finalmask;        /* mask of bits in final chunk of range */
  1500. X    local j;
  1501. X
  1502. X    /*
  1503. X     * setup and special cases
  1504. X     */
  1505. X    /* deal with the rand() case */
  1506. X    if (isnull(a) && isnull(b)) {
  1507. X    /* no args means same range as additive 55 generator */
  1508. X    return(a55rand());
  1509. X    }
  1510. X    /* firewall - args, if given must be in integers */
  1511. X    if (!isint(a) || (!isnull(b) && !isint(b))) {
  1512. X    quit "bad args: args, if given, must be integers";
  1513. X    }
  1514. X    /* convert rand(x) into rand(0,x-1) */
  1515. X    if (isnull(b)) {
  1516. X    /* convert call into a closed interval */
  1517. X    b = a-1;
  1518. X    a = 0;
  1519. X    /* firewall - rand(0) should act like rand(0,0) */
  1520. X    if (b == -1) {
  1521. X        return(0);
  1522. X    }
  1523. X    }
  1524. X    /* determine the range and offset */
  1525. X    if (a >= b) {
  1526. X    /* deal with the case of rand(a,a) */
  1527. X    if (a == b) {
  1528. X        /* not very random, but it is true! */
  1529. X        return(a);
  1530. X    }
  1531. X    range = a-b+1;
  1532. X    offset = b;
  1533. X    } else {
  1534. X    /* convert rand(a,b), where a < b into rand(b,a) */
  1535. X    range = b-a+1;
  1536. X    offset = a;
  1537. X    }
  1538. X    /*
  1539. X     * At this point, we seek a pseudo-random number [0,range) to which
  1540. X     * we will add offset to produce a number [offset,range+offset).
  1541. X     */
  1542. X    fullwords = highbit(range-1)//64;
  1543. X    finalmask = (1 << (1+(highbit(range-1)%64)))-1;
  1544. X
  1545. X    /*
  1546. X     * loop until we get a value that is in range
  1547. X     *
  1548. X     * A note in modulus biasing:
  1549. X     *
  1550. X     * We will not fall into the trap of thinking that we can simply take
  1551. X     * a value mod 'range'.  Consider the case where 'range' is '80'
  1552. X     * and we are given pseudo-random numbers [0,100).  If we took them
  1553. X     * mod 80, then the numbers [0,20) would be produced more frequently
  1554. X     * because the numbers [81,100) mod 80 wrap back into [0,20).
  1555. X     */
  1556. X    do {
  1557. X    /* load up all lower full 64 bit chunks with pseudo-random bits */
  1558. X    ret = 0;
  1559. X    for (j=0; j < fullwords; ++j) {
  1560. X        ret = (ret << 64) + shufrand();
  1561. X    }
  1562. X
  1563. X    /* load the highest chunk */
  1564. X    ret <<= (highbit(finalmask)+1);
  1565. X    ret |= (shufrand() >> (64-highbit(finalmask)-1));
  1566. X    } while (ret >= range);
  1567. X
  1568. X    /*
  1569. X     * return the adjusted range value
  1570. X     */
  1571. X    return(ret+offset);
  1572. X}
  1573. X
  1574. X
  1575. X/*
  1576. X * srand - seed the pseudo-random additive 55 generator
  1577. X *
  1578. X * input:
  1579. X *    seed
  1580. X *
  1581. X * returns:
  1582. X *    old_seed
  1583. X *
  1584. X * This function actually seeds the shuffle generator (and indirectly
  1585. X * the additive 55 generator used by rand() and a55rand().
  1586. X *
  1587. X * See sshufrand() and sa55rand() for information about a seed.
  1588. X *
  1589. X * There is no limit on the size of a seed.  On the other hand,
  1590. X * extremely large seeds require large tables and long seed times.
  1591. X * Using a seed in the range of [2^64, 2^64 * 128!) should be
  1592. X * sufficient for most purposes.  An easy way to stay within this
  1593. X * range to to use seeds that are between 21 and 215 digits long, or
  1594. X * 64 to 780 bits long.
  1595. X *
  1596. X * NOTE: This is NOT Blum's method.  This is used by Blum's method to
  1597. X *       generate some internal values.
  1598. X *
  1599. X * NOTE: If you do not need a crypto strong pseudo-random generator
  1600. X *     this function may very well serve your needs.
  1601. X */
  1602. Xdefine
  1603. Xsrand(seed)
  1604. X{
  1605. X    if (!isint(seed)) {
  1606. X    quit "bad arg: seed must be an integer";
  1607. X    }
  1608. X    if (seed < 0) {
  1609. X    quit "bad arg: seed < 0 is reserved for future use";
  1610. X    }
  1611. X    return(sshufrand(seed));
  1612. X}
  1613. X
  1614. X
  1615. X/*
  1616. X * cryrand - cryptographically strong pseudo-random number generator
  1617. X *
  1618. X * usage:
  1619. X *    cryrand(len)
  1620. X *
  1621. X * given:
  1622. X *    len        number of pseudo-random bits to generate
  1623. X *
  1624. X * returns:
  1625. X *    a cryptographically strong pseudo-random number of len bits
  1626. X *
  1627. X * Internally, bits are produced log2(log2(n=p*q)) at a time.  If a
  1628. X * call to this function does not exhaust all of the collected bits,
  1629. X * the unused bits will be saved away and used at a later call.
  1630. X * Setting the seed via scryrand() or srandom() will clear out all
  1631. X * unused bits.  Thus:
  1632. X *
  1633. X *    scryrand(0);            <-- restore generator to initial state
  1634. X *    cryrand(16);            <-- 16 bits
  1635. X *
  1636. X * will produce the same value as:
  1637. X *
  1638. X *    scryrand(0);            <-- restore generator to initial state
  1639. X *    cryrand(4)<<12 | cryrand(12);    <-- 4+12 = 16 bits
  1640. X *
  1641. X * and will produce the same value as:
  1642. X *
  1643. X *    scryrand(0);            <-- restore generator to initial state
  1644. X *    cryrand(3)<<13 | cryrand(7)<<6 | cryrand(6);    <-- 3+7+6 = 16 bits
  1645. X *
  1646. X * The crypto generator is not as fast as most generators, though it is not 
  1647. X * painfully slow either.
  1648. X *
  1649. X * NOTE: This function is the Blum cryptographically strong
  1650. X *     pseudo-random number generator!
  1651. X */
  1652. Xdefine
  1653. Xcryrand(len)
  1654. X{
  1655. X    local goodbits;    /* the number of good bits generated each pass */
  1656. X    local goodmask;    /* mask for the low order good bits */
  1657. X    local randval;    /* pseudo-random value being generated */
  1658. X
  1659. X    /*
  1660. X     * firewall
  1661. X     */
  1662. X    if (!isint(len) || len < 1) {
  1663. X    quit "bad arg: len must be an integer > 0";
  1664. X    }
  1665. X
  1666. X    /*
  1667. X     * Determine how many bits may be generated each pass.
  1668. X     *
  1669. X     * The result by Alexi et. al., says that the log2(log2(n=p*q))
  1670. X     * least significant bits are secure, where log2(x) is log base 2.
  1671. X     */
  1672. X    goodbits = highbit(highbit(cryrand_n));
  1673. X    goodmask = (1 << goodbits)-1;
  1674. X
  1675. X    /*
  1676. X     * If we have bits left over from the previous call, collect
  1677. X     * them now.
  1678. X     */
  1679. X    if (cryrand_bitcnt > 0) {
  1680. X
  1681. X    /* case where the left over bits are enough for this call */
  1682. X    if (len <= cryrand_bitcnt) {
  1683. X
  1684. X        /* we need only len bits */
  1685. X        randval = (cryrand_left >> (cryrand_bitcnt-len));
  1686. X
  1687. X        /* save the unused bits for later use */
  1688. X        cryrand_left &= ((1 << (cryrand_bitcnt-len))-1);
  1689. X
  1690. X        /* save away the number of bits that we will not use */
  1691. X        cryrand_bitcnt -= len;
  1692. X
  1693. X        /* return our complete result */
  1694. X        return(randval);
  1695. X
  1696. X    /* case where we need more than just the left over bits */
  1697. X    } else {
  1698. X
  1699. X        /* clear out the number of left over bits */
  1700. X        len -= cryrand_bitcnt;
  1701. X        cryrand_bitcnt = 0;
  1702. X
  1703. X        /* collect all of the left over bits for now */
  1704. X        randval = cryrand_left;
  1705. X    }
  1706. X
  1707. X    /* case where we have no previously left over bits */
  1708. X    } else {
  1709. X    randval = 0;
  1710. X    }
  1711. X
  1712. X    /*
  1713. X     * Pump out len cryptographically strong pseudo-random bits,
  1714. X     * 'goodbits' at a time using Blum's process.
  1715. X     */
  1716. X    while (len >= goodbits) {
  1717. X
  1718. X    /* generate the bits */
  1719. X    cryrand_exp = (cryrand_exp^2) % cryrand_n;
  1720. X    randval <<= goodbits;
  1721. X    randval |= (cryrand_exp & goodmask);
  1722. X
  1723. X    /* reduce the need count */
  1724. X    len -= goodbits;
  1725. X    }
  1726. X
  1727. X    /* if needed, save the unused bits for later use */
  1728. X    if (len > 0) {
  1729. X
  1730. X    /* generate the bits */
  1731. X    cryrand_exp = (cryrand_exp^2) % cryrand_n;
  1732. X    randval <<= len;
  1733. X    randval |= ((cryrand_exp&goodmask) >> (goodbits-len));
  1734. X
  1735. X    /* save away the number of bits that we will not use */
  1736. X    cryrand_left = cryrand_exp & ((1 << (goodbits-len))-1);
  1737. X    cryrand_bitcnt = goodbits-len;
  1738. X    }
  1739. X
  1740. X    /*
  1741. X     * return our pseudo-random bits
  1742. X     */
  1743. X     return(randval);
  1744. X}
  1745. X
  1746. X
  1747. X/*
  1748. X * scryrand - seed the cryptographically strong pseudo-random number generator
  1749. X *
  1750. X * usage:
  1751. X *    scryrand(seed)
  1752. X *    scryrand()
  1753. X *    scryrand(seed,len1,len2)
  1754. X *    scryrand(seed,ip,iq,ir)
  1755. X *
  1756. X * input:
  1757. X *    [seed        pseudo-random seed
  1758. X *    [len1 len2]    minimum bit length of the Blum primes 'p' and 'q'
  1759. X *            -1 => default lengths
  1760. X *    [ip iq ir]    Initial search values for Blum primes 'p', 'q' and 
  1761. X *            a quadratic residue 'r'
  1762. X *
  1763. X * returns:
  1764. X *    the previous seed
  1765. X *
  1766. X *
  1767. X * This function will seed and setup the generator needed to produce
  1768. X * cryptographically strong pseudo-random numbers.  See the function
  1769. X * a55rand() and sshufrand() for information about how 'seed' works.
  1770. X *
  1771. X * The first form of this function are fairly fast if the seed is not
  1772. X * excessively large.  The second form is also fairly fast if the internal
  1773. X * primes are not too large.  The third form, can take a long time to call.
  1774. X * (see below)   The fourth form, if the 'seed' arg is not -1, can take 
  1775. X * as long as the third form to call.  If the fourth form is called with
  1776. X * a 'seed' arg of -1, then it is fairly fast.
  1777. X *
  1778. X * Calling scryrand() with 1 or 3 args (first and third forms), or
  1779. X * calling srandom(), or calling scryrand() with 4 args with the first
  1780. X * arg >0, will leave the shuffle generator in a seeded state as if 
  1781. X * sshufrand(seed) has been called.  
  1782. X *
  1783. X * Calling scryrand() with no args will not seed the shuffle generator, 
  1784. X * before or afterwards, however the shuffle generator will have been 
  1785. X * changed as a side effect of that call.
  1786. X *
  1787. X * Calling scryrand() with 4 args where the first arg is 0 or '-1'
  1788. X * will not change the other generators.
  1789. X *
  1790. X *
  1791. X * First form of call:  scryrand(seed)
  1792. X *
  1793. X * The first form of this function will seed the shuffle generator
  1794. X * (via srand).  The default precomputed constants will be used.
  1795. X *
  1796. X *
  1797. X * Second form of call:  scryrand()
  1798. X *
  1799. X * Only a new quadratic residue of n=p*q is recomputed.  The previous prime
  1800. SHAR_EOF
  1801. echo "End of part 16"
  1802. echo "File calc2.9.0/lib/cryrand.cal is continued in part 17"
  1803. echo "17" > s2_seq_.tmp
  1804. exit 0
  1805.