xref: /openssl/crypto/bn/bn_print.c (revision 706457b7)
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdio.h>
11 #include <openssl/bio.h>
12 #include "bn_local.h"
13 
14 static const char Hex[] = "0123456789ABCDEF";
15 
16 #ifndef OPENSSL_NO_STDIO
BN_print_fp(FILE * fp,const BIGNUM * a)17 int BN_print_fp(FILE *fp, const BIGNUM *a)
18 {
19     BIO *b;
20     int ret;
21 
22     if ((b = BIO_new(BIO_s_file())) == NULL)
23         return 0;
24     BIO_set_fp(b, fp, BIO_NOCLOSE);
25     ret = BN_print(b, a);
26     BIO_free(b);
27     return ret;
28 }
29 #endif
30 
BN_print(BIO * bp,const BIGNUM * a)31 int BN_print(BIO *bp, const BIGNUM *a)
32 {
33     int i, j, v, z = 0;
34     int ret = 0;
35 
36     if ((a->neg) && BIO_write(bp, "-", 1) != 1)
37         goto end;
38     if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1)
39         goto end;
40     for (i = a->top - 1; i >= 0; i--) {
41         for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
42             /* strip leading zeros */
43             v = (int)((a->d[i] >> j) & 0x0f);
44             if (z || v != 0) {
45                 if (BIO_write(bp, &Hex[v], 1) != 1)
46                     goto end;
47                 z = 1;
48             }
49         }
50     }
51     ret = 1;
52  end:
53     return ret;
54 }
55 
BN_options(void)56 char *BN_options(void)
57 {
58     static int init = 0;
59     static char data[16];
60 
61     if (!init) {
62         init++;
63 #ifdef BN_LLONG
64         BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)",
65                      sizeof(BN_ULLONG) * 8, sizeof(BN_ULONG) * 8);
66 #else
67         BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)",
68                      sizeof(BN_ULONG) * 8, sizeof(BN_ULONG) * 8);
69 #endif
70     }
71     return data;
72 }
73