diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index b7b5c35f94374658867e08413f950af3147d7ccd..73dfd2f124a459823e89a5b02571688b47a437ef 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -177,12 +177,7 @@ class SimpleSAML_Utilities {
 	}
 	
 	public static function generateID() {
-		$bytes = self::generateRandomBytes(21);
-		$key = '_';
-		for($i = 0; $i < 21; $i++) {
-			$key .= sprintf('%02x', ord($bytes[$i]));
-		}
-		return $key;
+		return '_' . self::stringToHex(self::generateRandomBytes(21));
 	}
 	
 
@@ -917,6 +912,21 @@ class SimpleSAML_Utilities {
 		return $data;
 	}
 
+
+	/**
+	 * This function converts a binary string to hexadecimal characters.
+	 *
+	 * @param $bytes  Input string.
+	 * @return String with lowercase hexadecimal characters.
+	 */
+	public function stringToHex($bytes) {
+		$ret = '';
+		for($i = 0; $i < strlen($bytes); $i++) {
+			$ret .= sprintf('%02x', ord($bytes[$i]));
+		}
+		return $ret;
+	}
+
 }
 
 ?>
\ No newline at end of file