Accept spaces at EOL/buffer in base64_decode()
diff --git a/ChangeLog b/ChangeLog
index 9440e48..72ff504 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -25,6 +25,7 @@
      RelativeDistinguishedName are not accepted any more.
    * ssl_read() now returns POLARSSL_ERR_NET_WANT_READ rather than
      POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE on harmless alerts.
+   * Accept spaces at end of line or end of buffer in base64_decode().
 
 = Version 1.2.11 released 2014-07-11
 Features
diff --git a/library/base64.c b/library/base64.c
index 1364713..c56c060 100644
--- a/library/base64.c
+++ b/library/base64.c
@@ -137,8 +137,21 @@
     uint32_t j, x;
     unsigned char *p;
 
-    for( i = j = n = 0; i < slen; i++ )
+    /* First pass: check for validity and get output length */
+    for( i = n = j = 0; i < slen; i++ )
     {
+        /* Skip spaces before checking for EOL */
+        x = 0;
+        while( i < slen && src[i] == ' ' )
+        {
+            ++i;
+            ++x;
+        }
+
+        /* Spaces at end of buffer are OK */
+        if( i == slen )
+            break;
+
         if( ( slen - i ) >= 2 &&
             src[i] == '\r' && src[i + 1] == '\n' )
             continue;
@@ -146,6 +159,10 @@
         if( src[i] == '\n' )
             continue;
 
+        /* Space inside a line is an error */
+        if( x != 0 )
+            return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
+
         if( src[i] == '=' && ++j > 2 )
             return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );