diff --git a/lib/SimpleSAML/Auth/LDAP.php b/lib/SimpleSAML/Auth/LDAP.php
index 23f6c051e831e26dbbe4a4ca8c145e3ef4888a87..43efee196348f96dddb8837943e13332eecc7f7e 100644
--- a/lib/SimpleSAML/Auth/LDAP.php
+++ b/lib/SimpleSAML/Auth/LDAP.php
@@ -361,6 +361,25 @@ class SimpleSAML_Auth_LDAP {
 			);
 		}
 
+        // parse each entry and process its attributes
+        for ($i = 0; $i < $results['count']; $i++) {
+            $entry = $results[$i];
+
+            // iterate over the attributes of the entry
+            for ($j = 0; $j < $entry['count']; $j++) {
+                $name = $entry[$j];
+                $attribute = $entry[$name];
+
+                // decide whether to base64 encode or not
+                for ($k = 0; $k < $attribute['count']; $k++) {
+                    // base64 encode binary attributes
+                    if (!ctype_print($attribute[$k])) {
+                        $results[$i][$name][$k] = base64_encode($attribute[$k]);
+                    }
+                }
+            }
+        }
+
 		// Remove the count and return
 		unset($results['count']);
 		return $results;
@@ -522,12 +541,12 @@ class SimpleSAML_Auth_LDAP {
 					continue;
 				}
 
-				// Base64 encode jpegPhoto.
-				if (strtolower($name) === 'jpegphoto') {
+                // base64 encode binary attributes
+                if (!ctype_print($value)) {
 					$values[] = base64_encode($value);
-				} else
+				} else {
 					$values[] = $value;
-
+                }
 			}
 
 			// Adding.