factor.c revision 1.33 1 1.33 christos /* $NetBSD: factor.c,v 1.33 2020/10/05 14:31:30 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.33 christos __RCSID("$NetBSD: factor.c,v 1.33 2020/10/05 14:31:30 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.30 christos static void pollard_pminus1(BIGNUM *, int); /* print factors for big numbers */
95 1.30 christos
96 1.11 itojun #else
97 1.30 christos
98 1.11 itojun typedef long BIGNUM;
99 1.11 itojun typedef u_long BN_ULONG;
100 1.30 christos
101 1.30 christos #define BN_CTX int
102 1.30 christos #define BN_CTX_new() NULL
103 1.13 simonb #define BN_new() ((BIGNUM *)calloc(sizeof(BIGNUM), 1))
104 1.13 simonb #define BN_is_zero(v) (*(v) == 0)
105 1.13 simonb #define BN_is_one(v) (*(v) == 1)
106 1.11 itojun #define BN_mod_word(a, b) (*(a) % (b))
107 1.10 simonb
108 1.30 christos static int BN_dec2bn(BIGNUM **, const char *);
109 1.30 christos static int BN_hex2bn(BIGNUM **, const char *);
110 1.30 christos static BN_ULONG BN_div_word(BIGNUM *, BN_ULONG);
111 1.30 christos static void BN_print_fp(FILE *, const BIGNUM *);
112 1.1 cgd
113 1.21 drochner #endif
114 1.1 cgd
115 1.30 christos static void BN_print_dec_fp(FILE *, const BIGNUM *);
116 1.30 christos static void convert_str2bn(BIGNUM **, char *);
117 1.30 christos static bool is_hex_str(char *);
118 1.30 christos static void pr_fact(BIGNUM *, int, int); /* print factors of a value */
119 1.30 christos static void pr_print(BIGNUM *, int); /* print a prime */
120 1.32 tnn static void usage(void) __dead;
121 1.10 simonb
122 1.30 christos static BN_CTX *ctx; /* just use a global context */
123 1.1 cgd
124 1.5 cgd int
125 1.10 simonb main(int argc, char *argv[])
126 1.1 cgd {
127 1.10 simonb BIGNUM *val;
128 1.30 christos int ch, hflag, xflag;
129 1.10 simonb char *p, buf[LINE_MAX]; /* > max number of digits. */
130 1.10 simonb
131 1.30 christos hflag = xflag = 0;
132 1.12 simonb ctx = BN_CTX_new();
133 1.10 simonb val = BN_new();
134 1.10 simonb if (val == NULL)
135 1.10 simonb errx(1, "can't initialise bignum");
136 1.5 cgd
137 1.30 christos while ((ch = getopt(argc, argv, "hx")) != -1)
138 1.5 cgd switch (ch) {
139 1.28 rin case 'h':
140 1.30 christos hflag++;
141 1.30 christos break;
142 1.30 christos case 'x':
143 1.30 christos xflag++;
144 1.28 rin break;
145 1.5 cgd case '?':
146 1.5 cgd default:
147 1.5 cgd usage();
148 1.5 cgd }
149 1.5 cgd argc -= optind;
150 1.5 cgd argv += optind;
151 1.5 cgd
152 1.5 cgd /* No args supplied, read numbers from stdin. */
153 1.5 cgd if (argc == 0)
154 1.5 cgd for (;;) {
155 1.5 cgd if (fgets(buf, sizeof(buf), stdin) == NULL) {
156 1.5 cgd if (ferror(stdin))
157 1.5 cgd err(1, "stdin");
158 1.5 cgd exit (0);
159 1.5 cgd }
160 1.23 tnozaki for (p = buf; isblank((unsigned char)*p); ++p);
161 1.5 cgd if (*p == '\n' || *p == '\0')
162 1.5 cgd continue;
163 1.30 christos convert_str2bn(&val, p);
164 1.30 christos pr_fact(val, hflag, xflag);
165 1.5 cgd }
166 1.5 cgd /* Factor the arguments. */
167 1.5 cgd else
168 1.30 christos for (p = *argv; p != NULL; p = *++argv) {
169 1.30 christos convert_str2bn(&val, p);
170 1.30 christos pr_fact(val, hflag, xflag);
171 1.1 cgd }
172 1.1 cgd exit(0);
173 1.1 cgd }
174 1.1 cgd
175 1.1 cgd /*
176 1.1 cgd * pr_fact - print the factors of a number
177 1.1 cgd *
178 1.1 cgd * Print the factors of the number, from the lowest to the highest.
179 1.30 christos * A factor will be printed multiple times if it divides the value
180 1.30 christos * multiple times.
181 1.28 rin *
182 1.28 rin * If hflag is specified, duplicate factors are printed in "human-
183 1.28 rin * readable" form of x^n.
184 1.1 cgd *
185 1.30 christos * If the xflag is specified, numbers will be printed in hex.
186 1.30 christos *
187 1.1 cgd * Factors are printed with leading tabs.
188 1.1 cgd */
189 1.19 dholland static void
190 1.30 christos pr_fact(BIGNUM *val, int hflag, int xflag)
191 1.1 cgd {
192 1.28 rin int i;
193 1.30 christos const uint64_t *fact; /* The factor found. */
194 1.1 cgd
195 1.5 cgd /* Firewall - catch 0 and 1. */
196 1.30 christos if (BN_is_zero(val)) /* Historical practice; 0 just exits. */
197 1.30 christos exit(0);
198 1.30 christos if (BN_is_one(val)) {
199 1.30 christos printf("1: 1\n");
200 1.30 christos return;
201 1.30 christos }
202 1.1 cgd
203 1.5 cgd /* Factor value. */
204 1.10 simonb
205 1.30 christos if (xflag) {
206 1.30 christos fputs("0x", stdout);
207 1.30 christos BN_print_fp(stdout, val);
208 1.30 christos } else
209 1.30 christos BN_print_dec_fp(stdout, val);
210 1.10 simonb putchar(':');
211 1.10 simonb for (fact = &prime[0]; !BN_is_one(val); ++fact) {
212 1.5 cgd /* Look for the smallest factor. */
213 1.30 christos do {
214 1.10 simonb if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
215 1.1 cgd break;
216 1.30 christos } while (++fact <= pr_limit);
217 1.1 cgd
218 1.5 cgd /* Watch for primes larger than the table. */
219 1.1 cgd if (fact > pr_limit) {
220 1.11 itojun #ifdef HAVE_OPENSSL
221 1.12 simonb BIGNUM *bnfact;
222 1.12 simonb
223 1.12 simonb bnfact = BN_new();
224 1.30 christos BN_set_word(bnfact, *(fact - 1));
225 1.30 christos if (!BN_sqr(bnfact, bnfact, ctx))
226 1.30 christos errx(1, "error in BN_sqr()");
227 1.30 christos if (BN_cmp(bnfact, val) > 0 ||
228 1.30 christos BN_is_prime_ex(val, PRIME_CHECKS, NULL, NULL) == 1)
229 1.30 christos pr_print(val, xflag);
230 1.30 christos else
231 1.30 christos pollard_pminus1(val, xflag);
232 1.11 itojun #else
233 1.30 christos pr_print(val, xflag);
234 1.11 itojun #endif
235 1.5 cgd break;
236 1.1 cgd }
237 1.1 cgd
238 1.5 cgd /* Divide factor out until none are left. */
239 1.28 rin i = 0;
240 1.1 cgd do {
241 1.28 rin i++;
242 1.28 rin if (!hflag)
243 1.30 christos printf(xflag ? " 0x%" PRIx64 : " %" PRIu64,
244 1.30 christos *fact);
245 1.10 simonb BN_div_word(val, (BN_ULONG)*fact);
246 1.10 simonb } while (BN_mod_word(val, (BN_ULONG)*fact) == 0);
247 1.5 cgd
248 1.28 rin if (hflag) {
249 1.30 christos printf(xflag ? " 0x%" PRIx64 : " %" PRIu64, *fact);
250 1.28 rin if (i > 1)
251 1.30 christos printf(xflag ? "^0x%x" : "^%d", i);
252 1.28 rin }
253 1.28 rin
254 1.5 cgd /* Let the user know we're doing something. */
255 1.10 simonb fflush(stdout);
256 1.1 cgd }
257 1.10 simonb putchar('\n');
258 1.10 simonb }
259 1.10 simonb
260 1.19 dholland static void
261 1.30 christos pr_print(BIGNUM *val, int xflag)
262 1.10 simonb {
263 1.30 christos if (xflag) {
264 1.30 christos fputs(" 0x", stdout);
265 1.30 christos BN_print_fp(stdout, val);
266 1.30 christos } else {
267 1.30 christos putchar(' ');
268 1.30 christos BN_print_dec_fp(stdout, val);
269 1.30 christos }
270 1.5 cgd }
271 1.5 cgd
272 1.30 christos static void
273 1.10 simonb usage(void)
274 1.5 cgd {
275 1.28 rin fprintf(stderr, "usage: factor [-h] [value ...]\n");
276 1.30 christos exit(1);
277 1.10 simonb }
278 1.10 simonb
279 1.30 christos #ifdef HAVE_OPENSSL
280 1.10 simonb
281 1.30 christos /* pollard p-1, algorithm from Jim Gillogly, May 2000 */
282 1.19 dholland static void
283 1.30 christos pollard_pminus1(BIGNUM *val, int xflag)
284 1.10 simonb {
285 1.30 christos BIGNUM *base, *rbase, *num, *i, *x;
286 1.10 simonb
287 1.30 christos base = BN_new();
288 1.30 christos rbase = BN_new();
289 1.30 christos num = BN_new();
290 1.30 christos i = BN_new();
291 1.21 drochner x = BN_new();
292 1.30 christos
293 1.30 christos BN_set_word(rbase, 1);
294 1.30 christos newbase:
295 1.30 christos if (!BN_add_word(rbase, 1))
296 1.30 christos errx(1, "error in BN_add_word()");
297 1.30 christos BN_set_word(i, 2);
298 1.30 christos BN_copy(base, rbase);
299 1.10 simonb
300 1.10 simonb for (;;) {
301 1.30 christos BN_mod_exp(base, base, i, val, ctx);
302 1.30 christos if (BN_is_one(base))
303 1.30 christos goto newbase;
304 1.30 christos
305 1.30 christos BN_copy(x, base);
306 1.30 christos BN_sub_word(x, 1);
307 1.30 christos if (!BN_gcd(x, x, val, ctx))
308 1.30 christos errx(1, "error in BN_gcd()");
309 1.30 christos
310 1.30 christos if (!BN_is_one(x)) {
311 1.30 christos if (BN_is_prime_ex(x, PRIME_CHECKS, NULL, NULL) == 1)
312 1.30 christos pr_print(x, xflag);
313 1.30 christos else
314 1.30 christos pollard_pminus1(x, xflag);
315 1.10 simonb fflush(stdout);
316 1.10 simonb
317 1.30 christos BN_div(num, NULL, val, x, ctx);
318 1.10 simonb if (BN_is_one(num))
319 1.10 simonb return;
320 1.30 christos if (BN_is_prime_ex(num, PRIME_CHECKS, NULL,
321 1.30 christos NULL) == 1) {
322 1.30 christos pr_print(num, xflag);
323 1.10 simonb fflush(stdout);
324 1.10 simonb return;
325 1.10 simonb }
326 1.10 simonb BN_copy(val, num);
327 1.10 simonb }
328 1.30 christos if (!BN_add_word(i, 1))
329 1.30 christos errx(1, "error in BN_add_word()");
330 1.10 simonb }
331 1.1 cgd }
332 1.30 christos
333 1.30 christos /*
334 1.30 christos * Sigh.. No _decimal_ output to file functions in BN.
335 1.30 christos */
336 1.30 christos static void
337 1.30 christos BN_print_dec_fp(FILE *fp, const BIGNUM *num)
338 1.30 christos {
339 1.30 christos char *buf;
340 1.30 christos
341 1.30 christos buf = BN_bn2dec(num);
342 1.30 christos if (buf == NULL)
343 1.30 christos return; /* XXX do anything here? */
344 1.30 christos fprintf(fp, "%s", buf);
345 1.30 christos free(buf);
346 1.30 christos }
347 1.30 christos
348 1.11 itojun #else
349 1.30 christos
350 1.30 christos static void
351 1.30 christos BN_print_fp(FILE *fp, const BIGNUM *num)
352 1.30 christos {
353 1.30 christos fprintf(fp, "%lx", (unsigned long)*num);
354 1.30 christos }
355 1.30 christos
356 1.30 christos static void
357 1.30 christos BN_print_dec_fp(FILE *fp, const BIGNUM *num)
358 1.11 itojun {
359 1.30 christos fprintf(fp, "%lu", (unsigned long)*num);
360 1.30 christos }
361 1.30 christos
362 1.30 christos static int
363 1.30 christos BN_dec2bn(BIGNUM **a, const char *str)
364 1.30 christos {
365 1.30 christos char *p;
366 1.30 christos
367 1.30 christos errno = 0;
368 1.30 christos **a = strtoul(str, &p, 10);
369 1.30 christos return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
370 1.30 christos }
371 1.30 christos
372 1.30 christos static int
373 1.30 christos BN_hex2bn(BIGNUM **a, const char *str)
374 1.30 christos {
375 1.30 christos char *p;
376 1.11 itojun
377 1.30 christos errno = 0;
378 1.30 christos **a = strtoul(str, &p, 16);
379 1.30 christos return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
380 1.11 itojun }
381 1.11 itojun
382 1.19 dholland static BN_ULONG
383 1.11 itojun BN_div_word(BIGNUM *a, BN_ULONG b)
384 1.11 itojun {
385 1.11 itojun BN_ULONG mod;
386 1.11 itojun
387 1.11 itojun mod = *a % b;
388 1.11 itojun *a /= b;
389 1.11 itojun return mod;
390 1.11 itojun }
391 1.30 christos
392 1.11 itojun #endif
393 1.30 christos
394 1.30 christos /*
395 1.30 christos * Scan the string from left-to-right to see if the longest substring
396 1.30 christos * is a valid hexadecimal number.
397 1.30 christos */
398 1.30 christos static bool
399 1.30 christos is_hex_str(char *str)
400 1.30 christos {
401 1.30 christos char c, *p;
402 1.30 christos bool saw_hex = false;
403 1.30 christos
404 1.30 christos for (p = str; *p; p++) {
405 1.30 christos if (isdigit((unsigned char)*p))
406 1.30 christos continue;
407 1.30 christos c = tolower((unsigned char)*p);
408 1.30 christos if (c >= 'a' && c <= 'f') {
409 1.30 christos saw_hex = true;
410 1.30 christos continue;
411 1.30 christos }
412 1.30 christos break; /* Not a hexadecimal digit. */
413 1.30 christos }
414 1.30 christos return saw_hex;
415 1.30 christos }
416 1.30 christos
417 1.30 christos /* Convert string pointed to by *str to a bignum. */
418 1.30 christos static void
419 1.30 christos convert_str2bn(BIGNUM **val, char *p)
420 1.30 christos {
421 1.30 christos int n = 0;
422 1.30 christos
423 1.30 christos if (*p == '+') p++;
424 1.30 christos if (*p == '-')
425 1.30 christos errx(1, "negative numbers aren't permitted.");
426 1.33 christos if (*p == '0' && (p[1] == 'x' || p[1] == 'X')) {
427 1.33 christos n = BN_hex2bn(val, p + 2);
428 1.30 christos } else {
429 1.30 christos n = is_hex_str(p) ? BN_hex2bn(val, p) : BN_dec2bn(val, p);
430 1.30 christos }
431 1.30 christos if (n == 0)
432 1.30 christos errx(1, "%s: illegal numeric format.", p);
433 1.30 christos }
434