|
29 | 29 | #include <linux/swab.h> |
30 | 30 | #include <linux/fips.h> |
31 | 31 | #include <crypto/ecdh.h> |
| 32 | +#include <crypto/rng.h> |
32 | 33 |
|
33 | 34 | #include "ecc.h" |
34 | 35 | #include "ecc_curve_defs.h" |
@@ -927,6 +928,61 @@ int ecc_is_key_valid(unsigned int curve_id, unsigned int ndigits, |
927 | 928 | return 0; |
928 | 929 | } |
929 | 930 |
|
| 931 | +/* |
| 932 | + * ECC private keys are generated using the method of extra random bits, |
| 933 | + * equivalent to that described in FIPS 186-4, Appendix B.4.1. |
| 934 | + * |
| 935 | + * d = (c mod(n–1)) + 1 where c is a string of random bits, 64 bits longer |
| 936 | + * than requested |
| 937 | + * 0 <= c mod(n-1) <= n-2 and implies that |
| 938 | + * 1 <= d <= n-1 |
| 939 | + * |
| 940 | + * This method generates a private key uniformly distributed in the range |
| 941 | + * [1, n-1]. |
| 942 | + */ |
| 943 | +int ecc_gen_privkey(unsigned int curve_id, unsigned int ndigits, u64 *privkey) |
| 944 | +{ |
| 945 | + const struct ecc_curve *curve = ecc_get_curve(curve_id); |
| 946 | + u64 priv[ndigits]; |
| 947 | + unsigned int nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT; |
| 948 | + unsigned int nbits = vli_num_bits(curve->n, ndigits); |
| 949 | + int err; |
| 950 | + |
| 951 | + /* Check that N is included in Table 1 of FIPS 186-4, section 6.1.1 */ |
| 952 | + if (nbits < 160) |
| 953 | + return -EINVAL; |
| 954 | + |
| 955 | + /* |
| 956 | + * FIPS 186-4 recommends that the private key should be obtained from a |
| 957 | + * RBG with a security strength equal to or greater than the security |
| 958 | + * strength associated with N. |
| 959 | + * |
| 960 | + * The maximum security strength identified by NIST SP800-57pt1r4 for |
| 961 | + * ECC is 256 (N >= 512). |
| 962 | + * |
| 963 | + * This condition is met by the default RNG because it selects a favored |
| 964 | + * DRBG with a security strength of 256. |
| 965 | + */ |
| 966 | + if (crypto_get_default_rng()) |
| 967 | + err = -EFAULT; |
| 968 | + |
| 969 | + err = crypto_rng_get_bytes(crypto_default_rng, (u8 *)priv, nbytes); |
| 970 | + crypto_put_default_rng(); |
| 971 | + if (err) |
| 972 | + return err; |
| 973 | + |
| 974 | + if (vli_is_zero(priv, ndigits)) |
| 975 | + return -EINVAL; |
| 976 | + |
| 977 | + /* Make sure the private key is in the range [1, n-1]. */ |
| 978 | + if (vli_cmp(curve->n, priv, ndigits) != 1) |
| 979 | + return -EINVAL; |
| 980 | + |
| 981 | + ecc_swap_digits(priv, privkey, ndigits); |
| 982 | + |
| 983 | + return 0; |
| 984 | +} |
| 985 | + |
930 | 986 | int ecc_make_pub_key(unsigned int curve_id, unsigned int ndigits, |
931 | 987 | const u64 *private_key, u64 *public_key) |
932 | 988 | { |
|
0 commit comments