Index: src/engine_pkcs11.c
===================================================================
--- src/engine_pkcs11.c	(revision 42)
+++ src/engine_pkcs11.c	(working copy)
@@ -52,9 +52,17 @@
  */ 
 static char *pin = NULL;
 
+static void free_pin() {
+	if (pin != NULL) {
+		OPENSSL_cleanse(pin, strlen(pin));
+		free(pin);
+		pin = NULL;
+	}
+}
+
 int verbose = 0;
 
 char *module = NULL;
 int default_module = 1;
 
 int set_module(const char *modulename)
@@ -84,6 +93,7 @@
               errno = EINVAL;
               return 0;
         }
+	free_pin();
      
         /* Copy the PIN. If the string cannot be copied, NULL
            shall be returned and errno shall be set. */
@@ -129,11 +139,7 @@
 		PKCS11_CTX_free(ctx);
 		ctx = NULL;
 	}
-	if (pin != NULL) {
-		OPENSSL_cleanse(pin, strlen(pin));
-		free(pin);
-		pin = NULL;
-	}
+	free_pin();
 	return 1;
 }
 
@@ -152,10 +158,7 @@
 
 int pkcs11_rsa_finish(RSA * rsa)
 {
-	if (pin) {
-		free(pin);
-		pin = NULL;
-	}
+	free_pin();
 	if (!default_module && module) {
 		free(module);
 	}
@@ -598,11 +601,7 @@
                 if (tok->secureLogin) {
                         /* Free the PIN if it has already been 
                            assigned (i.e, via set_pin */
-			if (pin != NULL) {
-				OPENSSL_cleanse(pin, strlen(pin));
-				free (pin);
-				pin = NULL;
-			}
+			free_pin();
                 }
                 else if (pin == NULL) {
                         pin = (char *) calloc(MAX_PIN_LENGTH, sizeof(char));
@@ -615,11 +614,7 @@
                 /* Now login in with the (possibly NULL) pin */
                 if (PKCS11_login(slot, 0, pin)) {
                         /* Login failed, so free the PIN if present */
-                        if(pin != NULL) {
-				OPENSSL_cleanse(pin, strlen(pin));
-                                free(pin);
-                                pin = NULL;
-                        }
+			free_pin();
                         fail("Login failed\n");
                 }
                 /* Login successful, PIN retained in case further logins are 
