openssl req: don't try to report bits
[openssl.git] / engines / e_capi.c
index 2373d6903337a3c48536ce4f0cccf9afd0c8ba81..a7658922f3870a9f288bac543b6ad044844310d0 100644 (file)
@@ -1,64 +1,29 @@
-/* engines/e_capi.c */
 /*
- * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
- * project.
- */
-/* ====================================================================
- * Copyright (c) 2008 The OpenSSL Project.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. All advertising materials mentioning features or use of this
- *    software must display the following acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
- *
- * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
- *    endorse or promote products derived from this software without
- *    prior written permission. For written permission, please contact
- *    licensing@OpenSSL.org.
- *
- * 5. Products derived from this software may not be called "OpenSSL"
- *    nor may "OpenSSL" appear in their names without prior written
- *    permission of the OpenSSL Project.
+ * Copyright 2008-2018 The OpenSSL Project Authors. All Rights Reserved.
  *
- * 6. Redistributions of any form whatsoever must retain the following
- *    acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
- *
- * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
- * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- * ====================================================================
+ * Licensed under the OpenSSL license (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>
+#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>
+# 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
@@ -95,7 +49,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
+#  define PROV_RSA_AES 24
 # endif
 
 # include <openssl/engine.h>
@@ -150,17 +108,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);
@@ -173,9 +131,11 @@ static int capi_rsa_priv_dec(int flen, const unsigned char *from,
                              unsigned char *to, RSA *rsa, int padding);
 static int capi_rsa_free(RSA *rsa);
 
+# ifndef OPENSSL_NO_DSA
 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
                                  DSA *dsa);
 static int capi_dsa_free(DSA *dsa);
+# endif
 
 static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
                                      STACK_OF(X509_NAME) *ca_dn, X509 **pcert,
@@ -188,9 +148,11 @@ static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
 static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs);
 # endif
 
-typedef PCCERT_CONTEXT(WINAPI *CERTDLG) (HCERTSTORE, HWND, LPCWSTR,
-                                         LPCWSTR, DWORD, DWORD, void *);
-typedef HWND(WINAPI *GETCONSWIN) (void);
+void engine_load_capi_int(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
@@ -213,37 +175,28 @@ 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;
     GETCONSWIN getconswindow;
 };
 
-static CAPI_CTX *capi_ctx_new();
-static void capi_ctx_free(CAPI_CTX * ctx);
-static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
+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,
                                  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)
@@ -332,6 +285,7 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
     int ret = 1;
     CAPI_CTX *ctx;
     BIO *out;
+    LPSTR tmpstr;
     if (capi_idx == -1) {
         CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED);
         return 0;
@@ -360,10 +314,15 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
         break;
 
     case CAPI_CMD_STORE_NAME:
-        if (ctx->storename)
+        tmpstr = OPENSSL_strdup(p);
+        if (tmpstr != NULL) {
             OPENSSL_free(ctx->storename);
-        ctx->storename = BUF_strdup(p);
-        CAPI_trace(ctx, "Setting store name to %s\n", p);
+            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;
 
     case CAPI_CMD_STORE_FLAGS:
@@ -383,8 +342,14 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
         break;
 
     case CAPI_CMD_DEBUG_FILE:
-        ctx->debug_file = BUF_strdup(p);
-        CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file);
+        tmpstr = OPENSSL_strdup(p);
+        if (tmpstr != NULL) {
+            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;
 
     case CAPI_CMD_KEYTYPE:
@@ -427,42 +392,25 @@ static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
 
 }
 
-static RSA_METHOD capi_rsa_method = {
-    "CryptoAPI RSA method",
-    0,                          /* pub_enc */
-    0,                          /* pub_dec */
-    capi_rsa_priv_enc,          /* priv_enc */
-    capi_rsa_priv_dec,          /* priv_dec */
-    0,                          /* rsa_mod_exp */
-    0,                          /* bn_mod_exp */
-    0,                          /* init */
-    capi_rsa_free,              /* finish */
-    RSA_FLAG_SIGN_VER,          /* flags */
-    NULL,                       /* app_data */
-    capi_rsa_sign,              /* rsa_sign */
-    0                           /* rsa_verify */
-};
+static RSA_METHOD *capi_rsa_method = NULL;
+# ifndef OPENSSL_NO_DSA
+static DSA_METHOD *capi_dsa_method = NULL;
+# endif
 
-static DSA_METHOD capi_dsa_method = {
-    "CryptoAPI DSA method",
-    capi_dsa_do_sign,           /* dsa_do_sign */
-    0,                          /* dsa_sign_setup */
-    0,                          /* dsa_do_verify */
-    0,                          /* dsa_mod_exp */
-    0,                          /* bn_mod_exp */
-    0,                          /* init */
-    capi_dsa_free,              /* finish */
-    0,                          /* flags */
-    NULL,                       /* app_data */
-    0,                          /* dsa_paramgen */
-    0                           /* dsa_keygen */
-};
+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)
 {
     CAPI_CTX *ctx;
     const RSA_METHOD *ossl_rsa_meth;
+# ifndef OPENSSL_NO_DSA
     const DSA_METHOD *ossl_dsa_meth;
+# endif
+    HCRYPTPROV hprov;
 
     if (capi_idx < 0) {
         capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
@@ -473,22 +421,41 @@ static int capi_init(ENGINE *e)
 
         /* Setup RSA_METHOD */
         rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0);
-        ossl_rsa_meth = RSA_PKCS1_SSLeay();
-        capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc;
-        capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec;
-        capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp;
-        capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp;
+        ossl_rsa_meth = RSA_PKCS1_OpenSSL();
+        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))
+            || !RSA_meth_set_priv_enc(capi_rsa_method, capi_rsa_priv_enc)
+            || !RSA_meth_set_priv_dec(capi_rsa_method, capi_rsa_priv_dec)
+            || !RSA_meth_set_mod_exp(capi_rsa_method,
+                                     RSA_meth_get_mod_exp(ossl_rsa_meth))
+            || !RSA_meth_set_bn_mod_exp(capi_rsa_method,
+                                        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;
+        }
 
+# 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();
-        capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify;
-        capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp;
-        capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp;
+        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)
+            || !DSA_meth_set_mod_exp(capi_dsa_method,
+                                     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;
+        }
+# endif
     }
 
     ctx = capi_ctx_new();
-    if (!ctx)
+    if (ctx == NULL)
         goto memerr;
 
     ENGINE_set_ex_data(e, capi_idx, ctx);
@@ -509,6 +476,13 @@ static int capi_init(ENGINE *e)
     }
 # endif
 
+    /* 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:
@@ -520,6 +494,12 @@ static int capi_init(ENGINE *e)
 
 static int capi_destroy(ENGINE *e)
 {
+    RSA_meth_free(capi_rsa_method);
+    capi_rsa_method = NULL;
+# ifndef OPENSSL_NO_DSA
+    DSA_meth_free(capi_dsa_method);
+    capi_dsa_method = NULL;
+# endif
     ERR_unload_CAPI_strings();
     return 1;
 }
@@ -549,24 +529,41 @@ struct CAPI_KEY_st {
 
 static int bind_capi(ENGINE *e)
 {
+    capi_rsa_method = RSA_meth_new("CryptoAPI RSA method", 0);
+    if (capi_rsa_method == NULL)
+        return 0;
+# ifndef OPENSSL_NO_DSA
+    capi_dsa_method = DSA_meth_new("CryptoAPI DSA method", 0);
+    if (capi_dsa_method == NULL)
+        goto memerr;
+# endif
     if (!ENGINE_set_id(e, engine_capi_id)
         || !ENGINE_set_name(e, engine_capi_name)
         || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL)
         || !ENGINE_set_init_function(e, capi_init)
         || !ENGINE_set_finish_function(e, capi_finish)
         || !ENGINE_set_destroy_function(e, capi_destroy)
-        || !ENGINE_set_RSA(e, &capi_rsa_method)
-        || !ENGINE_set_DSA(e, &capi_dsa_method)
+        || !ENGINE_set_RSA(e, capi_rsa_method)
+# ifndef OPENSSL_NO_DSA
+        || !ENGINE_set_DSA(e, capi_dsa_method)
+# endif
         || !ENGINE_set_load_privkey_function(e, capi_load_privkey)
         || !ENGINE_set_load_ssl_client_cert_function(e,
                                                      capi_load_ssl_client_cert)
         || !ENGINE_set_cmd_defns(e, capi_cmd_defns)
         || !ENGINE_set_ctrl_function(e, capi_ctrl))
-        return 0;
+        goto memerr;
     ERR_load_CAPI_strings();
 
     return 1;
-
+ memerr:
+    RSA_meth_free(capi_rsa_method);
+    capi_rsa_method = NULL;
+# ifndef OPENSSL_NO_DSA
+    DSA_meth_free(capi_dsa_method);
+    capi_dsa_method = NULL;
+# endif
+    return 0;
 }
 
 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
@@ -580,12 +577,12 @@ 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)
 {
     ENGINE *ret = ENGINE_new();
-    if (!ret)
+    if (ret == NULL)
         return NULL;
     if (!bind_capi(ret)) {
         ENGINE_free(ret);
@@ -594,7 +591,7 @@ static ENGINE *engine_capi(void)
     return ret;
 }
 
-void ENGINE_load_capi(void)
+void engine_load_capi_int(void)
 {
     /* Copied from eng_[openssl|dyn].c */
     ENGINE *toadd = engine_capi();
@@ -628,7 +625,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;
@@ -644,7 +641,7 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
 
     pubkey = OPENSSL_malloc(len);
 
-    if (!pubkey)
+    if (pubkey == NULL)
         goto memerr;
 
     if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) {
@@ -661,6 +658,7 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
     if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) {
         RSAPUBKEY *rp;
         DWORD rsa_modlen;
+        BIGNUM *e = NULL, *n = NULL;
         unsigned char *rsa_modulus;
         rp = (RSAPUBKEY *) (bh + 1);
         if (rp->magic != 0x31415352) {
@@ -676,31 +674,38 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
         if (!rkey)
             goto memerr;
 
-        rkey->e = BN_new();
-        rkey->n = BN_new();
+        e = BN_new();
+        n = BN_new();
 
-        if (!rkey->e || !rkey->n)
+        if (e == NULL || n == NULL) {
+            BN_free(e);
+            BN_free(n);
             goto memerr;
+        }
+
+        RSA_set0_key(rkey, n, e, NULL);
 
-        if (!BN_set_word(rkey->e, rp->pubexp))
+        if (!BN_set_word(e, rp->pubexp))
             goto memerr;
 
         rsa_modlen = rp->bitlen / 8;
-        if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen))
+        if (!lend_tobn(n, rsa_modulus, rsa_modlen))
             goto memerr;
 
         RSA_set_ex_data(rkey, rsa_capi_idx, key);
 
-        if (!(ret = EVP_PKEY_new()))
+        if ((ret = EVP_PKEY_new()) == NULL)
             goto memerr;
 
         EVP_PKEY_assign_RSA(ret, rkey);
         rkey = NULL;
 
+# ifndef OPENSSL_NO_DSA
     } else if (bh->aiKeyAlg == CALG_DSS_SIGN) {
         DSSPUBKEY *dp;
         DWORD dsa_plen;
         unsigned char *btmp;
+        BIGNUM *p, *q, *g, *pub_key;
         dp = (DSSPUBKEY *) (bh + 1);
         if (dp->magic != 0x31535344) {
             char magstr[10];
@@ -715,35 +720,43 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
         dkey = DSA_new_method(eng);
         if (!dkey)
             goto memerr;
-        dkey->p = BN_new();
-        dkey->q = BN_new();
-        dkey->g = BN_new();
-        dkey->pub_key = BN_new();
-        if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key)
+        p = BN_new();
+        q = BN_new();
+        g = BN_new();
+        pub_key = BN_new();
+        if (p == NULL || q == NULL || g == NULL || pub_key == NULL) {
+            BN_free(p);
+            BN_free(q);
+            BN_free(g);
+            BN_free(pub_key);
             goto memerr;
-        if (!lend_tobn(dkey->p, btmp, dsa_plen))
+        }
+        DSA_set0_pqg(dkey, p, q, g);
+        DSA_set0_key(dkey, pub_key, NULL);
+        if (!lend_tobn(p, btmp, dsa_plen))
             goto memerr;
         btmp += dsa_plen;
-        if (!lend_tobn(dkey->q, btmp, 20))
+        if (!lend_tobn(q, btmp, 20))
             goto memerr;
         btmp += 20;
-        if (!lend_tobn(dkey->g, btmp, dsa_plen))
+        if (!lend_tobn(g, btmp, dsa_plen))
             goto memerr;
         btmp += dsa_plen;
-        if (!lend_tobn(dkey->pub_key, btmp, dsa_plen))
+        if (!lend_tobn(pub_key, btmp, dsa_plen))
             goto memerr;
         btmp += dsa_plen;
 
         DSA_set_ex_data(dkey, dsa_capi_idx, key);
 
-        if (!(ret = EVP_PKEY_new()))
+        if ((ret = EVP_PKEY_new()) == NULL)
             goto memerr;
 
         EVP_PKEY_assign_DSA(ret, dkey);
         dkey = NULL;
+# endif
     } else {
         char algstr[10];
-        BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg);
+        BIO_snprintf(algstr, 10, "%ux", bh->aiKeyAlg);
         CAPIerr(CAPI_F_CAPI_GET_PKEY,
                 CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM);
         ERR_add_error_data(2, "aiKeyAlg=0x", algstr);
@@ -751,11 +764,12 @@ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY * key)
     }
 
  err:
-    if (pubkey)
-        OPENSSL_free(pubkey);
+    OPENSSL_free(pubkey);
     if (!ret) {
         RSA_free(rkey);
+# ifndef OPENSSL_NO_DSA
         DSA_free(dkey);
+# endif
     }
 
     return ret;
@@ -812,7 +826,7 @@ int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
     CAPI_KEY *capi_key;
     CAPI_CTX *ctx;
 
-    ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
+    ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
 
     CAPI_trace(ctx, "Called CAPI_rsa_sign()\n");
 
@@ -821,7 +835,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;
@@ -849,20 +863,20 @@ int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len,
     default:
         {
             char algstr[10];
-            BIO_snprintf(algstr, 10, "%lx", dtype);
+            BIO_snprintf(algstr, 10, "%x", dtype);
             CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID);
             ERR_add_error_data(2, "NID=0x", algstr);
             return -1;
         }
     }
 
-/* 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);
@@ -870,7 +884,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);
@@ -903,7 +917,12 @@ int capi_rsa_priv_dec(int flen, const unsigned char *from,
     unsigned char *tmpbuf;
     CAPI_KEY *capi_key;
     CAPI_CTX *ctx;
-    ctx = ENGINE_get_ex_data(rsa->engine, capi_idx);
+    DWORD dlen;
+
+    if (flen <= 0)
+        return flen;
+
+    ctx = ENGINE_get_ex_data(RSA_get0_engine(rsa), capi_idx);
 
     CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n");
 
@@ -922,7 +941,7 @@ int capi_rsa_priv_dec(int flen, const unsigned char *from,
     }
 
     /* Create temp reverse order version of input */
-    if (!(tmpbuf = OPENSSL_malloc(flen))) {
+    if ((tmpbuf = OPENSSL_malloc(flen)) == NULL) {
         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE);
         return -1;
     }
@@ -930,14 +949,15 @@ int capi_rsa_priv_dec(int flen, const unsigned char *from,
         tmpbuf[flen - i - 1] = from[i];
 
     /* Finally decrypt it */
-    if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) {
+    dlen = flen;
+    if (!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &dlen)) {
         CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR);
         capi_addlasterror();
         OPENSSL_free(tmpbuf);
         return -1;
-    } else
-        memcpy(to, tmpbuf, flen);
-
+    } else {
+        memcpy(to, tmpbuf, (flen = (int)dlen));
+    }
     OPENSSL_free(tmpbuf);
 
     return flen;
@@ -952,6 +972,7 @@ static int capi_rsa_free(RSA *rsa)
     return 1;
 }
 
+# ifndef OPENSSL_NO_DSA
 /* CryptoAPI DSA operations */
 
 static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
@@ -964,7 +985,7 @@ static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
     CAPI_CTX *ctx;
     unsigned char csigbuf[40];
 
-    ctx = ENGINE_get_ex_data(dsa->engine, capi_idx);
+    ctx = ENGINE_get_ex_data(DSA_get0_engine(dsa), capi_idx);
 
     CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n");
 
@@ -1001,19 +1022,17 @@ static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen,
         capi_addlasterror();
         goto err;
     } else {
-        ret = DSA_SIG_new();
-        if (!ret)
-            goto err;
-        ret->r = BN_new();
-        ret->s = BN_new();
-        if (!ret->r || !ret->s)
-            goto err;
-        if (!lend_tobn(ret->r, csigbuf, 20)
-            || !lend_tobn(ret->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 */
@@ -1032,8 +1051,9 @@ static int capi_dsa_free(DSA *dsa)
     DSA_set_ex_data(dsa, dsa_capi_idx, 0);
     return 1;
 }
+# 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;
@@ -1049,7 +1069,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);
@@ -1083,7 +1103,7 @@ static char *wide_to_asc(LPCWSTR wstr)
         return NULL;
     }
     str = OPENSSL_malloc(sz);
-    if (!str) {
+    if (str == NULL) {
         CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
@@ -1095,7 +1115,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;
@@ -1128,15 +1148,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;
@@ -1149,45 +1170,44 @@ static int capi_list_providers(CAPI_CTX * ctx, BIO *out)
             break;
         if (ret == 0)
             break;
-        BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype);
+        BIO_printf(out, "%lu. %s, type %lu\n", idx, provname, ptype);
         OPENSSL_free(provname);
     }
     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);
@@ -1197,7 +1217,7 @@ static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
     if (buflen == 0)
         buflen = 1024;
     cname = OPENSSL_malloc(buflen);
-    if (!cname) {
+    if (cname == NULL) {
         CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE);
         goto err;
     }
@@ -1210,8 +1230,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;
@@ -1225,35 +1245,35 @@ static int capi_list_containers(CAPI_CTX * ctx, BIO *out)
             CAPI_trace(ctx, "Enumerate bug: using workaround\n");
             goto done;
         }
-        BIO_printf(out, "%d. %s\n", idx, cname);
+        BIO_printf(out, "%lu. %s\n", idx, cname);
     }
  err:
 
     ret = 0;
 
  done:
-    if (cname)
-        OPENSSL_free(cname);
+    OPENSSL_free(cname);
     CryptReleaseContext(hprov, 0);
 
     return ret;
 }
 
-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) {
+    if (pinfo == NULL) {
         CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE);
         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();
@@ -1263,8 +1283,8 @@ CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
     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) {
@@ -1277,31 +1297,29 @@ static void capi_dump_prov_info(CAPI_CTX * ctx, BIO *out,
         goto err;
 
     BIO_printf(out, "  Private Key Info:\n");
-    BIO_printf(out, "    Provider Name:  %s, Provider Type %d\n", provname,
+    BIO_printf(out, "    Provider Name:  %s, Provider Type %lu\n", provname,
                pinfo->dwProvType);
-    BIO_printf(out, "    Container Name: %s, Key Type %d\n", contname,
+    BIO_printf(out, "    Container Name: %s, Key Type %lu\n", contname,
                pinfo->dwKeySpec);
  err:
-    if (provname)
-        OPENSSL_free(provname);
-    if (contname)
-        OPENSSL_free(contname);
+    OPENSSL_free(provname);
+    OPENSSL_free(contname);
 }
 
-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;
@@ -1313,10 +1331,10 @@ char *capi_cert_get_fname(CAPI_CTX * ctx, PCCERT_CONTEXT cert)
     return NULL;
 }
 
-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;
-    unsigned char *p;
+    const unsigned char *p;
     unsigned long flags = ctx->dump_flags;
     if (flags & CAPI_DMP_FNAME) {
         char *fname;
@@ -1324,8 +1342,9 @@ 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;
@@ -1346,8 +1365,7 @@ void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
         CRYPT_KEY_PROV_INFO *pinfo;
         pinfo = capi_get_prov_info(ctx, cert);
         capi_dump_prov_info(ctx, out, pinfo);
-        if (pinfo)
-            OPENSSL_free(pinfo);
+        OPENSSL_free(pinfo);
     }
 
     if (flags & CAPI_DMP_PEM)
@@ -1355,7 +1373,7 @@ void capi_dump_cert(CAPI_CTX * ctx, BIO *out, PCCERT_CONTEXT cert)
     X509_free(x);
 }
 
-HCERTSTORE capi_open_store(CAPI_CTX * ctx, char *storename)
+static HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename)
 {
     HCERTSTORE hstore;
 
@@ -1374,7 +1392,7 @@ 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;
@@ -1412,7 +1430,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;
@@ -1420,8 +1438,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 (;;) {
@@ -1444,32 +1461,38 @@ 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)
 {
-    CAPI_KEY *key;
     DWORD dwFlags = 0;
-    key = OPENSSL_malloc(sizeof(CAPI_KEY));
+    CAPI_KEY *key = OPENSSL_malloc(sizeof(*key));
+
     if (key == NULL)
         return NULL;
-    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 PROV_RSA_AES supported use it instead */
+    if (ptype == PROV_RSA_FULL && use_aes_csp &&
+        wcscmp(provname, rsa_enh_cspname) == 0) {
+        provname = rsa_aes_cspname;
+        ptype = PROV_RSA_AES;
+    }
+    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);
-        if (_provname)
-            OPENSSL_free(_provname);
-        if (_contname)
-            OPENSSL_free(_contname);
+        OPENSSL_free(_provname);
+        OPENSSL_free(_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;
@@ -1489,42 +1512,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:
-    if (pinfo)
-        OPENSSL_free(pinfo);
-    if (provname)
-        OPENSSL_free(provname);
-    if (contname)
-        OPENSSL_free(contname);
+    OPENSSL_free(pinfo);
     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:
@@ -1540,36 +1548,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;
@@ -1582,64 +1582,53 @@ void capi_free_key(CAPI_KEY * key)
 
 /* Initialize a CAPI_CTX structure */
 
-static CAPI_CTX *capi_ctx_new()
+static CAPI_CTX *capi_ctx_new(void)
 {
-    CAPI_CTX *ctx;
-    ctx = OPENSSL_malloc(sizeof(CAPI_CTX));
-    if (!ctx) {
+    CAPI_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
+
+    if (ctx == NULL) {
         CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
-    ctx->cspname = NULL;
     ctx->csptype = PROV_RSA_FULL;
     ctx->dump_flags = CAPI_DMP_SUMMARY | CAPI_DMP_FNAME;
     ctx->keytype = AT_KEYEXCHANGE;
-    ctx->storename = NULL;
-    ctx->ssl_client_store = NULL;
     ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG |
         CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER;
     ctx->lookup_method = CAPI_LU_SUBSTR;
-    ctx->debug_level = 0;
-    ctx->debug_file = NULL;
     ctx->client_cert_select = cert_select_simple;
     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)
         return;
-    if (ctx->cspname)
-        OPENSSL_free(ctx->cspname);
-    if (ctx->debug_file)
-        OPENSSL_free(ctx->debug_file);
-    if (ctx->storename)
-        OPENSSL_free(ctx->storename);
-    if (ctx->ssl_client_store)
-        OPENSSL_free(ctx->ssl_client_store);
+    OPENSSL_free(ctx->cspname);
+    OPENSSL_free(ctx->debug_file);
+    OPENSSL_free(ctx->storename);
+    OPENSSL_free(ctx->ssl_client_store);
     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;
+
     CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type);
     if (check) {
         HCRYPTPROV hprov;
-        LPTSTR name = NULL;
-
-        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;
+        LPWSTR name = NULL;
+        DWORD len;
 
-        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();
@@ -1647,14 +1636,18 @@ static int capi_ctx_set_provname(CAPI_CTX * ctx, LPSTR pname, DWORD type,
         }
         CryptReleaseContext(hprov, 0);
     }
-    if (ctx->cspname)
-        OPENSSL_free(ctx->cspname);
-    ctx->cspname = BUF_strdup(pname);
+    tmpcspname = OPENSSL_strdup(pname);
+    if (tmpcspname == NULL) {
+        CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, ERR_R_MALLOC_FAILURE);
+        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;
@@ -1690,7 +1683,7 @@ static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl,
     STACK_OF(X509) *certs = NULL;
     X509 *x;
     char *storename;
-    const char *p;
+    const unsigned char *p;
     int i, client_cert_idx;
     HCERTSTORE hstore;
     PCCERT_CONTEXT cert = NULL, excert = NULL;
@@ -1738,9 +1731,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)
@@ -1889,7 +1882,8 @@ OPENSSL_EXPORT
 
 IMPLEMENT_DYNAMIC_CHECK_FN()
 # else
-void ENGINE_load_capi(void)
+void engine_load_capi_int(void);
+void engine_load_capi_int(void)
 {
 }
 # endif