2 * Copyright 1995-2017 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
11 #include <openssl/crypto.h>
12 #include "internal/cryptlib.h"
13 #include "internal/bn_int.h"
14 #include <openssl/rand.h>
17 int RSA_bits(const RSA *r)
19 return BN_num_bits(r->n);
22 int RSA_size(const RSA *r)
24 return BN_num_bytes(r->n);
27 int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to,
28 RSA *rsa, int padding)
30 return rsa->meth->rsa_pub_enc(flen, from, to, rsa, padding);
33 int RSA_private_encrypt(int flen, const unsigned char *from,
34 unsigned char *to, RSA *rsa, int padding)
36 return rsa->meth->rsa_priv_enc(flen, from, to, rsa, padding);
39 int RSA_private_decrypt(int flen, const unsigned char *from,
40 unsigned char *to, RSA *rsa, int padding)
42 return rsa->meth->rsa_priv_dec(flen, from, to, rsa, padding);
45 int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to,
46 RSA *rsa, int padding)
48 return rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding);
51 int RSA_flags(const RSA *r)
53 return r == NULL ? 0 : r->meth->flags;
56 void RSA_blinding_off(RSA *rsa)
58 BN_BLINDING_free(rsa->blinding);
60 rsa->flags &= ~RSA_FLAG_BLINDING;
61 rsa->flags |= RSA_FLAG_NO_BLINDING;
64 int RSA_blinding_on(RSA *rsa, BN_CTX *ctx)
68 if (rsa->blinding != NULL)
69 RSA_blinding_off(rsa);
71 rsa->blinding = RSA_setup_blinding(rsa, ctx);
72 if (rsa->blinding == NULL)
75 rsa->flags |= RSA_FLAG_BLINDING;
76 rsa->flags &= ~RSA_FLAG_NO_BLINDING;
82 static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p,
83 const BIGNUM *q, BN_CTX *ctx)
85 BIGNUM *ret = NULL, *r0, *r1, *r2;
87 if (d == NULL || p == NULL || q == NULL)
97 if (!BN_sub(r1, p, BN_value_one()))
99 if (!BN_sub(r2, q, BN_value_one()))
101 if (!BN_mul(r0, r1, r2, ctx))
104 ret = BN_mod_inverse(NULL, d, r0, ctx);
110 BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx)
114 BN_BLINDING *ret = NULL;
116 if (in_ctx == NULL) {
117 if ((ctx = BN_CTX_new()) == NULL)
126 RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_MALLOC_FAILURE);
130 if (rsa->e == NULL) {
131 e = rsa_get_public_exp(rsa->d, rsa->p, rsa->q, ctx);
133 RSAerr(RSA_F_RSA_SETUP_BLINDING, RSA_R_NO_PUBLIC_EXPONENT);
141 BIGNUM *n = BN_new();
144 RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_MALLOC_FAILURE);
147 BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME);
149 ret = BN_BLINDING_create_param(NULL, e, n, ctx, rsa->meth->bn_mod_exp,
151 /* We MUST free n before any further use of rsa->n */
155 RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_BN_LIB);
159 BN_BLINDING_set_current_thread(ret);