/src/nss/lib/freebl/secmpi.c
Line | Count | Source |
1 | | /* This Source Code Form is subject to the terms of the Mozilla Public |
2 | | * License, v. 2.0. If a copy of the MPL was not distributed with this |
3 | | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
4 | | |
5 | | #ifdef FREEBL_NO_DEPEND |
6 | | #include "stubs.h" |
7 | | #endif |
8 | | |
9 | | #include "blapi.h" |
10 | | |
11 | | #include "mpi.h" |
12 | | #include "mpprime.h" |
13 | | #include "secerr.h" |
14 | | #include "secmpi.h" |
15 | | |
16 | | mp_err |
17 | | mpp_random_secure(mp_int *a) |
18 | 0 | { |
19 | 0 | SECStatus rv; |
20 | 0 | rv = RNG_GenerateGlobalRandomBytes((unsigned char *)MP_DIGITS(a), MP_USED(a) * sizeof(mp_digit)); |
21 | 0 | if (rv != SECSuccess) { |
22 | 0 | return MP_UNDEF; |
23 | 0 | } |
24 | 0 | MP_SIGN(a) = MP_ZPOS; |
25 | 0 | return MP_OKAY; |
26 | 0 | } |
27 | | |
28 | | mp_err |
29 | | mpp_pprime_secure(mp_int *a, int nt) |
30 | 0 | { |
31 | 0 | return mpp_pprime_ext_random(a, nt, &mpp_random_secure); |
32 | 0 | } |
33 | | |
34 | | mp_err |
35 | | mpp_make_prime_secure(mp_int *start, mp_size nBits, mp_size strong) |
36 | 0 | { |
37 | 0 | return mpp_make_prime_ext_random(start, nBits, strong, &mpp_random_secure); |
38 | 0 | } |
39 | | |
40 | | /* |
41 | | ** Number of times to attempt to generate a prime (p or q) from a random |
42 | | ** seed (the seed changes for each iteration). |
43 | | */ |
44 | 0 | #define MAX_PRIME_GEN_ATTEMPTS 10 |
45 | | |
46 | | SECStatus |
47 | | generate_prime(mp_int *prime, int primeLen) |
48 | 0 | { |
49 | 0 | mp_err err = MP_OKAY; |
50 | 0 | SECStatus rv = SECSuccess; |
51 | 0 | int piter; |
52 | 0 | unsigned char *pb = NULL; |
53 | 0 | pb = PORT_Alloc(primeLen); |
54 | 0 | if (!pb) { |
55 | 0 | PORT_SetError(SEC_ERROR_NO_MEMORY); |
56 | 0 | goto cleanup; |
57 | 0 | } |
58 | 0 | for (piter = 0; piter < MAX_PRIME_GEN_ATTEMPTS; piter++) { |
59 | 0 | CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(pb, primeLen)); |
60 | 0 | pb[0] |= 0xC0; /* set two high-order bits */ |
61 | 0 | pb[primeLen - 1] |= 0x01; /* set low-order bit */ |
62 | 0 | CHECK_MPI_OK(mp_read_unsigned_octets(prime, pb, primeLen)); |
63 | 0 | err = mpp_make_prime_secure(prime, primeLen * 8, PR_FALSE); |
64 | 0 | if (err != MP_NO) |
65 | 0 | goto cleanup; |
66 | | /* keep going while err == MP_NO */ |
67 | 0 | } |
68 | 0 | cleanup: |
69 | 0 | if (pb) |
70 | 0 | PORT_ZFree(pb, primeLen); |
71 | 0 | if (err) { |
72 | 0 | MP_TO_SEC_ERROR(err); |
73 | 0 | rv = SECFailure; |
74 | 0 | } |
75 | 0 | return rv; |
76 | 0 | } |