Fix migration guide mappings for i2o/o2i_ECPublicKey
[openssl.git] / engines / e_capi.c
index f2d5c3e0912856969b6ef1a868426ad686a85c5d..ffc5bf7a2aa8d563c2b852c4acc5a3a71e7b8967 100644 (file)
@@ -1,19 +1,32 @@
 /*
- * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
- * Licensed under the OpenSSL license (the "License").  You may not use
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
  * in the file LICENSE in the source distribution or at
  * https://www.openssl.org/source/license.html
  */
 
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
+/* We need to use some deprecated APIs */
+#define OPENSSL_SUPPRESS_DEPRECATED
 
-#include <openssl/crypto.h>
+#ifdef _WIN32
+# ifndef _WIN32_WINNT
+#  define _WIN32_WINNT 0x0400
+# endif
+# include <windows.h>
+# include <wincrypt.h>
+
+# include <stdio.h>
+# include <string.h>
+# include <stdlib.h>
+# include <malloc.h>
+# ifndef alloca
+#  define alloca _alloca
+# endif
+
+# include <openssl/crypto.h>
 
-#ifdef OPENSSL_SYS_WIN32
 # ifndef OPENSSL_NO_CAPIENG
 
 #  include <openssl/buffer.h>
 #  include <openssl/rsa.h>
 #  include <openssl/dsa.h>
 
-#  ifndef _WIN32_WINNT
-#   define _WIN32_WINNT 0x0400
-#  endif
-
-#  include <windows.h>
-#  include <wincrypt.h>
-#  include <malloc.h>
-#  ifndef alloca
-#   define alloca _alloca
-#  endif
-
 /*
  * This module uses several "new" interfaces, among which is
  * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is
@@ -50,7 +52,7 @@
 #   define __COMPILE_CAPIENG
 #  endif                        /* CERT_KEY_PROV_INFO_PROP_ID */
 # endif                         /* OPENSSL_NO_CAPIENG */
-#endif                          /* OPENSSL_SYS_WIN32 */
+#endif                          /* _WIN32 */
 
 #ifdef __COMPILE_CAPIENG
 
 # endif
 
 # ifndef ALG_SID_SHA_256
-#  define ALG_SID_SHA_256                 12
+#  define ALG_SID_SHA_256   12
 # endif
 # ifndef ALG_SID_SHA_384
-#  define ALG_SID_SHA_384                 13
+#  define ALG_SID_SHA_384   13
 # endif
 # ifndef ALG_SID_SHA_512
-#  define ALG_SID_SHA_512                 14
+#  define ALG_SID_SHA_512   14
 # endif
 
 # ifndef CALG_SHA_256
-#  define CALG_SHA_256            (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
+#  define CALG_SHA_256      (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
 # endif
 # ifndef CALG_SHA_384
-#  define CALG_SHA_384            (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
+#  define CALG_SHA_384      (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
 # endif
 # ifndef CALG_SHA_512
-#  define CALG_SHA_512            (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
+#  define CALG_SHA_512      (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
 # endif
 
 # ifndef PROV_RSA_AES
@@ -109,17 +111,17 @@ typedef struct CAPI_KEY_st CAPI_KEY;
 static void capi_addlasterror(void);
 static void capi_adderror(DWORD err);
 
-static void CAPI_trace(CAPI_CTX * ctx, char *format, ...);
+static void CAPI_trace(CAPI_CTX *ctx, char *format, ...);
 
-static int capi_list_providers(CAPI_CTX * ctx, BIO *out);
-static int capi_list_containers(CAPI_CTX * ctx, BIO *out);
-int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *storename);
-void capi_free_key(CAPI_KEY * key);
+static int capi_list_providers(CAPI_CTX *ctx, BIO *out);
+static int capi_list_containers(CAPI_CTX *ctx, BIO *out);
+int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename);
+void capi_free_key(CAPI_KEY *key);
 
-static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
+static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id,
                                      HCERTSTORE hstore);
 
-CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id);
+CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id);
 
 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
                                    UI_METHOD *ui_method, void *callback_data);
@@ -151,9 +153,9 @@ static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
 
 void engine_load_capi_int(void);
 
-typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
-                                         LPCWSTR, DWORD, DWORD, void *);
-typedef HWND(WINAPI *GETCONSWIN) (void);
+typedef PCCERT_CONTEXT(WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR,
+                                        LPCWSTR, DWORD, DWORD, void *);
+typedef HWND(WINAPI *GETCONSWIN)(void);
 
 /*
  * This structure contains CAPI ENGINE specific data: it contains various
@@ -176,26 +178,17 @@ struct CAPI_CTX_st {
     /* System store flags */
     DWORD store_flags;
 /* Lookup string meanings in load_private_key */
-/* Substring of subject: uses "storename" */
-# define CAPI_LU_SUBSTR          1
-/* Friendly name: uses storename */
-# define CAPI_LU_FNAME           2
-/* Container name: uses cspname, keytype */
-# define CAPI_LU_CONTNAME        3
+# define CAPI_LU_SUBSTR          1  /* Substring of subject: uses "storename" */
+# define CAPI_LU_FNAME           2  /* Friendly name: uses storename */
+# define CAPI_LU_CONTNAME        3  /* Container name: uses cspname, keytype */
     int lookup_method;
 /* Info to dump with dumpcerts option */
-/* Issuer and serial name strings */
-# define CAPI_DMP_SUMMARY        0x1
-/* Friendly name */
-# define CAPI_DMP_FNAME          0x2
-/* Full X509_print dump */
-# define CAPI_DMP_FULL           0x4
-/* Dump PEM format certificate */
-# define CAPI_DMP_PEM            0x8
-/* Dump pseudo key (if possible) */
-# define CAPI_DMP_PSKEY          0x10
-/* Dump key info (if possible) */
-# define CAPI_DMP_PKEYINFO       0x20
+# define CAPI_DMP_SUMMARY        0x1    /* Issuer and serial name strings */
+# define CAPI_DMP_FNAME          0x2    /* Friendly name */
+# define CAPI_DMP_FULL           0x4    /* Full X509_print dump */
+# define CAPI_DMP_PEM            0x8    /* Dump PEM format certificate */
+# define CAPI_DMP_PSKEY          0x10   /* Dump pseudo key (if possible) */
+# define CAPI_DMP_PKEYINFO       0x20   /* Dump key info (if possible) */
     DWORD dump_flags;
     int (*client_cert_select) (ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
     CERTDLG certselectdlg;
@@ -203,10 +196,10 @@ struct CAPI_CTX_st {
 };
 
 static CAPI_CTX *capi_ctx_new(void);
-static void capi_ctx_free(CAPI_CTX * ctx);
-static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
+static void capi_ctx_free(CAPI_CTX *ctx);
+static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type,
                                  int check);
-static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx);
+static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx);
 
 # define CAPI_CMD_LIST_CERTS             ENGINE_CMD_BASE
 # define CAPI_CMD_LOOKUP_CERT            (ENGINE_CMD_BASE + 1)
@@ -330,7 +323,6 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
             ctx->storename = tmpstr;
             CAPI_trace(ctx, "Setting store name to %s\n", p);
         } else {
-            CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
             ret = 0;
         }
         break;
@@ -357,7 +349,6 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
             ctx->debug_file = tmpstr;
             CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
         } else {
-            CAPIerr(CAPI_F_CAPI_CTRL, ERR_R_MALLOC_FAILURE);
             ret = 0;
         }
         break;
@@ -408,6 +399,10 @@ static DSA_METHOD *capi_dsa_method = NULL;
 # endif
 
 static int use_aes_csp = 0;
+static const WCHAR rsa_aes_cspname[] =
+    L"Microsoft Enhanced RSA and AES Cryptographic Provider";
+static const WCHAR rsa_enh_cspname[] =
+    L"Microsoft Enhanced Cryptographic Provider v1.0";
 
 static int capi_init(ENGINE *e)
 {
@@ -420,15 +415,17 @@ static int capi_init(ENGINE *e)
 
     if (capi_idx < 0) {
         capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
-        if (capi_idx < 0)
-            goto memerr;
+        if (capi_idx < 0) {
+            CAPIerr(CAPI_F_CAPI_INIT, ERR_R_ENGINE_LIB);
+            goto err;
+        }
 
         cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0);
 
         /* Setup RSA_METHOD */
         rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
         ossl_rsa_meth = RSA_PKCS1_OpenSSL();
-        if (   !RSA_meth_set_pub_enc(capi_rsa_method,
+        if (!RSA_meth_set_pub_enc(capi_rsa_method,
                                      RSA_meth_get_pub_enc(ossl_rsa_meth))
             || !RSA_meth_set_pub_dec(capi_rsa_method,
                                      RSA_meth_get_pub_dec(ossl_rsa_meth))
@@ -440,14 +437,15 @@ static int capi_init(ENGINE *e)
                                         RSA_meth_get_bn_mod_exp(ossl_rsa_meth))
             || !RSA_meth_set_finish(capi_rsa_method, capi_rsa_free)
             || !RSA_meth_set_sign(capi_rsa_method, capi_rsa_sign)) {
-            goto memerr;
+            CAPIerr(CAPI_F_CAPI_INIT, ERR_R_RSA_LIB);
+            goto err;
         }
 
 # ifndef OPENSSL_NO_DSA
         /* Setup DSA Method */
         dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
         ossl_dsa_meth = DSA_OpenSSL();
-        if (   !DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
+        if (!DSA_meth_set_sign(capi_dsa_method, capi_dsa_do_sign)
             || !DSA_meth_set_verify(capi_dsa_method,
                                     DSA_meth_get_verify(ossl_dsa_meth))
             || !DSA_meth_set_finish(capi_dsa_method, capi_dsa_free)
@@ -455,14 +453,17 @@ static int capi_init(ENGINE *e)
                                      DSA_meth_get_mod_exp(ossl_dsa_meth))
             || !DSA_meth_set_bn_mod_exp(capi_dsa_method,
                                     DSA_meth_get_bn_mod_exp(ossl_dsa_meth))) {
-            goto memerr;
+            CAPIerr(CAPI_F_CAPI_INIT, ERR_R_DSA_LIB);
+            goto err;
         }
 # endif
     }
 
     ctx = capi_ctx_new();
-    if (ctx == NULL)
-        goto memerr;
+    if (ctx == NULL) {
+        CAPIerr(CAPI_F_CAPI_INIT, ERR_R_CAPI_LIB);
+        goto err;
+    }
 
     ENGINE_set_ex_data(e, capi_idx, ctx);
 
@@ -482,21 +483,17 @@ static int capi_init(ENGINE *e)
     }
 # endif
 
-    /* See if we support AES CSP */
-
-    if (CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES,
-                            CRYPT_VERIFYCONTEXT)) {
+    /* See if there is RSA+AES CSP */
+    if (CryptAcquireContextW(&hprov, NULL, rsa_aes_cspname, PROV_RSA_AES,
+                             CRYPT_VERIFYCONTEXT)) {
         use_aes_csp = 1;
         CryptReleaseContext(hprov, 0);
     }
 
     return 1;
 
- memerr:
-    CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE);
+ err:
     return 0;
-
-    return 1;
 }
 
 static int capi_destroy(ENGINE *e)
@@ -584,7 +581,7 @@ static int bind_helper(ENGINE *e, const char *id)
 }
 
 IMPLEMENT_DYNAMIC_CHECK_FN()
-    IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
 # else
 static ENGINE *engine_capi(void)
 {
@@ -604,9 +601,19 @@ void engine_load_capi_int(void)
     ENGINE *toadd = engine_capi();
     if (!toadd)
         return;
+    ERR_set_mark();
     ENGINE_add(toadd);
+    /*
+     * If the "add" worked, it gets a structural reference. So either way, we
+     * release our just-created reference.
+     */
     ENGINE_free(toadd);
-    ERR_clear_error();
+    /*
+     * If the "add" didn't work, it was probably a conflict because it was
+     * already added (eg. someone calling ENGINE_load_blah then calling
+     * ENGINE_load_builtin_engines() perhaps).
+     */
+    ERR_pop_to_mark();
 }
 # endif
 
@@ -632,7 +639,7 @@ static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen)
 
 /* Given a CAPI_KEY get an EVP_PKEY structure */
 
-static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
+static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key)
 {
     unsigned char *pubkey = NULL;
     DWORD len;
@@ -649,7 +656,7 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
     pubkey = OPENSSL_malloc(len);
 
     if (pubkey == NULL)
-        goto memerr;
+        goto err;
 
     if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
         CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR);
@@ -678,8 +685,10 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
         }
         rsa_modulus = (unsigned char *)(rp + 1);
         rkey = RSA_new_method(eng);
-        if (!rkey)
-            goto memerr;
+        if (!rkey) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_RSA_LIB);
+            goto err;
+        }
 
         e = BN_new();
         n = BN_new();
@@ -687,22 +696,29 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
         if (e == NULL || n == NULL) {
             BN_free(e);
             BN_free(n);
-            goto memerr;
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_BN_LIB);
+            goto err;
         }
 
         RSA_set0_key(rkey, n, e, NULL);
 
-        if (!BN_set_word(e, rp->pubexp))
-            goto memerr;
+        if (!BN_set_word(e, rp->pubexp)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_BN_LIB);
+            goto err;
+        }
 
         rsa_modlen = rp->bitlen / 8;
-        if (!lend_tobn(n, rsa_modulus, rsa_modlen))
-            goto memerr;
+        if (!lend_tobn(n, rsa_modulus, rsa_modlen)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_BN_LIB);
+            goto err;
+        }
 
         RSA_set_ex_data(rkey, rsa_capi_idx, key);
 
-        if ((ret = EVP_PKEY_new()) == NULL)
-            goto memerr;
+        if ((ret = EVP_PKEY_new()) == NULL) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_EVP_LIB);
+            goto err;
+        }
 
         EVP_PKEY_assign_RSA(ret, rkey);
         rkey = NULL;
@@ -725,8 +741,10 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
         dsa_plen = dp->bitlen / 8;
         btmp = (unsigned char *)(dp + 1);
         dkey = DSA_new_method(eng);
-        if (!dkey)
-            goto memerr;
+        if (!dkey) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_DSA_LIB);
+            goto err;
+        }
         p = BN_new();
         q = BN_new();
         g = BN_new();
@@ -736,27 +754,38 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
             BN_free(q);
             BN_free(g);
             BN_free(pub_key);
-            goto memerr;
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_BN_LIB);
+            goto err;
         }
         DSA_set0_pqg(dkey, p, q, g);
         DSA_set0_key(dkey, pub_key, NULL);
-        if (!lend_tobn(p, btmp, dsa_plen))
-            goto memerr;
+        if (!lend_tobn(p, btmp, dsa_plen)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_CAPI_LIB);
+            goto err;
+        }
         btmp += dsa_plen;
-        if (!lend_tobn(q, btmp, 20))
-            goto memerr;
+        if (!lend_tobn(q, btmp, 20)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_CAPI_LIB);
+            goto err;
+        }
         btmp += 20;
-        if (!lend_tobn(g, btmp, dsa_plen))
-            goto memerr;
+        if (!lend_tobn(g, btmp, dsa_plen)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_CAPI_LIB);
+            goto err;
+        }
         btmp += dsa_plen;
-        if (!lend_tobn(pub_key, btmp, dsa_plen))
-            goto memerr;
+        if (!lend_tobn(pub_key, btmp, dsa_plen)) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_CAPI_LIB);
+            goto err;
+        }
         btmp += dsa_plen;
 
         DSA_set_ex_data(dkey, dsa_capi_idx, key);
 
-        if ((ret = EVP_PKEY_new()) == NULL)
-            goto memerr;
+        if ((ret = EVP_PKEY_new()) == NULL) {
+            CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_EVP_LIB);
+            goto err;
+        }
 
         EVP_PKEY_assign_DSA(ret, dkey);
         dkey = NULL;
@@ -780,11 +809,6 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
     }
 
     return ret;
-
- memerr:
-    CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE);
-    goto err;
-
 }
 
 static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id,
@@ -842,7 +866,7 @@ int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY);
         return -1;
     }
-/* Convert the signature type to a CryptoAPI algorithm ID */
+    /* Convert the signature type to a CryptoAPI algorithm ID */
     switch (dtype) {
     case NID_sha256:
         alg = CALG_SHA_256;
@@ -877,13 +901,13 @@ int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
         }
     }
 
-/* Create the hash object */
+    /* Create the hash object */
     if (!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) {
         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT);
         capi_addlasterror();
         return -1;
     }
-/* Set the hash value to the value passed */
+    /* Set the hash value to the value passed */
 
     if (!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) {
         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE);
@@ -891,7 +915,7 @@ int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
         goto err;
     }
 
-/* Finally sign it */
+    /* Finally sign it */
     slen = RSA_size(rsa);
     if (!CryptSignHash(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) {
         CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH);
@@ -924,6 +948,7 @@ int capi_rsa_priv_dec(int flen, const unsigned char *from,
     unsigned char *tmpbuf;
     CAPI_KEY *capi_key;
     CAPI_CTX *ctx;
+    DWORD flags = 0;
     DWORD dlen;
 
     if (flen <= 0)
@@ -939,32 +964,43 @@ int capi_rsa_priv_dec(int flen, const unsigned char *from,
         return -1;
     }
 
-    if (padding != RSA_PKCS1_PADDING) {
-        char errstr[10];
-        BIO_snprintf(errstr, 10, "%d", padding);
-        CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
-        ERR_add_error_data(2, "padding=", errstr);
-        return -1;
+    switch (padding) {
+    case RSA_PKCS1_PADDING:
+        /* Nothing to do */
+        break;
+#ifdef CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
+    case RSA_NO_PADDING:
+        flags = CRYPT_DECRYPT_RSA_NO_PADDING_CHECK;
+        break;
+#endif
+    default:
+        {
+            char errstr[10];
+            BIO_snprintf(errstr, 10, "%d", padding);
+            CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING);
+            ERR_add_error_data(2, "padding=", errstr);
+            return -1;
+        }
     }
 
     /* Create temp reverse order version of input */
-    if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
-        CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
+    if ((tmpbuf = OPENSSL_malloc(flen)) == NULL)
         return -1;
-    }
     for (i = 0; i < flen; i++)
         tmpbuf[flen - i - 1] = from[i];
 
     /* Finally decrypt it */
     dlen = flen;
-    if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
+    if (!CryptDecrypt(capi_key->key, 0, TRUE, flags, tmpbuf, &dlen)) {
         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
         capi_addlasterror();
+        OPENSSL_cleanse(tmpbuf, dlen);
         OPENSSL_free(tmpbuf);
         return -1;
-    } else
+    } else {
         memcpy(to, tmpbuf, (flen = (int)dlen));
-
+    }
+    OPENSSL_cleanse(tmpbuf, flen);
     OPENSSL_free(tmpbuf);
 
     return flen;
@@ -1029,17 +1065,17 @@ static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
         capi_addlasterror();
         goto err;
     } else {
-        BIGNUM *r = NULL, *s = NULL;
-        ret = DSA_SIG_new();
-        if (ret == NULL)
-            goto err;
-        DSA_SIG_get0(&r, &s, ret);
-        if (!lend_tobn(r, csigbuf, 20)
-            || !lend_tobn(s, csigbuf + 20, 20)) {
-            DSA_SIG_free(ret);
-            ret = NULL;
+        BIGNUM *r = BN_new(), *s = BN_new();
+
+        if (r == NULL || s == NULL
+            || !lend_tobn(r, csigbuf, 20)
+            || !lend_tobn(s, csigbuf + 20, 20)
+            || (ret = DSA_SIG_new()) == NULL) {
+            BN_free(r); /* BN_free checks for BIGNUM * being NULL */
+            BN_free(s);
             goto err;
         }
+        DSA_SIG_set0(ret, r, s);
     }
 
     /* Now cleanup */
@@ -1060,7 +1096,7 @@ static int capi_dsa_free(DSA *dsa)
 }
 # endif
 
-static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
+static void capi_vtrace(CAPI_CTX *ctx, int level, char *format,
                         va_list argptr)
 {
     BIO *out;
@@ -1076,7 +1112,7 @@ static void capi_vtrace(CAPI_CTX * ctx, int level, char *format,
     BIO_free(out);
 }
 
-static void CAPI_trace(CAPI_CTX * ctx, char *format, ...)
+static void CAPI_trace(CAPI_CTX *ctx, char *format, ...)
 {
     va_list args;
     va_start(args, format);
@@ -1100,20 +1136,27 @@ static char *wide_to_asc(LPCWSTR wstr)
 {
     char *str;
     int len_0, sz;
+    size_t len_1;
 
     if (!wstr)
         return NULL;
-    len_0 = (int)wcslen(wstr) + 1; /* WideCharToMultiByte expects int */
+
+    len_1 = wcslen(wstr) + 1;
+
+    if (len_1 > INT_MAX) {
+           CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_FUNCTION_NOT_SUPPORTED);
+           return NULL;
+    }
+
+    len_0 = (int)len_1; /* WideCharToMultiByte expects int */
     sz = WideCharToMultiByte(CP_ACP, 0, wstr, len_0, NULL, 0, NULL, NULL);
     if (!sz) {
         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
         return NULL;
     }
     str = OPENSSL_malloc(sz);
-    if (str == NULL) {
-        CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
+    if (str == NULL)
         return NULL;
-    }
     if (!WideCharToMultiByte(CP_ACP, 0, wstr, len_0, str, sz, NULL, NULL)) {
         OPENSSL_free(str);
         CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR);
@@ -1122,7 +1165,7 @@ static char *wide_to_asc(LPCWSTR wstr)
     return str;
 }
 
-static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
+static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype,
                              DWORD idx)
 {
     DWORD len, err;
@@ -1137,10 +1180,8 @@ static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
         return 0;
     }
     name = OPENSSL_malloc(len);
-    if (name == NULL) {
-        CAPIerr(CAPI_F_CAPI_GET_PROVNAME, ERR_R_MALLOC_FAILURE);
+    if (name == NULL)
         return 0;
-    }
     if (!CryptEnumProviders(idx, NULL, 0, ptype, name, &len)) {
         err = GetLastError();
         OPENSSL_free(name);
@@ -1155,15 +1196,16 @@ static int capi_get_provname(CAPI_CTX * ctx, LPSTR * pname, DWORD * ptype,
         OPENSSL_free(name);
         if (*pname == NULL)
             return 0;
-    } else
+    } else {
         *pname = (char *)name;
+    }
     CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", *pname,
                *ptype);
 
     return 1;
 }
 
-static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
+static int capi_list_providers(CAPI_CTX *ctx, BIO *out)
 {
     DWORD idx, ptype;
     int ret;
@@ -1182,39 +1224,38 @@ static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
     return 1;
 }
 
-static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
+static int capi_list_containers(CAPI_CTX *ctx, BIO *out)
 {
     int ret = 1;
     HCRYPTPROV hprov;
     DWORD err, idx, flags, buflen = 0, clen;
     LPSTR cname;
-    LPTSTR cspname = NULL;
+    LPWSTR cspname = NULL;
 
     CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname,
                ctx->csptype);
-    if (ctx->cspname && sizeof(TCHAR) != sizeof(char)) {
-        if ((clen =
-             MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))) {
+    if (ctx->cspname != NULL) {
+        if ((clen = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
+                                        NULL, 0))) {
             cspname = alloca(clen * sizeof(WCHAR));
             MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, (WCHAR *)cspname,
                                 clen);
         }
-        if (!cspname) {
+        if (cspname == NULL) {
             CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
             capi_addlasterror();
             return 0;
         }
-    } else
-        cspname = (TCHAR *)ctx->cspname;
-    if (!CryptAcquireContext
-        (&hprov, NULL, cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) {
+    }
+    if (!CryptAcquireContextW(&hprov, NULL, cspname, ctx->csptype,
+                              CRYPT_VERIFYCONTEXT)) {
         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS,
                 CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
         capi_addlasterror();
         return 0;
     }
-    if (!CryptGetProvParam
-        (hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) {
+    if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen,
+                           CRYPT_FIRST)) {
         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR);
         capi_addlasterror();
         CryptReleaseContext(hprov, 0);
@@ -1224,10 +1265,8 @@ static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
     if (buflen == 0)
         buflen = 1024;
     cname = OPENSSL_malloc(buflen);
-    if (cname == NULL) {
-        CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
+    if (cname == NULL)
         goto err;
-    }
 
     for (idx = 0;; idx++) {
         clen = buflen;
@@ -1237,8 +1276,8 @@ static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
             flags = CRYPT_FIRST;
         else
             flags = 0;
-        if (!CryptGetProvParam
-            (hprov, PP_ENUMCONTAINERS, (BYTE *) cname, &clen, flags)) {
+        if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, (BYTE *)cname,
+                               &clen, flags)) {
             err = GetLastError();
             if (err == ERROR_NO_MORE_ITEMS)
                 goto done;
@@ -1265,21 +1304,20 @@ static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
     return ret;
 }
 
-static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
+static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx,
+                                               PCCERT_CONTEXT cert)
 {
     DWORD len;
     CRYPT_KEY_PROV_INFO *pinfo;
 
-    if (!CertGetCertificateContextProperty
-        (cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len))
+    if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
+                                           NULL, &len))
         return NULL;
     pinfo = OPENSSL_malloc(len);
-    if (pinfo == NULL) {
-        CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
+    if (pinfo == NULL)
         return NULL;
-    }
-    if (!CertGetCertificateContextProperty
-        (cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) {
+    if (!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
+                                           pinfo, &len)) {
         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO,
                 CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO);
         capi_addlasterror();
@@ -1289,17 +1327,18 @@ static CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT ce
     return pinfo;
 }
 
-static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
-                                CRYPT_KEY_PROV_INFO * pinfo)
+static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out,
+                                CRYPT_KEY_PROV_INFO *pinfo)
 {
     char *provname = NULL, *contname = NULL;
-    if (!pinfo) {
+
+    if (pinfo == NULL) {
         BIO_printf(out, "  No Private Key\n");
         return;
     }
     provname = wide_to_asc(pinfo->pwszProvName);
     contname = wide_to_asc(pinfo->pwszContainerName);
-    if (!provname || !contname)
+    if (provname == NULL || contname == NULL)
         goto err;
 
     BIO_printf(out, "  Private Key Info:\n");
@@ -1312,20 +1351,20 @@ static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
     OPENSSL_free(contname);
 }
 
-static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
+static char *capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
 {
     LPWSTR wfname;
     DWORD dlen;
 
     CAPI_trace(ctx, "capi_cert_get_fname\n");
-    if (!CertGetCertificateContextProperty
-        (cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen))
+    if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
+                                           NULL, &dlen))
         return NULL;
     wfname = OPENSSL_malloc(dlen);
     if (wfname == NULL)
         return NULL;
-    if (CertGetCertificateContextProperty
-        (cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) {
+    if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
+                                          wfname, &dlen)) {
         char *fname = wide_to_asc(wfname);
         OPENSSL_free(wfname);
         return fname;
@@ -1337,7 +1376,7 @@ static char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
     return NULL;
 }
 
-static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
+static void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert)
 {
     X509 *x;
     const unsigned char *p;
@@ -1348,8 +1387,9 @@ static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
         if (fname) {
             BIO_printf(out, "  Friendly Name \"%s\"\n", fname);
             OPENSSL_free(fname);
-        } else
+        } else {
             BIO_printf(out, "  <No Friendly Name>\n");
+        }
     }
 
     p = cert->pbCertEncoded;
@@ -1378,7 +1418,7 @@ static void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
     X509_free(x);
 }
 
-static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
+static HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
 {
     HCERTSTORE hstore;
 
@@ -1397,7 +1437,7 @@ static HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
     return hstore;
 }
 
-int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
+int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id)
 {
     char *storename;
     int idx;
@@ -1435,7 +1475,7 @@ int capi_list_certs(CAPI_CTX * ctx, BIO *out, char *id)
     return ret;
 }
 
-static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
+static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id,
                                      HCERTSTORE hstore)
 {
     PCCERT_CONTEXT cert = NULL;
@@ -1443,8 +1483,7 @@ static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
     int match;
     switch (ctx->lookup_method) {
     case CAPI_LU_SUBSTR:
-        return CertFindCertificateInStore(hstore,
-                                          X509_ASN_ENCODING, 0,
+        return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0,
                                           CERT_FIND_SUBJECT_STR_A, id, NULL);
     case CAPI_LU_FNAME:
         for (;;) {
@@ -1467,8 +1506,9 @@ static PCCERT_CONTEXT capi_find_cert(CAPI_CTX * ctx, const char *id,
     }
 }
 
-static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
-                              TCHAR *provname, DWORD ptype, DWORD keyspec)
+static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const WCHAR *contname,
+                              const WCHAR *provname, DWORD ptype,
+                              DWORD keyspec)
 {
     DWORD dwFlags = 0;
     CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
@@ -1476,17 +1516,18 @@ static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
     if (key == NULL)
         return NULL;
     /* If PROV_RSA_AES supported use it instead */
-    if (ptype == PROV_RSA_FULL && use_aes_csp) {
-        provname = NULL;
+    if (ptype == PROV_RSA_FULL && use_aes_csp &&
+        wcscmp(provname, rsa_enh_cspname) == 0) {
+        provname = rsa_aes_cspname;
         ptype = PROV_RSA_AES;
-        CAPI_trace(ctx, "capi_get_key, contname=%s, RSA_AES_CSP\n", contname);
-    } else if (sizeof(TCHAR) == sizeof(char)) {
-        CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
-                   contname, provname, ptype);
-    } else if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
-        /* above 'if' is optimization to minimize malloc-ations */
-        char *_contname = wide_to_asc((WCHAR *)contname);
-        char *_provname = wide_to_asc((WCHAR *)provname);
+    }
+    if (ctx && ctx->debug_level >= CAPI_DBG_TRACE && ctx->debug_file) {
+        /*
+         * above 'if' is [complementary] copy from CAPI_trace and serves
+         * as optimization to minimize [below] malloc-ations
+         */
+        char *_contname = wide_to_asc(contname);
+        char *_provname = wide_to_asc(provname);
 
         CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n",
                    _contname, _provname, ptype);
@@ -1495,7 +1536,8 @@ static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
     }
     if (ctx->store_flags & CERT_SYSTEM_STORE_LOCAL_MACHINE)
         dwFlags = CRYPT_MACHINE_KEYSET;
-    if (!CryptAcquireContext(&key->hprov, contname, provname, ptype, dwFlags)) {
+    if (!CryptAcquireContextW(&key->hprov, contname, provname, ptype,
+                              dwFlags)) {
         CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
         capi_addlasterror();
         goto err;
@@ -1515,39 +1557,27 @@ static CAPI_KEY *capi_get_key(CAPI_CTX * ctx, const TCHAR *contname,
     return NULL;
 }
 
-static CAPI_KEY *capi_get_cert_key(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
+static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert)
 {
     CAPI_KEY *key = NULL;
     CRYPT_KEY_PROV_INFO *pinfo = NULL;
-    char *provname = NULL, *contname = NULL;
+
     pinfo = capi_get_prov_info(ctx, cert);
-    if (!pinfo)
-        goto err;
-    if (sizeof(TCHAR) != sizeof(char))
-        key = capi_get_key(ctx, (TCHAR *)pinfo->pwszContainerName,
-                           (TCHAR *)pinfo->pwszProvName,
-                           pinfo->dwProvType, pinfo->dwKeySpec);
-    else {
-        provname = wide_to_asc(pinfo->pwszProvName);
-        contname = wide_to_asc(pinfo->pwszContainerName);
-        if (!provname || !contname)
-            goto err;
-        key = capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
+
+    if (pinfo != NULL)
+        key = capi_get_key(ctx, pinfo->pwszContainerName, pinfo->pwszProvName,
                            pinfo->dwProvType, pinfo->dwKeySpec);
-    }
 
- err:
     OPENSSL_free(pinfo);
-    OPENSSL_free(provname);
-    OPENSSL_free(contname);
     return key;
 }
 
-CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
+CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id)
 {
     PCCERT_CONTEXT cert;
     HCERTSTORE hstore;
     CAPI_KEY *key = NULL;
+
     switch (ctx->lookup_method) {
     case CAPI_LU_SUBSTR:
     case CAPI_LU_FNAME:
@@ -1563,36 +1593,28 @@ CAPI_KEY *capi_find_key(CAPI_CTX * ctx, const char *id)
         break;
 
     case CAPI_LU_CONTNAME:
-        if (sizeof(TCHAR) != sizeof(char)) {
+        {
             WCHAR *contname, *provname;
             DWORD len;
 
             if ((len = MultiByteToWideChar(CP_ACP, 0, id, -1, NULL, 0)) &&
                 (contname = alloca(len * sizeof(WCHAR)),
                  MultiByteToWideChar(CP_ACP, 0, id, -1, contname, len)) &&
-                (len =
-                 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1, NULL, 0))
-                && (provname =
-                    alloca(len * sizeof(WCHAR)), MultiByteToWideChar(CP_ACP,
-                                                                     0,
-                                                                     ctx->cspname,
-                                                                     -1,
-                                                                     provname,
-                                                                     len)))
-                key =
-                    capi_get_key(ctx, (TCHAR *)contname, (TCHAR *)provname,
-                                 ctx->csptype, ctx->keytype);
-        } else
-            key = capi_get_key(ctx, (TCHAR *)id,
-                               (TCHAR *)ctx->cspname,
-                               ctx->csptype, ctx->keytype);
+                (len = MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
+                                           NULL, 0)) &&
+                (provname = alloca(len * sizeof(WCHAR)),
+                 MultiByteToWideChar(CP_ACP, 0, ctx->cspname, -1,
+                                     provname, len)))
+                key = capi_get_key(ctx, contname, provname,
+                                   ctx->csptype, ctx->keytype);
+        }
         break;
     }
 
     return key;
 }
 
-void capi_free_key(CAPI_KEY * key)
+void capi_free_key(CAPI_KEY *key)
 {
     if (!key)
         return;
@@ -1609,10 +1631,8 @@ static CAPI_CTX *capi_ctx_new(void)
 {
     CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
 
-    if (ctx == NULL) {
-        CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
+    if (ctx == NULL)
         return NULL;
-    }
     ctx->csptype = PROV_RSA_FULL;
     ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
     ctx->keytype = AT_KEYEXCHANGE;
@@ -1623,7 +1643,7 @@ static CAPI_CTX *capi_ctx_new(void)
     return ctx;
 }
 
-static void capi_ctx_free(CAPI_CTX * ctx)
+static void capi_ctx_free(CAPI_CTX *ctx)
 {
     CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx);
     if (!ctx)
@@ -1635,7 +1655,7 @@ static void capi_ctx_free(CAPI_CTX * ctx)
     OPENSSL_free(ctx);
 }
 
-static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
+static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type,
                                  int check)
 {
     LPSTR tmpcspname;
@@ -1643,19 +1663,15 @@ static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
     CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
     if (check) {
         HCRYPTPROV hprov;
-        LPTSTR name = NULL;
+        LPWSTR name = NULL;
+        DWORD len;
 
-        if (sizeof(TCHAR) != sizeof(char)) {
-            DWORD len;
-            if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
-                name = alloca(len * sizeof(WCHAR));
-                MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
-            }
-        } else
-            name = (TCHAR *)pname;
-
-        if (!name || !CryptAcquireContext(&hprov, NULL, name, type,
-                                          CRYPT_VERIFYCONTEXT)) {
+        if ((len = MultiByteToWideChar(CP_ACP, 0, pname, -1, NULL, 0))) {
+            name = alloca(len * sizeof(WCHAR));
+            MultiByteToWideChar(CP_ACP, 0, pname, -1, (WCHAR *)name, len);
+        }
+        if (name == NULL || !CryptAcquireContextW(&hprov, NULL, name, type,
+                                                  CRYPT_VERIFYCONTEXT)) {
             CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME,
                     CAPI_R_CRYPTACQUIRECONTEXT_ERROR);
             capi_addlasterror();
@@ -1664,17 +1680,15 @@ static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
         CryptReleaseContext(hprov, 0);
     }
     tmpcspname = OPENSSL_strdup(pname);
-    if (tmpcspname == NULL) {
-        CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
+    if (tmpcspname == NULL)
         return 0;
-    }
     OPENSSL_free(ctx->cspname);
     ctx->cspname = tmpcspname;
     ctx->csptype = type;
     return 1;
 }
 
-static int capi_ctx_set_provname_idx(CAPI_CTX * ctx, int idx)
+static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx)
 {
     LPSTR pname;
     DWORD type;
@@ -1758,9 +1772,9 @@ static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
                 certs = sk_X509_new_null();
 
             sk_X509_push(certs, x);
-        } else
+        } else {
             X509_free(x);
-
+        }
     }
 
     if (cert)
@@ -1790,7 +1804,7 @@ static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
 
     sk_X509_free(certs);
 
-    if (!*pcert)
+    if (*pcert == NULL)
         return 0;
 
     /* Setup key for selected certificate */