diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php
index 60fc77f8e86ff47559c2b51b7eef9f04763183bb..46026579ff658ee68a403eb4f4f0d0be6ba9835c 100644
--- a/modules/saml/lib/IdP/SAML2.php
+++ b/modules/saml/lib/IdP/SAML2.php
@@ -48,7 +48,7 @@ class sspmod_saml_IdP_SAML2 {
 			'Handler' => 'sspmod_saml_IdP_SAML2',
 			'Expires' => $assertion->getSessionNotOnOrAfter(),
 			'saml:entityID' => $spEntityId,
-			'saml:NameID' => $assertion->getNameId(),
+			'saml:NameID' => $state['saml:idp:NameID'],
 			'saml:SessionIndex' => $assertion->getSessionIndex(),
 		);
 
@@ -658,8 +658,18 @@ class sspmod_saml_IdP_SAML2 {
 			);
 		}
 
+		$state['saml:idp:NameID'] = $nameId;
+
 		$a->setNameId($nameId);
 
+		$encryptNameId = $spMetadata->getBoolean('nameid.encryption', NULL);
+		if ($encryptNameId === NULL) {
+			$encryptNameId = $idpMetadata->getBoolean('nameid.encryption', FALSE);
+		}
+		if ($encryptNameId) {
+			$a->encryptNameId(sspmod_saml_Message::getEncryptionKey($spMetadata));
+		}
+
 		return $a;
 	}