diff --git a/modules/saml2/lib/Message.php b/modules/saml2/lib/Message.php
index 369006286b0d6bd5dda43851c30b8226105157f7..866d95f3206ebfc5fe1108becd58798130a32e21 100644
--- a/modules/saml2/lib/Message.php
+++ b/modules/saml2/lib/Message.php
@@ -472,12 +472,15 @@ class sspmod_saml2_Message {
 					$value = (string)$value;
 					break;
 				case 'base64':
-					$value = base64_encode($value);
+					$value = base64_encode((string)$value);
 					break;
 				case 'raw':
-					$doc = new DOMDocument();
-					$doc->loadXML('<root>' . $value . '</root>');
-					$value = $doc->firstChild->childNodes;
+					if (is_string($value)) {
+						$doc = new DOMDocument();
+						$doc->loadXML('<root>' . $value . '</root>');
+						$value = $doc->firstChild->childNodes;
+					}
+					assert('$value instanceof DOMNodeList');
 					break;
 				default:
 					throw new SimpleSAML_Error_Exception('Invalid encoding for attribute ' .