Escape special characters RFC 4514

This escapes special characters according to RFC 4514 in
mbedtls_x509_dn_gets and de-escapes in mbedtls_x509_string_to_names.
This commit does not handle hexpairs.

Signed-off-by: Agathiyan Bragadeesh <agathiyan.bragadeesh2@arm.com>
diff --git a/library/x509.c b/library/x509.c
index ba8d719..2764ba6 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -855,12 +855,16 @@
             }
 
             c = name->val.p[i];
-            // Special characters requiring escaping, RFC 1779
-            if (c && strchr(",=+<>#;\"\\", c)) {
-                if (j + 1 >= sizeof(s) - 1) {
-                    return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
+            // Special characters requiring escaping, RFC 4514 Section 2.4
+            if (c) {
+                if (strchr(",=+<>;\"\\+", c) || 
+                ((i == 0) && strchr("# ", c)) ||
+                ((i == name->val.len-1 ) && (c == ' '))) {
+                    if (j + 1 >= sizeof(s) - 1) {
+                        return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
+                    }
+                    s[j++] = '\\';
                 }
-                s[j++] = '\\';
             }
             if (c < 32 || c >= 127) {
                 s[j] = '?';
diff --git a/library/x509_create.c b/library/x509_create.c
index bd772d3..170a6bc 100644
--- a/library/x509_create.c
+++ b/library/x509_create.c
@@ -153,8 +153,8 @@
         if (!in_tag && *c == '\\' && c != end) {
             c++;
 
-            /* Check for valid escaped characters */
-            if (c == end || *c != ',') {
+            /* Check for valid escaped characters in RFC 4514 in Section 3*/
+            if (c == end || !strchr(" ,=+<>#;\"\\+", *c)) {
                 ret = MBEDTLS_ERR_X509_INVALID_NAME;
                 goto exit;
             }