diff --git a/modules/saml2/lib/Message.php b/modules/saml2/lib/Message.php
index c49f5ce347f71a5e948be2b24826a3beff6000ba..6c44a9cf9e207b81bf7b625ec6f3754cfaab1dba 100644
--- a/modules/saml2/lib/Message.php
+++ b/modules/saml2/lib/Message.php
@@ -754,6 +754,18 @@ class sspmod_saml2_Message {
 			$assertion->setAttributes($newAttributes);
 		}
 
+
+		/* Decrypt the NameID element if it is encrypted. */
+		if ($assertion->isNameIdEncrypted()) {
+			try {
+				$key = self::getDecryptionKey($idpMetadata, $spMetadata);
+			} catch (Exception $e) {
+				throw new SimpleSAML_Error_Exception('Error decrypting NameID: ' . $e->getMessage());
+			}
+
+			$assertion->decryptNameId($key);
+		}
+
 		return $assertion;
 	}