factor.c revision 1.36 1 1.36 christos /* $NetBSD: factor.c,v 1.36 2020/10/11 17:18:34 christos Exp $ */
2 1.1 cgd /*
3 1.5 cgd * Copyright (c) 1989, 1993
4 1.5 cgd * The Regents of the University of California. All rights reserved.
5 1.1 cgd *
6 1.1 cgd * This code is derived from software contributed to Berkeley by
7 1.1 cgd * Landon Curt Noll.
8 1.1 cgd *
9 1.1 cgd * Redistribution and use in source and binary forms, with or without
10 1.1 cgd * modification, are permitted provided that the following conditions
11 1.1 cgd * are met:
12 1.1 cgd * 1. Redistributions of source code must retain the above copyright
13 1.1 cgd * notice, this list of conditions and the following disclaimer.
14 1.1 cgd * 2. Redistributions in binary form must reproduce the above copyright
15 1.1 cgd * notice, this list of conditions and the following disclaimer in the
16 1.1 cgd * documentation and/or other materials provided with the distribution.
17 1.14 agc * 3. Neither the name of the University nor the names of its contributors
18 1.1 cgd * may be used to endorse or promote products derived from this software
19 1.1 cgd * without specific prior written permission.
20 1.1 cgd *
21 1.1 cgd * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 1.1 cgd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 1.1 cgd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 1.1 cgd * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 1.1 cgd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 1.1 cgd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 1.1 cgd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 1.1 cgd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 1.1 cgd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 1.1 cgd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 1.1 cgd * SUCH DAMAGE.
32 1.1 cgd */
33 1.1 cgd
34 1.30 christos #ifndef lint
35 1.7 lukem #include <sys/cdefs.h>
36 1.30 christos #ifdef __COPYRIGHT
37 1.18 lukem __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
38 1.30 christos The Regents of the University of California. All rights reserved.");
39 1.30 christos #endif
40 1.30 christos #ifdef __SCCSID
41 1.30 christos __SCCSID("@(#)factor.c 8.4 (Berkeley) 5/4/95");
42 1.30 christos #endif
43 1.30 christos #ifdef __RCSID
44 1.36 christos __RCSID("$NetBSD: factor.c,v 1.36 2020/10/11 17:18:34 christos Exp $");
45 1.30 christos #endif
46 1.30 christos #ifdef __FBSDID
47 1.30 christos __FBSDID("$FreeBSD: head/usr.bin/factor/factor.c 356666 2020-01-12 20:25:11Z gad $");
48 1.5 cgd #endif
49 1.1 cgd #endif /* not lint */
50 1.1 cgd
51 1.1 cgd /*
52 1.1 cgd * factor - factor a number into primes
53 1.1 cgd *
54 1.30 christos * By: Landon Curt Noll chongo (at) toad.com, ...!{sun,tolsoft}!hoptoad!chongo
55 1.30 christos *
56 1.30 christos * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
57 1.1 cgd *
58 1.1 cgd * usage:
59 1.30 christos * factor [-hx] [number] ...
60 1.1 cgd *
61 1.30 christos * The form of the output is:
62 1.1 cgd *
63 1.1 cgd * number: factor1 factor1 factor2 factor3 factor3 factor3 ...
64 1.1 cgd *
65 1.16 rillig * where factor1 <= factor2 <= factor3 <= ...
66 1.1 cgd *
67 1.28 rin * If the -h flag is specified, the output is in "human-readable" format.
68 1.28 rin * Duplicate factors are printed in the form of x^n.
69 1.28 rin *
70 1.30 christos * If the -x flag is specified numbers are printed in hex.
71 1.30 christos *
72 1.28 rin * If no number args are given, the list of numbers are read from stdin.
73 1.30 christos * If no args are given, the list of numbers are read from stdin.
74 1.1 cgd */
75 1.1 cgd
76 1.10 simonb #include <ctype.h>
77 1.5 cgd #include <err.h>
78 1.5 cgd #include <errno.h>
79 1.30 christos #include <inttypes.h>
80 1.5 cgd #include <limits.h>
81 1.30 christos #include <stdbool.h>
82 1.1 cgd #include <stdio.h>
83 1.5 cgd #include <stdlib.h>
84 1.6 tls #include <unistd.h>
85 1.30 christos
86 1.30 christos #include "primes.h"
87 1.5 cgd
88 1.11 itojun #ifdef HAVE_OPENSSL
89 1.30 christos
90 1.10 simonb #include <openssl/bn.h>
91 1.30 christos
92 1.30 christos #define PRIME_CHECKS 5
93 1.30 christos
94 1.36 christos /* print factors for big numbers */
95 1.36 christos static void pollard_pminus1(BIGNUM *, int, int);
96 1.30 christos
97 1.11 itojun #else
98 1.30 christos
99 1.11 itojun typedef long BIGNUM;
100 1.11 itojun typedef u_long BN_ULONG;
101 1.30 christos
102 1.30 christos #define BN_CTX int
103 1.30 christos #define BN_CTX_new() NULL
104 1.34 christos #define BN_new() calloc(sizeof(BIGNUM), 1)
105 1.34 christos #define BN_free(a) free(a)
106 1.34 christos
107 1.34 christos #define BN_copy(a, b) *(a) = *(b)
108 1.34 christos #define BN_cmp(a, b) (*(a) - *(b))
109 1.13 simonb #define BN_is_zero(v) (*(v) == 0)
110 1.13 simonb #define BN_is_one(v) (*(v) == 1)
111 1.11 itojun #define BN_mod_word(a, b) (*(a) % (b))
112 1.10 simonb
113 1.34 christos static BIGNUM *BN_dup(const BIGNUM *);
114 1.30 christos static int BN_dec2bn(BIGNUM **, const char *);
115 1.30 christos static int BN_hex2bn(BIGNUM **, const char *);
116 1.30 christos static BN_ULONG BN_div_word(BIGNUM *, BN_ULONG);
117 1.30 christos static void BN_print_fp(FILE *, const BIGNUM *);
118 1.1 cgd
119 1.21 drochner #endif
120 1.1 cgd
121 1.30 christos static void BN_print_dec_fp(FILE *, const BIGNUM *);
122 1.30 christos static void convert_str2bn(BIGNUM **, char *);
123 1.30 christos static bool is_hex_str(char *);
124 1.30 christos static void pr_fact(BIGNUM *, int, int); /* print factors of a value */
125 1.36 christos static void pr_print(BIGNUM *, int, int); /* print a prime */
126 1.32 tnn static void usage(void) __dead;
127 1.10 simonb
128 1.30 christos static BN_CTX *ctx; /* just use a global context */
129 1.1 cgd
130 1.5 cgd int
131 1.10 simonb main(int argc, char *argv[])
132 1.1 cgd {
133 1.10 simonb BIGNUM *val;
134 1.30 christos int ch, hflag, xflag;
135 1.10 simonb char *p, buf[LINE_MAX]; /* > max number of digits. */
136 1.10 simonb
137 1.30 christos hflag = xflag = 0;
138 1.12 simonb ctx = BN_CTX_new();
139 1.10 simonb val = BN_new();
140 1.10 simonb if (val == NULL)
141 1.10 simonb errx(1, "can't initialise bignum");
142 1.5 cgd
143 1.30 christos while ((ch = getopt(argc, argv, "hx")) != -1)
144 1.5 cgd switch (ch) {
145 1.28 rin case 'h':
146 1.30 christos hflag++;
147 1.30 christos break;
148 1.30 christos case 'x':
149 1.30 christos xflag++;
150 1.28 rin break;
151 1.5 cgd case '?':
152 1.5 cgd default:
153 1.5 cgd usage();
154 1.5 cgd }
155 1.5 cgd argc -= optind;
156 1.5 cgd argv += optind;
157 1.5 cgd
158 1.5 cgd /* No args supplied, read numbers from stdin. */
159 1.5 cgd if (argc == 0)
160 1.5 cgd for (;;) {
161 1.5 cgd if (fgets(buf, sizeof(buf), stdin) == NULL) {
162 1.5 cgd if (ferror(stdin))
163 1.5 cgd err(1, "stdin");
164 1.5 cgd exit (0);
165 1.5 cgd }
166 1.23 tnozaki for (p = buf; isblank((unsigned char)*p); ++p);
167 1.5 cgd if (*p == '\n' || *p == '\0')
168 1.5 cgd continue;
169 1.30 christos convert_str2bn(&val, p);
170 1.30 christos pr_fact(val, hflag, xflag);
171 1.5 cgd }
172 1.5 cgd /* Factor the arguments. */
173 1.5 cgd else
174 1.30 christos for (p = *argv; p != NULL; p = *++argv) {
175 1.30 christos convert_str2bn(&val, p);
176 1.30 christos pr_fact(val, hflag, xflag);
177 1.1 cgd }
178 1.1 cgd exit(0);
179 1.1 cgd }
180 1.1 cgd
181 1.35 christos static void
182 1.35 christos pr_exp(int i, int xflag)
183 1.35 christos {
184 1.35 christos printf(xflag && i > 9 ? "^0x%x" : "^%d", i);
185 1.35 christos }
186 1.35 christos
187 1.35 christos static void
188 1.35 christos pr_uint64(uint64_t i, int xflag)
189 1.35 christos {
190 1.35 christos printf(xflag ? " 0x%" PRIx64 : " %" PRIu64, i);
191 1.35 christos }
192 1.35 christos
193 1.1 cgd /*
194 1.1 cgd * pr_fact - print the factors of a number
195 1.1 cgd *
196 1.1 cgd * Print the factors of the number, from the lowest to the highest.
197 1.30 christos * A factor will be printed multiple times if it divides the value
198 1.30 christos * multiple times.
199 1.28 rin *
200 1.28 rin * If hflag is specified, duplicate factors are printed in "human-
201 1.28 rin * readable" form of x^n.
202 1.1 cgd *
203 1.30 christos * If the xflag is specified, numbers will be printed in hex.
204 1.30 christos *
205 1.1 cgd * Factors are printed with leading tabs.
206 1.1 cgd */
207 1.19 dholland static void
208 1.30 christos pr_fact(BIGNUM *val, int hflag, int xflag)
209 1.1 cgd {
210 1.28 rin int i;
211 1.30 christos const uint64_t *fact; /* The factor found. */
212 1.1 cgd
213 1.5 cgd /* Firewall - catch 0 and 1. */
214 1.30 christos if (BN_is_zero(val)) /* Historical practice; 0 just exits. */
215 1.30 christos exit(0);
216 1.30 christos if (BN_is_one(val)) {
217 1.30 christos printf("1: 1\n");
218 1.30 christos return;
219 1.30 christos }
220 1.1 cgd
221 1.5 cgd /* Factor value. */
222 1.10 simonb
223 1.30 christos if (xflag) {
224 1.30 christos fputs("0x", stdout);
225 1.30 christos BN_print_fp(stdout, val);
226 1.30 christos } else
227 1.30 christos BN_print_dec_fp(stdout, val);
228 1.10 simonb putchar(':');
229 1.10 simonb for (fact = &prime[0]; !BN_is_one(val); ++fact) {
230 1.5 cgd /* Look for the smallest factor. */
231 1.30 christos do {
232 1.10 simonb if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
233 1.1 cgd break;
234 1.30 christos } while (++fact <= pr_limit);
235 1.1 cgd
236 1.5 cgd /* Watch for primes larger than the table. */
237 1.1 cgd if (fact > pr_limit) {
238 1.11 itojun #ifdef HAVE_OPENSSL
239 1.12 simonb BIGNUM *bnfact;
240 1.12 simonb
241 1.12 simonb bnfact = BN_new();
242 1.30 christos BN_set_word(bnfact, *(fact - 1));
243 1.30 christos if (!BN_sqr(bnfact, bnfact, ctx))
244 1.30 christos errx(1, "error in BN_sqr()");
245 1.30 christos if (BN_cmp(bnfact, val) > 0 ||
246 1.30 christos BN_is_prime_ex(val, PRIME_CHECKS, NULL, NULL) == 1)
247 1.36 christos pr_print(val, hflag, xflag);
248 1.30 christos else
249 1.36 christos pollard_pminus1(val, hflag, xflag);
250 1.11 itojun #else
251 1.36 christos pr_print(val, hflag, xflag);
252 1.11 itojun #endif
253 1.36 christos pr_print(NULL, hflag, xflag);
254 1.5 cgd break;
255 1.1 cgd }
256 1.1 cgd
257 1.5 cgd /* Divide factor out until none are left. */
258 1.28 rin i = 0;
259 1.1 cgd do {
260 1.28 rin i++;
261 1.28 rin if (!hflag)
262 1.35 christos pr_uint64(*fact, xflag);
263 1.10 simonb BN_div_word(val, (BN_ULONG)*fact);
264 1.10 simonb } while (BN_mod_word(val, (BN_ULONG)*fact) == 0);
265 1.5 cgd
266 1.28 rin if (hflag) {
267 1.35 christos pr_uint64(*fact, xflag);
268 1.28 rin if (i > 1)
269 1.35 christos pr_exp(i, xflag);
270 1.28 rin }
271 1.28 rin
272 1.5 cgd /* Let the user know we're doing something. */
273 1.10 simonb fflush(stdout);
274 1.1 cgd }
275 1.10 simonb putchar('\n');
276 1.10 simonb }
277 1.10 simonb
278 1.19 dholland static void
279 1.36 christos pr_print(BIGNUM *val, int hflag, int xflag)
280 1.10 simonb {
281 1.34 christos static BIGNUM *sval;
282 1.34 christos static int ex = 1;
283 1.36 christos BIGNUM *pval;
284 1.36 christos
285 1.36 christos if (hflag) {
286 1.36 christos if (sval == NULL) {
287 1.36 christos sval = BN_dup(val);
288 1.36 christos return;
289 1.36 christos }
290 1.34 christos
291 1.36 christos if (val != NULL && BN_cmp(val, sval) == 0) {
292 1.36 christos ex++;
293 1.36 christos return;
294 1.36 christos }
295 1.36 christos pval = sval;
296 1.36 christos } else if (val == NULL) {
297 1.34 christos return;
298 1.36 christos } else {
299 1.36 christos pval = val;
300 1.34 christos }
301 1.34 christos
302 1.30 christos if (xflag) {
303 1.30 christos fputs(" 0x", stdout);
304 1.36 christos BN_print_fp(stdout, pval);
305 1.30 christos } else {
306 1.30 christos putchar(' ');
307 1.36 christos BN_print_dec_fp(stdout, pval);
308 1.30 christos }
309 1.34 christos
310 1.36 christos if (hflag) {
311 1.36 christos if (ex > 1)
312 1.36 christos pr_exp(ex, xflag);
313 1.36 christos
314 1.36 christos if (val != NULL) {
315 1.36 christos BN_copy(sval, val);
316 1.36 christos } else {
317 1.36 christos BN_free(sval);
318 1.36 christos sval = NULL;
319 1.36 christos }
320 1.36 christos ex = 1;
321 1.34 christos }
322 1.5 cgd }
323 1.5 cgd
324 1.30 christos static void
325 1.10 simonb usage(void)
326 1.5 cgd {
327 1.35 christos fprintf(stderr, "Usage: %s [-hx] [value ...]\n", getprogname());
328 1.30 christos exit(1);
329 1.10 simonb }
330 1.10 simonb
331 1.30 christos #ifdef HAVE_OPENSSL
332 1.10 simonb
333 1.30 christos /* pollard p-1, algorithm from Jim Gillogly, May 2000 */
334 1.19 dholland static void
335 1.36 christos pollard_pminus1(BIGNUM *val, int hflag, int xflag)
336 1.10 simonb {
337 1.30 christos BIGNUM *base, *rbase, *num, *i, *x;
338 1.10 simonb
339 1.30 christos base = BN_new();
340 1.30 christos rbase = BN_new();
341 1.30 christos num = BN_new();
342 1.30 christos i = BN_new();
343 1.21 drochner x = BN_new();
344 1.30 christos
345 1.30 christos BN_set_word(rbase, 1);
346 1.30 christos newbase:
347 1.30 christos if (!BN_add_word(rbase, 1))
348 1.30 christos errx(1, "error in BN_add_word()");
349 1.30 christos BN_set_word(i, 2);
350 1.30 christos BN_copy(base, rbase);
351 1.10 simonb
352 1.10 simonb for (;;) {
353 1.30 christos BN_mod_exp(base, base, i, val, ctx);
354 1.30 christos if (BN_is_one(base))
355 1.30 christos goto newbase;
356 1.30 christos
357 1.30 christos BN_copy(x, base);
358 1.30 christos BN_sub_word(x, 1);
359 1.30 christos if (!BN_gcd(x, x, val, ctx))
360 1.30 christos errx(1, "error in BN_gcd()");
361 1.30 christos
362 1.30 christos if (!BN_is_one(x)) {
363 1.30 christos if (BN_is_prime_ex(x, PRIME_CHECKS, NULL, NULL) == 1)
364 1.36 christos pr_print(x, hflag, xflag);
365 1.30 christos else
366 1.36 christos pollard_pminus1(x, hflag, xflag);
367 1.10 simonb fflush(stdout);
368 1.10 simonb
369 1.30 christos BN_div(num, NULL, val, x, ctx);
370 1.10 simonb if (BN_is_one(num))
371 1.10 simonb return;
372 1.30 christos if (BN_is_prime_ex(num, PRIME_CHECKS, NULL,
373 1.30 christos NULL) == 1) {
374 1.36 christos pr_print(num, hflag, xflag);
375 1.10 simonb fflush(stdout);
376 1.10 simonb return;
377 1.10 simonb }
378 1.10 simonb BN_copy(val, num);
379 1.10 simonb }
380 1.30 christos if (!BN_add_word(i, 1))
381 1.30 christos errx(1, "error in BN_add_word()");
382 1.10 simonb }
383 1.1 cgd }
384 1.30 christos
385 1.30 christos /*
386 1.30 christos * Sigh.. No _decimal_ output to file functions in BN.
387 1.30 christos */
388 1.30 christos static void
389 1.30 christos BN_print_dec_fp(FILE *fp, const BIGNUM *num)
390 1.30 christos {
391 1.30 christos char *buf;
392 1.30 christos
393 1.30 christos buf = BN_bn2dec(num);
394 1.30 christos if (buf == NULL)
395 1.30 christos return; /* XXX do anything here? */
396 1.30 christos fprintf(fp, "%s", buf);
397 1.30 christos free(buf);
398 1.30 christos }
399 1.30 christos
400 1.11 itojun #else
401 1.30 christos
402 1.30 christos static void
403 1.30 christos BN_print_fp(FILE *fp, const BIGNUM *num)
404 1.30 christos {
405 1.30 christos fprintf(fp, "%lx", (unsigned long)*num);
406 1.30 christos }
407 1.30 christos
408 1.30 christos static void
409 1.30 christos BN_print_dec_fp(FILE *fp, const BIGNUM *num)
410 1.11 itojun {
411 1.30 christos fprintf(fp, "%lu", (unsigned long)*num);
412 1.30 christos }
413 1.30 christos
414 1.30 christos static int
415 1.30 christos BN_dec2bn(BIGNUM **a, const char *str)
416 1.30 christos {
417 1.30 christos char *p;
418 1.30 christos
419 1.30 christos errno = 0;
420 1.30 christos **a = strtoul(str, &p, 10);
421 1.30 christos return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
422 1.30 christos }
423 1.30 christos
424 1.30 christos static int
425 1.30 christos BN_hex2bn(BIGNUM **a, const char *str)
426 1.30 christos {
427 1.30 christos char *p;
428 1.11 itojun
429 1.30 christos errno = 0;
430 1.30 christos **a = strtoul(str, &p, 16);
431 1.30 christos return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
432 1.11 itojun }
433 1.11 itojun
434 1.19 dholland static BN_ULONG
435 1.11 itojun BN_div_word(BIGNUM *a, BN_ULONG b)
436 1.11 itojun {
437 1.11 itojun BN_ULONG mod;
438 1.11 itojun
439 1.11 itojun mod = *a % b;
440 1.11 itojun *a /= b;
441 1.11 itojun return mod;
442 1.11 itojun }
443 1.30 christos
444 1.34 christos static BIGNUM *
445 1.34 christos BN_dup(const BIGNUM *a)
446 1.34 christos {
447 1.34 christos BIGNUM *b = BN_new();
448 1.34 christos BN_copy(b, a);
449 1.34 christos return b;
450 1.34 christos }
451 1.34 christos
452 1.11 itojun #endif
453 1.30 christos
454 1.30 christos /*
455 1.30 christos * Scan the string from left-to-right to see if the longest substring
456 1.30 christos * is a valid hexadecimal number.
457 1.30 christos */
458 1.30 christos static bool
459 1.30 christos is_hex_str(char *str)
460 1.30 christos {
461 1.30 christos char c, *p;
462 1.30 christos bool saw_hex = false;
463 1.30 christos
464 1.30 christos for (p = str; *p; p++) {
465 1.30 christos if (isdigit((unsigned char)*p))
466 1.30 christos continue;
467 1.30 christos c = tolower((unsigned char)*p);
468 1.30 christos if (c >= 'a' && c <= 'f') {
469 1.30 christos saw_hex = true;
470 1.30 christos continue;
471 1.30 christos }
472 1.30 christos break; /* Not a hexadecimal digit. */
473 1.30 christos }
474 1.30 christos return saw_hex;
475 1.30 christos }
476 1.30 christos
477 1.30 christos /* Convert string pointed to by *str to a bignum. */
478 1.30 christos static void
479 1.30 christos convert_str2bn(BIGNUM **val, char *p)
480 1.30 christos {
481 1.30 christos int n = 0;
482 1.30 christos
483 1.30 christos if (*p == '+') p++;
484 1.30 christos if (*p == '-')
485 1.30 christos errx(1, "negative numbers aren't permitted.");
486 1.33 christos if (*p == '0' && (p[1] == 'x' || p[1] == 'X')) {
487 1.33 christos n = BN_hex2bn(val, p + 2);
488 1.30 christos } else {
489 1.30 christos n = is_hex_str(p) ? BN_hex2bn(val, p) : BN_dec2bn(val, p);
490 1.30 christos }
491 1.30 christos if (n == 0)
492 1.30 christos errx(1, "%s: illegal numeric format.", p);
493 1.30 christos }
494