2 * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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
13 #include <openssl/err.h>
14 #include <openssl/bn.h>
17 /* X9.31 RSA key derivation and generation */
19 int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2, BIGNUM *q1,
20 BIGNUM *q2, const BIGNUM *Xp1, const BIGNUM *Xp2,
21 const BIGNUM *Xp, const BIGNUM *Xq1, const BIGNUM *Xq2,
22 const BIGNUM *Xq, const BIGNUM *e, BN_GENCB *cb)
24 BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL;
25 BN_CTX *ctx = NULL, *ctx2 = NULL;
52 * If not all parameters present only calculate what we can. This allows
53 * test programs to output selective parameters.
56 if (Xp && rsa->p == NULL) {
61 if (!BN_X931_derive_prime_ex(rsa->p, p1, p2,
62 Xp, Xp1, Xp2, e, ctx, cb))
66 if (Xq && rsa->q == NULL) {
70 if (!BN_X931_derive_prime_ex(rsa->q, q1, q2,
71 Xq, Xq1, Xq2, e, ctx, cb))
75 if (rsa->p == NULL || rsa->q == NULL) {
82 * Since both primes are set we can now calculate all remaining
90 if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx))
94 if (!BN_sub(r1, rsa->p, BN_value_one()))
96 if (!BN_sub(r2, rsa->q, BN_value_one()))
98 if (!BN_mul(r0, r1, r2, ctx))
99 goto err; /* (p-1)(q-1) */
101 if (!BN_gcd(r3, r1, r2, ctx))
104 if (!BN_div(r0, NULL, r0, r3, ctx))
105 goto err; /* LCM((p-1)(q-1)) */
111 rsa->d = BN_mod_inverse(NULL, rsa->e, r0, ctx2); /* d */
115 /* calculate d mod (p-1) */
116 rsa->dmp1 = BN_new();
117 if (rsa->dmp1 == NULL)
119 if (!BN_mod(rsa->dmp1, rsa->d, r1, ctx))
122 /* calculate d mod (q-1) */
123 rsa->dmq1 = BN_new();
124 if (rsa->dmq1 == NULL)
126 if (!BN_mod(rsa->dmq1, rsa->d, r2, ctx))
129 /* calculate inverse of q mod p */
130 rsa->iqmp = BN_mod_inverse(NULL, rsa->q, rsa->p, ctx2);
131 if (rsa->iqmp == NULL)
144 int RSA_X931_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e,
148 BIGNUM *Xp = NULL, *Xq = NULL;
156 Xp = BN_CTX_get(ctx);
157 Xq = BN_CTX_get(ctx);
160 if (!BN_X931_generate_Xpq(Xp, Xq, bits, ctx))
165 if (rsa->p == NULL || rsa->q == NULL)
168 /* Generate two primes from Xp, Xq */
170 if (!BN_X931_generate_prime_ex(rsa->p, NULL, NULL, NULL, NULL, Xp,
174 if (!BN_X931_generate_prime_ex(rsa->q, NULL, NULL, NULL, NULL, Xq,
179 * Since rsa->p and rsa->q are valid this call will just derive remaining
183 if (!RSA_X931_derive_ex(rsa, NULL, NULL, NULL, NULL,
184 NULL, NULL, NULL, NULL, NULL, NULL, e, cb))