2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * factor - factor a number into primes
36 * By: Landon Curt Noll chongo@toad.com, ...!{sun,tolsoft}!hoptoad!chongo
38 * chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
41 * factor [-h] [number] ...
43 * The form of the output is:
45 * number: factor1 factor1 factor2 factor3 factor3 factor3 ...
47 * where factor1 <= factor2 <= factor3 <= ...
49 * If no args are given, the list of numbers are read from stdin.
66 #include <openssl/bn.h>
68 #if OPENSSL_VERSION_NUMBER < 0x30000000L
70 BN_check_prime(BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb)
72 const int nchecks = 5;
74 return BN_is_prime_ex(p, nchecks, ctx, cb);
78 static void pollard_pminus1(BIGNUM *); /* print factors for big numbers */
83 typedef u_long BN_ULONG;
86 #define BN_CTX_new() NULL
87 #define BN_new() ((BIGNUM *)calloc(sizeof(BIGNUM), 1))
88 #define BN_is_zero(v) (*(v) == 0)
89 #define BN_is_one(v) (*(v) == 1)
90 #define BN_mod_word(a, b) (*(a) % (b))
92 static int BN_dec2bn(BIGNUM **, const char *);
93 static int BN_hex2bn(BIGNUM **, const char *);
94 static BN_ULONG BN_div_word(BIGNUM *, BN_ULONG);
95 static void BN_print_fp(FILE *, const BIGNUM *);
99 static void BN_print_dec_fp(FILE *, const BIGNUM *);
100 static void convert_str2bn(BIGNUM **, char *);
101 static bool is_hex_str(char *);
102 static void pr_fact(BIGNUM *); /* print factors of a value */
103 static void pr_print(BIGNUM *); /* print a prime */
104 static void usage(void);
106 static BN_CTX *ctx; /* just use a global context */
110 main(int argc, char *argv[])
114 char *p, buf[LINE_MAX]; /* > max number of digits. */
119 errx(1, "can't initialise bignum");
121 while ((ch = getopt(argc, argv, "h")) != -1)
133 /* No args supplied, read numbers from stdin. */
136 if (fgets(buf, sizeof(buf), stdin) == NULL) {
141 for (p = buf; isblank(*p); ++p);
142 if (*p == '\n' || *p == '\0')
144 convert_str2bn(&val, p);
147 /* Factor the arguments. */
149 for (p = *argv; p != NULL; p = *++argv) {
150 convert_str2bn(&val, p);
157 * pr_fact - print the factors of a number
159 * Print the factors of the number, from the lowest to the highest.
160 * A factor will be printed multiple times if it divides the value
163 * Factors are printed with leading tabs.
168 const ubig *fact; /* The factor found. */
170 /* Firewall - catch 0 and 1. */
171 if (BN_is_zero(val)) /* Historical practice; 0 just exits. */
173 if (BN_is_one(val)) {
182 BN_print_fp(stdout, val);
184 BN_print_dec_fp(stdout, val);
186 for (fact = &prime[0]; !BN_is_one(val); ++fact) {
187 /* Look for the smallest factor. */
189 if (BN_mod_word(val, (BN_ULONG)*fact) == 0)
191 } while (++fact <= pr_limit);
193 /* Watch for primes larger than the table. */
194 if (fact > pr_limit) {
199 BN_set_word(bnfact, *(fact - 1));
200 if (!BN_sqr(bnfact, bnfact, ctx))
201 errx(1, "error in BN_sqr()");
202 if (BN_cmp(bnfact, val) > 0 ||
203 BN_check_prime(val, NULL, NULL) == 1)
206 pollard_pminus1(val);
213 /* Divide factor out until none are left. */
215 printf(hflag ? " 0x%" PRIx64 "" : " %" PRIu64 "", *fact);
216 BN_div_word(val, (BN_ULONG)*fact);
217 } while (BN_mod_word(val, (BN_ULONG)*fact) == 0);
219 /* Let the user know we're doing something. */
226 pr_print(BIGNUM *val)
229 fputs(" 0x", stdout);
230 BN_print_fp(stdout, val);
233 BN_print_dec_fp(stdout, val);
240 fprintf(stderr, "usage: factor [-h] [value ...]\n");
246 /* pollard p-1, algorithm from Jim Gillogly, May 2000 */
248 pollard_pminus1(BIGNUM *val)
250 BIGNUM *base, *rbase, *num, *i, *x;
258 BN_set_word(rbase, 1);
260 if (!BN_add_word(rbase, 1))
261 errx(1, "error in BN_add_word()");
263 BN_copy(base, rbase);
266 BN_mod_exp(base, base, i, val, ctx);
272 if (!BN_gcd(x, x, val, ctx))
273 errx(1, "error in BN_gcd()");
276 if (BN_check_prime(x, NULL, NULL) == 1)
282 BN_div(num, NULL, val, x, ctx);
285 if (BN_check_prime(num, NULL, NULL) == 1) {
292 if (!BN_add_word(i, 1))
293 errx(1, "error in BN_add_word()");
298 * Sigh.. No _decimal_ output to file functions in BN.
301 BN_print_dec_fp(FILE *fp, const BIGNUM *num)
305 buf = BN_bn2dec(num);
307 return; /* XXX do anything here? */
308 fprintf(fp, "%s", buf);
315 BN_print_fp(FILE *fp, const BIGNUM *num)
317 fprintf(fp, "%lx", (unsigned long)*num);
321 BN_print_dec_fp(FILE *fp, const BIGNUM *num)
323 fprintf(fp, "%lu", (unsigned long)*num);
327 BN_dec2bn(BIGNUM **a, const char *str)
332 **a = strtoul(str, &p, 10);
333 return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
337 BN_hex2bn(BIGNUM **a, const char *str)
342 **a = strtoul(str, &p, 16);
343 return (errno == 0 ? 1 : 0); /* OpenSSL returns 0 on error! */
347 BN_div_word(BIGNUM *a, BN_ULONG b)
359 * Scan the string from left-to-right to see if the longest substring
360 * is a valid hexadecimal number.
363 is_hex_str(char *str)
366 bool saw_hex = false;
368 for (p = str; *p; p++) {
372 if (c >= 'a' && c <= 'f') {
376 break; /* Not a hexadecimal digit. */
381 /* Convert string pointed to by *str to a bignum. */
383 convert_str2bn(BIGNUM **val, char *p)
389 errx(1, "negative numbers aren't permitted.");
392 if (*p == 'x' || *p == 'X')
393 n = BN_hex2bn(val, ++p);
395 n = is_hex_str(p) ? BN_hex2bn(val, p) : BN_dec2bn(val, p);
398 errx(1, "%s: illegal numeric format.", p);