Convert RSA blinding to new multi-threading API
[openssl.git] / crypto / rsa / rsa_crpt.c
index 052f42c..cec4a7c 100644 (file)
@@ -1,4 +1,3 @@
-/* crypto/rsa/rsa_lib.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
 
 #include <stdio.h>
 #include <openssl/crypto.h>
-#include "cryptlib.h"
+#include "internal/cryptlib.h"
 #include <openssl/lhash.h>
 #include "internal/bn_int.h"
 #include <openssl/rsa.h>
 #include <openssl/rand.h>
 
+int RSA_bits(const RSA *r)
+{
+    return (BN_num_bits(r->n));
+}
+
 int RSA_size(const RSA *r)
 {
     return (BN_num_bytes(r->n));
@@ -100,10 +104,8 @@ int RSA_flags(const RSA *r)
 
 void RSA_blinding_off(RSA *rsa)
 {
-    if (rsa->blinding != NULL) {
-        BN_BLINDING_free(rsa->blinding);
-        rsa->blinding = NULL;
-    }
+    BN_BLINDING_free(rsa->blinding);
+    rsa->blinding = NULL;
     rsa->flags &= ~RSA_FLAG_BLINDING;
     rsa->flags |= RSA_FLAG_NO_BLINDING;
 }
@@ -156,8 +158,7 @@ static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p,
 
 BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx)
 {
-    BIGNUM *local_n = NULL;
-    BIGNUM *e, *n;
+    BIGNUM *e;
     BN_CTX *ctx;
     BN_BLINDING *ret = NULL;
 
@@ -193,32 +194,38 @@ BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx)
                  0.0);
     }
 
-    if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
-        /* Set BN_FLG_CONSTTIME flag */
-        local_n = n = BN_new();
-        if (!local_n) {
-            RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_MALLOC_FAILURE);
-            goto err;
+    {
+        BIGNUM *local_n = NULL, *n;
+        if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
+            /* Set BN_FLG_CONSTTIME flag */
+            local_n = n = BN_new();
+            if (local_n == NULL) {
+                RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_MALLOC_FAILURE);
+                goto err;
+            }
+            BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME);
+        } else {
+            n = rsa->n;
         }
-        BN_with_flags(n, rsa->n, BN_FLG_CONSTTIME);
-    } else
-        n = rsa->n;
 
-    ret = BN_BLINDING_create_param(NULL, e, n, ctx,
-                                   rsa->meth->bn_mod_exp, rsa->_method_mod_n);
+        ret = BN_BLINDING_create_param(NULL, e, n, ctx, rsa->meth->bn_mod_exp,
+                                       rsa->_method_mod_n);
+        /* We MUST free local_n before any further use of rsa->n */
+        BN_free(local_n);
+    }
     if (ret == NULL) {
         RSAerr(RSA_F_RSA_SETUP_BLINDING, ERR_R_BN_LIB);
         goto err;
     }
-    CRYPTO_THREADID_current(BN_BLINDING_thread_id(ret));
+
+    BN_BLINDING_set_current_thread(ret);
+
  err:
     BN_CTX_end(ctx);
-    if (in_ctx == NULL)
+    if (ctx != in_ctx)
         BN_CTX_free(ctx);
-    if (rsa->e == NULL)
+    if (e != rsa->e)
         BN_free(e);
-    if (local_n)
-        BN_free(local_n);
 
     return ret;
 }