diff -u -r stunnel-3.8.orig/ssl.c stunnel-3.8/ssl.c
--- stunnel-3.8.orig/ssl.c	Fri Feb 18 10:26:48 2000
+++ stunnel-3.8/ssl.c	Tue Sep 26 16:52:04 2000
@@ -129,19 +129,7 @@
 static void print_cipher(SSL *);
 static void sslerror(char *);
 
-/* Correct callback definitions overriding ssl.h */
-#ifndef NO_RSA
-#ifdef SSL_CTX_set_tmp_rsa_callback
-    #undef SSL_CTX_set_tmp_rsa_callback
-#endif
-#define SSL_CTX_set_tmp_rsa_callback(ctx,cb) \
-    SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_RSA_CB,0,(char *)cb)
-#endif /* NO_RSA */
-
 SSL_CTX *ctx;           /* global SSL context */
-#ifndef NO_RSA
-RSA *rsa_tmp;           /* temporary RSA key */
-#endif /* NO_RSA */
 #if SSLEAY_VERSION_NUMBER >= 0x0922
 static unsigned char *sid_ctx=(unsigned char *)"stunnel SID";
     /* const allowed here */
@@ -161,17 +149,6 @@
     } else { /* Server mode */
         ctx=SSL_CTX_new(SSLv23_server_method());
 #ifndef NO_RSA
-        log(LOG_DEBUG, "Generating %d bit temporary RSA key...", KEYLENGTH);
-#if SSLEAY_VERSION_NUMBER <= 0x0800
-        rsa_tmp=RSA_generate_key(KEYLENGTH, RSA_F4, NULL);
-#else
-        rsa_tmp=RSA_generate_key(KEYLENGTH, RSA_F4, NULL, NULL);
-#endif
-        if(!rsa_tmp) {
-            sslerror("tmp_rsa_cb");
-            exit(1);
-        }
-        log(LOG_DEBUG, "Temporary RSA key generated");
         SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
 #endif /* NO_RSA */
 #ifndef NO_DH
@@ -520,11 +497,41 @@
     return retval;
 }
 
+#if SSLEAY_VERSION_NUMBER >= 0x0900
+#define TempKey(s) RSA_generate_key((s), RSA_F4, NULL, NULL);
+# else
+#define TempKey(s) RSA_generate_key((s), RSA_F4, NULL);
+# endif
+
 #ifndef NO_RSA
+/* Callback function invoked from SSL that returns a temporary RSA key.     *
+ * As this is a time-consuming task, we re-use the last key we generated.   */
 static RSA *tmp_rsa_cb(SSL *s, int export, int keylength)
-{ /* temporary RSA key callback */
-    log(LOG_DEBUG, "Returned temporary RSA callback");
-    return rsa_tmp;
+{
+  static RSA *key512=NULL, *key1024=NULL, *keyx=NULL;
+  static int keyxs=0;
+
+  if (keylength == 512) {
+    if (key512 == NULL) {
+      log(LOG_DEBUG, "Generating 512 bit temporary RSA key...");
+      key512 = TempKey(512);
+    }
+    return (key512);
+  } else if (keylength == 1024) {
+    if (key1024 == NULL) {
+      log(LOG_DEBUG, "Generating 1024 bit temporary RSA key...");
+      key1024 = TempKey(1024);
+    }
+    return(key1024);
+  } else {
+    if (keylength != keyxs) {
+      log(LOG_DEBUG, "Generating %d bit temporary RSA key...", keylength);
+      if (keyx != NULL) RSA_free(keyx);
+      keyx = TempKey(keylength);
+      keyxs = keylength;
+    }
+    return (keyx);
+  }
 }
 #endif /* NO_RSA */
 
