2 * Copyright 1999-2016 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
10 #include <openssl/bn.h>
11 #include <openssl/err.h>
14 int RSA_check_key(const RSA *key)
16 return RSA_check_key_ex(key, NULL);
19 int RSA_check_key_ex(const RSA *key, BN_GENCB *cb)
21 BIGNUM *i, *j, *k, *l, *m;
26 if (!key->p || !key->q || !key->n || !key->e || !key->d) {
27 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_VALUE_MISSING);
37 if (i == NULL || j == NULL || k == NULL || l == NULL ||
38 m == NULL || ctx == NULL) {
40 RSAerr(RSA_F_RSA_CHECK_KEY_EX, ERR_R_MALLOC_FAILURE);
45 r = BN_is_prime_ex(key->p, BN_prime_checks, NULL, cb);
50 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_P_NOT_PRIME);
54 r = BN_is_prime_ex(key->q, BN_prime_checks, NULL, cb);
59 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_Q_NOT_PRIME);
63 r = BN_mul(i, key->p, key->q, ctx);
69 if (BN_cmp(i, key->n) != 0) {
71 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_N_DOES_NOT_EQUAL_P_Q);
74 /* d*e = 1 mod lcm(p-1,q-1)? */
76 r = BN_sub(i, key->p, BN_value_one());
81 r = BN_sub(j, key->q, BN_value_one());
87 /* now compute k = lcm(i,j) */
88 r = BN_mul(l, i, j, ctx);
93 r = BN_gcd(m, i, j, ctx);
98 r = BN_div(k, NULL, l, m, ctx); /* remainder is 0 */
104 r = BN_mod_mul(i, key->d, key->e, k, ctx);
112 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_D_E_NOT_CONGRUENT_TO_1);
115 if (key->dmp1 != NULL && key->dmq1 != NULL && key->iqmp != NULL) {
116 /* dmp1 = d mod (p-1)? */
117 r = BN_sub(i, key->p, BN_value_one());
123 r = BN_mod(j, key->d, i, ctx);
129 if (BN_cmp(j, key->dmp1) != 0) {
131 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_DMP1_NOT_CONGRUENT_TO_D);
134 /* dmq1 = d mod (q-1)? */
135 r = BN_sub(i, key->q, BN_value_one());
141 r = BN_mod(j, key->d, i, ctx);
147 if (BN_cmp(j, key->dmq1) != 0) {
149 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_DMQ1_NOT_CONGRUENT_TO_D);
152 /* iqmp = q^-1 mod p? */
153 if (!BN_mod_inverse(i, key->q, key->p, ctx)) {
158 if (BN_cmp(i, key->iqmp) != 0) {
160 RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_IQMP_NOT_INVERSE_OF_Q);