--- a/src/lib-dcrypt/dcrypt-openssl.c
+++ b/src/lib-dcrypt/dcrypt-openssl.c
@@ -20,10 +20,12 @@
 #include <openssl/bio.h>
 #include <openssl/pem.h>
 #include <openssl/x509.h>
-#include <openssl/engine.h>
 #include <openssl/hmac.h>
 #include <openssl/objects.h>
 #include <openssl/bn.h>
+#ifndef OPENSSL_NO_ENGINE
+#include <openssl/engine.h>
+#endif
 #include "dcrypt.h"
 #include "dcrypt-private.h"
 
@@ -236,11 +238,13 @@ dcrypt_openssl_padding_mode(enum dcrypt_
 static bool dcrypt_openssl_initialize(const struct dcrypt_settings *set,
 				      const char **error_r)
 {
+#ifndef OPENSSL_NO_ENGINE
 	if (set->crypto_device != NULL && set->crypto_device[0] != '\0') {
 		if (dovecot_openssl_common_global_set_engine(
 			set->crypto_device, error_r) <= 0)
 			return FALSE;
 	}
+#endif
 	return TRUE;
 }
 
--- a/src/lib-ssl-iostream/dovecot-openssl-common.c
+++ b/src/lib-ssl-iostream/dovecot-openssl-common.c
@@ -5,11 +5,14 @@
 #include "dovecot-openssl-common.h"
 
 #include <openssl/ssl.h>
-#include <openssl/engine.h>
 #include <openssl/rand.h>
+#ifndef OPENSSL_NO_ENGINE
+#include <openssl/engine.h>
 
-static int openssl_init_refcount = 0;
 static ENGINE *dovecot_openssl_engine;
+#endif
+
+static int openssl_init_refcount = 0;
 
 #ifdef HAVE_SSL_NEW_MEM_FUNCS
 static void *dovecot_openssl_malloc(size_t size, const char *u0 ATTR_UNUSED, int u1 ATTR_UNUSED)
@@ -77,10 +80,12 @@ bool dovecot_openssl_common_global_unref
 	if (--openssl_init_refcount > 0)
 		return TRUE;
 
+#ifndef OPENSSL_NO_ENGINE
 	if (dovecot_openssl_engine != NULL) {
 		ENGINE_finish(dovecot_openssl_engine);
 		dovecot_openssl_engine = NULL;
 	}
+#endif
 #if OPENSSL_VERSION_NUMBER < 0x10100000L
 	/* OBJ_cleanup() is called automatically by EVP_cleanup() in
 	   newer versions. Doesn't hurt to call it anyway. */
@@ -88,7 +93,9 @@ bool dovecot_openssl_common_global_unref
 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
 	SSL_COMP_free_compression_methods();
 #endif
+#ifndef OPENSSL_NO_ENGINE
 	ENGINE_cleanup();
+#endif
 	EVP_cleanup();
 	CRYPTO_cleanup_all_ex_data();
 #ifdef HAVE_OPENSSL_AUTO_THREAD_DEINIT
@@ -111,6 +118,7 @@ bool dovecot_openssl_common_global_unref
 int dovecot_openssl_common_global_set_engine(const char *engine,
 					     const char **error_r)
 {
+#ifndef OPENSSL_NO_ENGINE
 	if (dovecot_openssl_engine != NULL)
 		return 1;
 
@@ -132,5 +140,6 @@ int dovecot_openssl_common_global_set_en
 		dovecot_openssl_engine = NULL;
 		return -1;
 	}
+#endif
 	return 1;
 }
