Merge pull request #5997 from gilles-peskine-arm/storage-format-doc-202206-2.28

Backport 2.28: Documentation about storage format compatibility
diff --git a/ChangeLog.d/asn1write-0-fix b/ChangeLog.d/asn1write-0-fix
new file mode 100644
index 0000000..2e01244
--- /dev/null
+++ b/ChangeLog.d/asn1write-0-fix
@@ -0,0 +1,2 @@
+Bugfix
+   * Fix mbedtls_asn1_write_mpi() writing an incorrect encoding of 0.
diff --git a/ChangeLog.d/fix-csr_subject_commas.txt b/ChangeLog.d/fix-csr_subject_commas.txt
new file mode 100644
index 0000000..e01c9a8
--- /dev/null
+++ b/ChangeLog.d/fix-csr_subject_commas.txt
@@ -0,0 +1,3 @@
+Bugfix
+   * Fix string representation of DNs when outputting values containing commas
+     and other special characters, conforming to RFC 1779. Fixes #769.
diff --git a/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt b/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt
index 6878645..a6540a1 100644
--- a/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt
+++ b/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt
@@ -1,3 +1,3 @@
 Bugfix
-   * Fix compilation on Windows when building shared library, by setting
-     library search path to CMAKE_CURRENT_BINARY_DIR.
+   * Fix the library search path when building a shared library with CMake
+     on Windows.
diff --git a/ChangeLog.d/fix-x25519-program.txt b/ChangeLog.d/fix-x25519-program.txt
index af60465..bf5d6ac 100644
--- a/ChangeLog.d/fix-x25519-program.txt
+++ b/ChangeLog.d/fix-x25519-program.txt
@@ -1,4 +1,4 @@
 Bugfix
-   * Fix a bug in x25519 example program where the removal of
+   * Fix a bug in the x25519 example program where the removal of
      MBEDTLS_ECDH_LEGACY_CONTEXT caused the program not to run. Fixes #4901 and
      #3191.
diff --git a/ChangeLog.d/mbedtls_ssl_config_defaults-memleak.txt b/ChangeLog.d/mbedtls_ssl_config_defaults-memleak.txt
index d55c016..043b273 100644
--- a/ChangeLog.d/mbedtls_ssl_config_defaults-memleak.txt
+++ b/ChangeLog.d/mbedtls_ssl_config_defaults-memleak.txt
@@ -1,2 +1,2 @@
 Bugfix
-   * Fix memory leak if mbedtls_ssl_config_defaults() call is repeated
+   * Fix a memory leak if mbedtls_ssl_config_defaults() is called twice.
diff --git a/ChangeLog.d/raw-agreement-destroy-missing.txt b/ChangeLog.d/raw-agreement-destroy-missing.txt
deleted file mode 100644
index 7342b8c..0000000
--- a/ChangeLog.d/raw-agreement-destroy-missing.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Add missing key slot destruction calls when a raw key agreement or
-     a public key export fails in ssl_write_client_key_exchange.
diff --git a/ChangeLog.d/selftest-gcc12.txt b/ChangeLog.d/selftest-gcc12.txt
new file mode 100644
index 0000000..aafa256
--- /dev/null
+++ b/ChangeLog.d/selftest-gcc12.txt
@@ -0,0 +1,2 @@
+Bugfix
+   * Silence a warning from GCC 12 in the selftest program. Fixes #5974.
diff --git a/ChangeLog.d/use-psa-ecdhe-curve.txt b/ChangeLog.d/use-psa-ecdhe-curve.txt
index cc432bd..658f88f 100644
--- a/ChangeLog.d/use-psa-ecdhe-curve.txt
+++ b/ChangeLog.d/use-psa-ecdhe-curve.txt
@@ -4,4 +4,4 @@
      client would fail to check that the curve selected by the server for
      ECDHE was indeed one that was offered. As a result, the client would
      accept any curve that it supported, even if that curve was not allowed
-     according to its configuration.
+     according to its configuration. Fixes #5291.
diff --git a/docs/architecture/mbed-crypto-storage-specification.md b/docs/architecture/mbed-crypto-storage-specification.md
index 914bca3..d630e8e 100644
--- a/docs/architecture/mbed-crypto-storage-specification.md
+++ b/docs/architecture/mbed-crypto-storage-specification.md
@@ -112,7 +112,7 @@
 The way in which the file name is constructed from the key identifier depends on the storage backend. The content of the file is described [below](#key-file-format-for-1.0.0).
 
 * Library integration: the key file name is just the key identifier as defined in the PSA crypto specification. This is a 32-bit value.
-* PSA service integration: the key file name is `(uint32_t)owner_uid << 32 | key_id` where `key_id` is the key identifier from the owner point of view and `owner_uid` (of type `int32_t`) is the calling partition identifier provided to the server by the partition manager. This is a 64-bit value.
+* PSA service integration: the key file name is `(uint64_t)owner_uid << 32 | key_id` where `key_id` is the key identifier from the owner point of view and `owner_uid` (of type `int32_t`) is the calling partition identifier provided to the server by the partition manager. This is a 64-bit value.
 
 ### Key file format for 1.0.0
 
@@ -120,7 +120,11 @@
 
 ### Nonvolatile random seed file format for 1.0.0
 
-[Identical to 0.1.0](#nonvolatile-random-seed-file-format-for-0.1.0).
+The nonvolatile random seed file contains a seed for the random generator. If present, it is rewritten at each boot as part of the random generator initialization.
+
+The file format is just the seed as a byte string with no metadata or encoding of any kind.
+
+This is unchanged since [the feature was introduced in Mbed Crypto 0.1.0](#nonvolatile-random-seed-file-format-for-0.1.0).
 
 ### File namespace on a PSA platform for 1.0.0
 
@@ -167,7 +171,21 @@
 Released in early June 2019. <br>
 Integrated in Mbed OS 5.13.
 
-Identical to [1.0.0](#mbed-crypto-1.0.0) except for some changes in the key file format.
+Changes since [1.0.0](#mbed-crypto-1.0.0):
+
+* The stdio backend for storage has been replaced by an implementation of [PSA ITS over stdio](#file-namespace-on-stdio-for-1.1.0).
+* [Some changes in the key file format](#key-file-format-for-1.1.0).
+
+### File namespace on stdio for 1.1.0
+
+Assumption: C stdio, allowing names containing lowercase letters, digits and underscores, of length up to 23.
+
+An undocumented build-time configuration value `PSA_ITS_STORAGE_PREFIX` allows storing the key files in a directory other than the current directory. This value is simply prepended to the file name (so it must end with a directory separator to put the keys in a different directory).
+
+* `PSA_ITS_STORAGE_PREFIX "tempfile.psa_its"`: used as a temporary file. Must be writable. May be overwritten or deleted if present.
+* `sprintf(PSA_ITS_STORAGE_PREFIX "%016llx.psa_its", key_id)`: a key or non-key file. The `key_id` in the name is the 64-bit file identifier, which is the [key identifier](#key-names-for-mbed-tls-2.25.0) for a key file or some reserved identifier for a non-key file (currently: only the [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-1.0.0)). The contents of the file are:
+    * Magic header (8 bytes): `"PSA\0ITS\0"`
+    * File contents.
 
 ### Key file format for 1.1.0
 
@@ -314,3 +332,134 @@
     * For an opaque key (unified driver interface): driver-specific opaque key blob.
     * For an opaque key (key in a secure element): slot number (8 bytes), in platform endianness.
 * Any trailing data is rejected on load.
+
+Mbed TLS 2.25.0
+---------------
+
+Tags: `mbedtls-2.25.0`, `mbedtls-2.26.0`, `mbedtls-2.27.0`, `mbedtls-2.28.0` (continued in early 3.x releases)
+
+First released in December 2020.
+
+Note: this is the first version that is officially supported. The version number is still 0.
+
+Backward compatibility commitments: we promise backward compatibility for stored keys when Mbed TLS is upgraded from x to y if x >= 2.25 and y < 4. See [`BRANCHES.md`](../../BRANCHES.md) for more details.
+
+Supported integrations:
+
+* [PSA platform](#file-namespace-on-a-psa-platform-on-mbed-tls-2.25.0)
+* [library using PSA ITS](#file-namespace-on-its-as-a-library-on-mbed-tls-2.25.0)
+* [library using C stdio](#file-namespace-on-stdio-for-mbed-tls-2.25.0)
+
+Supported features:
+
+* [Persistent keys](#key-file-format-for-mbed-tls-2.25.0) designated by a [key identifier and owner](#key-names-for-mbed-tls-2.25.0). Keys can be:
+    * Transparent, stored in the export format.
+    * Opaque, using the unified driver interface with statically registered drivers (`MBEDTLS_PSA_CRYPTO_DRIVERS`). The driver determines the content of the opaque key blob.
+    * Opaque, using the deprecated secure element interface with dynamically registered drivers (`MBEDTLS_PSA_CRYPTO_SE_C`). The driver picks a slot number which is stored in the place of the key material.
+* [Nonvolatile random seed](#nonvolatile-random-seed-file-format-for-mbed-tls-2.25.0) on ITS only.
+
+### Changes introduced in Mbed TLS 2.25.0
+
+* The numerical encodings of `psa_key_type_t`, `psa_key_usage_t` and `psa_algorithm_t` have changed.
+
+### File namespace on a PSA platform on Mbed TLS 2.25.0
+
+Assumption: ITS provides a 64-bit file identifier namespace. The Crypto service can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
+
+Assumption: the owner identifier is a nonzero value of type `int32_t`.
+
+* Files 0 through 0xfffeffff: unused.
+* Files 0xffff0000 through 0xffffffff: reserved for internal use of the crypto library or crypto service. See [non-key files](#non-key-files-on-mbed-tls-2.25.0).
+* Files 0x100000000 through 0xffffffffffff: [content](#key-file-format-for-mbed-tls-2.25.0) of the [key whose identifier is the file identifier](#key-names-for-mbed-tls-2.25.0). The upper 32 bits determine the owner.
+
+### File namespace on ITS as a library on Mbed TLS 2.25.0
+
+Assumption: ITS provides a 64-bit file identifier namespace. The entity using the crypto library can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
+
+This is a library integration, so there is no owner. The key file identifier is identical to the key identifier.
+
+* File 0: unused.
+* Files 1 through 0xfffeffff: [content](#key-file-format-for-mbed-tls-2.25.0) of the [key whose identifier is the file identifier](#key-names-for-mbed-tls-2.25.0).
+* Files 0xffff0000 through 0xffffffff: reserved for internal use of the crypto library or crypto service. See [non-key files](#non-key-files-on-mbed-tls-2.25.0).
+* Files 0x100000000 through 0xffffffffffffffff: unused.
+
+### File namespace on stdio for Mbed TLS 2.25.0
+
+Assumption: C stdio, allowing names containing lowercase letters, digits and underscores, of length up to 23.
+
+An undocumented build-time configuration value `PSA_ITS_STORAGE_PREFIX` allows storing the key files in a directory other than the current directory. This value is simply prepended to the file name (so it must end with a directory separator to put the keys in a different directory).
+
+* `PSA_ITS_STORAGE_PREFIX "tempfile.psa_its"`: used as a temporary file. Must be writable. May be overwritten or deleted if present.
+* `sprintf(PSA_ITS_STORAGE_PREFIX "%016llx.psa_its", key_id)`: a key or non-key file. The `key_id` in the name is the 64-bit file identifier, which is the [key identifier](#key-names-for-mbed-tls-2.25.0) for a key file or some reserved identifier for a [non-key file](#non-key-files-on-mbed-tls-2.25.0). The contents of the file are:
+    * Magic header (8 bytes): `"PSA\0ITS\0"`
+    * File contents.
+
+### Key names for Mbed TLS 2.25.0
+
+Information about each key is stored in a dedicated file designated by the key identifier. In integrations where there is no concept of key owner (in particular, in library integrations), the key identifier is exactly the key identifier as defined in the PSA Cryptography API specification (`psa_key_id_t`). In integrations where there is a concept of key owner (integration into a service for example), the key identifier is made of an owner identifier (its semantics and type are integration specific) and of the key identifier (`psa_key_id_t`) from the key owner point of view.
+
+The way in which the file name is constructed from the key identifier depends on the storage backend. The content of the file is described [below](#key-file-format-for-mbed-tls-2.25.0).
+
+* Library integration: the key file name is just the key identifier as defined in the PSA crypto specification. This is a 32-bit value which must be in the range 0x00000001..0x3fffffff (`PSA_KEY_ID_USER_MIN`..`PSA_KEY_ID_USER_MAX`).
+* PSA service integration: the key file name is `(uint64_t)owner_uid << 32 | key_id` where `key_id` is the key identifier from the owner point of view and `owner_uid` (of type `int32_t`) is the calling partition identifier provided to the server by the partition manager. This is a 64-bit value.
+
+### Key file format for Mbed TLS 2.25.0
+
+All integers are encoded in little-endian order in 8-bit bytes except where otherwise indicated.
+
+The layout of a key file is:
+
+* magic (8 bytes): `"PSA\0KEY\0"`.
+* version (4 bytes): 0.
+* lifetime (4 bytes): `psa_key_lifetime_t` value.
+* type (2 bytes): `psa_key_type_t` value.
+* bits (2 bytes): `psa_key_bits_t` value.
+* policy usage flags (4 bytes): `psa_key_usage_t` value.
+* policy usage algorithm (4 bytes): `psa_algorithm_t` value.
+* policy enrollment algorithm (4 bytes): `psa_algorithm_t` value.
+* key material length (4 bytes).
+* key material:
+    * For a transparent key: output of `psa_export_key`.
+    * For an opaque key (unified driver interface): driver-specific opaque key blob.
+    * For an opaque key (key in a dynamic secure element): slot number (8 bytes), in platform endianness.
+* Any trailing data is rejected on load.
+
+### Non-key files on Mbed TLS 2.25.0
+
+File identifiers that are outside the range of persistent key identifiers are reserved for internal use by the library. The only identifiers currently in use have the owner id (top 32 bits) set to 0.
+
+* Files 0xfffffe02 through 0xfffffeff (`PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + lifetime`): dynamic secure element driver storage. The content of the file is the secure element driver's persistent data.
+* File 0xffffff52 (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`): [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-mbed-tls-2.25.0).
+* File 0xffffff54 (`PSA_CRYPTO_ITS_TRANSACTION_UID`): [transaction file](#transaction-file-format-for-mbed-tls-2.25.0).
+* Other files are unused and reserved for future use.
+
+### Nonvolatile random seed file format for Mbed TLS 2.25.0
+
+[Identical to Mbed Crypto 0.1.0](#nonvolatile-random-seed-file-format-for-0.1.0).
+
+### Transaction file format for Mbed TLS 2.25.0
+
+The transaction file contains data about an ongoing action that cannot be completed atomically. It exists only if there is an ongoing transaction.
+
+All integers are encoded in platform endianness.
+
+All currently existing transactions concern a key in a dynamic secure element.
+
+The layout of a transaction file is:
+
+* type (2 bytes): the [transaction type](#transaction-types-on-mbed-tls-2.25.0).
+* unused (2 bytes)
+* lifetime (4 bytes): `psa_key_lifetime_t` value that corresponds to a key in a secure element.
+* slot number (8 bytes): `psa_key_slot_number_t` value. This is the unique designation of the key for the secure element driver.
+* key identifier (4 bytes in a library integration, 8 bytes on a PSA platform): the internal representation of the key identifier. On a PSA platform, this encodes the key owner in the same way as [in file identifiers for key files](#file-namespace-on-a-psa-platform-on-mbed-tls-2.25.0)).
+
+#### Transaction types on Mbed TLS 2.25.0
+
+* 0x0001: key creation. The following locations may or may not contain data about the key that is being created:
+    * The slot in the secure element designated by the slot number.
+    * The file containing the key metadata designated by the key identifier.
+    * The driver persistent data.
+* 0x0002: key destruction. The following locations may or may not still contain data about the key that is being destroyed:
+    * The slot in the secure element designated by the slot number.
+    * The file containing the key metadata designated by the key identifier.
+    * The driver persistent data.
diff --git a/library/asn1write.c b/library/asn1write.c
index d454841..afa26a6 100644
--- a/library/asn1write.c
+++ b/library/asn1write.c
@@ -133,6 +133,11 @@
     //
     len = mbedtls_mpi_size( X );
 
+    /* DER represents 0 with a sign bit (0=nonnegative) and 7 value bits, not
+     * as 0 digits. We need to end up with 020100, not with 0200. */
+    if( len == 0 )
+        len = 1;
+
     if( *p < start || (size_t)( *p - start ) < len )
         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
 
diff --git a/library/x509.c b/library/x509.c
index f21e9e6..3997ebd 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -741,7 +741,7 @@
 int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn )
 {
     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
-    size_t i, n;
+    size_t i, j, n;
     unsigned char c, merge = 0;
     const mbedtls_x509_name *name;
     const char *short_name = NULL;
@@ -775,17 +775,24 @@
             ret = mbedtls_snprintf( p, n, "\?\?=" );
         MBEDTLS_X509_SAFE_SNPRINTF;
 
-        for( i = 0; i < name->val.len; i++ )
+        for( i = 0, j = 0; i < name->val.len; i++, j++ )
         {
-            if( i >= sizeof( s ) - 1 )
-                break;
+            if( j >= sizeof( s ) - 1 )
+                return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
 
             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 );
+                s[j++] = '\\';
+            }
             if( c < 32 || c >= 127 )
-                 s[i] = '?';
-            else s[i] = c;
+                 s[j] = '?';
+            else s[j] = c;
         }
-        s[i] = '\0';
+        s[j] = '\0';
         ret = mbedtls_snprintf( p, n, "%s", s );
         MBEDTLS_X509_SAFE_SNPRINTF;
 
diff --git a/programs/test/selftest.c b/programs/test/selftest.c
index 41d7040..393d737 100644
--- a/programs/test/selftest.c
+++ b/programs/test/selftest.c
@@ -89,7 +89,6 @@
     void *empty2 = mbedtls_calloc( 0, 1 );
     void *buffer1 = mbedtls_calloc( 1, 1 );
     void *buffer2 = mbedtls_calloc( 1, 1 );
-    uintptr_t old_buffer1;
 
     if( empty1 == NULL && empty2 == NULL )
     {
@@ -131,7 +130,6 @@
             mbedtls_printf( "  CALLOC(1): passed\n" );
     }
 
-    old_buffer1 = (uintptr_t) buffer1;
     mbedtls_free( buffer1 );
     buffer1 = mbedtls_calloc( 1, 1 );
     if( buffer1 == NULL )
@@ -143,9 +141,7 @@
     else
     {
         if( verbose )
-            mbedtls_printf( "  CALLOC(1 again): passed (%s address)\n",
-                            (uintptr_t) old_buffer1 == (uintptr_t) buffer1 ?
-                            "same" : "different" );
+            mbedtls_printf( "  CALLOC(1 again): passed\n" );
     }
 
     if( verbose )
diff --git a/tests/data_files/Makefile b/tests/data_files/Makefile
index f3cba5a..49db4ca 100644
--- a/tests/data_files/Makefile
+++ b/tests/data_files/Makefile
@@ -937,6 +937,10 @@
 	$(MBEDTLS_CERT_REQ) output_file=$@ filename=$< subject_name="C=NL,O=PolarSSL,CN=PolarSSL Server 1" md=SHA1 force_ns_cert_type=1
 all_final += server1.req.cert_type_empty
 
+server1.req.commas.sha256: server1.key
+	$(MBEDTLS_CERT_REQ) output_file=$@ filename=$< subject_name="C=NL,O=PolarSSL\, Commas,CN=PolarSSL Server 1" md=SHA256
+all_final += server1.req.commas.sha256
+
 # server2*
 
 server2_pwd_ec = PolarSSLTest
@@ -994,7 +998,9 @@
 	$(MBEDTLS_CERT_WRITE) request_file=server1.req.sha256 issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) not_before=20190210144406 not_after=20290210144406 md=SHA1 authority_identifier=0 version=3 output_file=$@
 server1.der: server1.crt
 	$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
-all_final += server1.crt server1.noauthid.crt server1.crt.der
+server1.commas.crt: server1.key server1.req.commas.sha256 $(test_ca_crt) $(test_ca_key_file_rsa)
+	$(MBEDTLS_CERT_WRITE) request_file=server1.req.commas.sha256 issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20190210144406 not_after=20290210144406 md=SHA1 version=3 output_file=$@
+all_final += server1.crt server1.noauthid.crt server1.crt.der server1.commas.crt
 
 server1.key_usage.crt: server1.key server1.req.sha256 $(test_ca_crt) $(test_ca_key_file_rsa)
 	$(MBEDTLS_CERT_WRITE) request_file=server1.req.sha256 issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20190210144406 not_after=20290210144406 md=SHA1 key_usage=digital_signature,non_repudiation,key_encipherment version=3 output_file=$@
diff --git a/tests/data_files/server1.commas.crt b/tests/data_files/server1.commas.crt
new file mode 100644
index 0000000..5acd255
--- /dev/null
+++ b/tests/data_files/server1.commas.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIIDRzCCAi+gAwIBAgIBATANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER
+MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN
+MTkwMjEwMTQ0NDA2WhcNMjkwMjEwMTQ0NDA2WjBEMQswCQYDVQQGEwJOTDEZMBcG
+A1UECgwQUG9sYXJTU0wsIENvbW1hczEaMBgGA1UEAwwRUG9sYXJTU0wgU2VydmVy
+IDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpAh89QGrVVVOL/Tbu
+gmUuFWFeib+46EWQ2+6IFlLT8UNQR5YSWWSHa/0r4Eb5c77dz5LhkVvtZqBviSl5
+RYDQg2rVQUN3Xzl8CQRHgrBXOXDto+wVGR6oMwhHwQVCqf1Mw7Tf3QYfTRBRQGdz
+Ew9A+G2BJV8KsVPGMH4VOaz5Wu5/kp6mBVvnE5eFtSOS2dQkBtUJJYl1B92mGo8/
+CRm+rWUsZOuVm9z+QV4XptpsW2nMAroULBYknErczdD3Umdz8S2gI/1+9DHKLXDK
+iQsE2y6mT3Buns69WIniU1meblqSZeKIPwyUGaPd5eidlRPtKdurcBLcWsprF6tS
+glSxAgMBAAGjTTBLMAkGA1UdEwQCMAAwHQYDVR0OBBYEFB901j8pwXR0RTsFEiw9
+qL1DWQKmMB8GA1UdIwQYMBaAFLRa5KWz3tJS9rnVppUP6z68x/3/MA0GCSqGSIb3
+DQEBBQUAA4IBAQA1Ecg+VVJRmgFF9cnlztnXj4y9QKj8MCf2uZA3nTNe1Deh9l17
+ZNNWdPkXzVzf0IeR3LQRKT+daTzxuOOCSV9OxOcN0dIODBwa97BtNQfuWw2eWC9I
+3UOVXbx8Ga+bXnD8ouatpyEG0FfhLO5YgEP0K9TyyN/nFa9kkB2Kvpy8yWm3w9WG
+WgsOr2fpIExfC2ZFaiu3NVGTpT9fLv8RTatSC1XLA5Sr8NNHia3zCvEJEAlTuFHs
+wm8apIAHlb44bbgW+7UwBIH9r2A21gQFy3v4cTLtlbnaUBbHUJvarK4ru70J+gew
+OO3NZ1ocvnV+qGIcc7LgyNA8pZW5Jbewb/gN
+-----END CERTIFICATE-----
diff --git a/tests/data_files/server1.req.commas.sha256 b/tests/data_files/server1.req.commas.sha256
new file mode 100644
index 0000000..0287a31
--- /dev/null
+++ b/tests/data_files/server1.req.commas.sha256
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICiTCCAXECAQAwRDELMAkGA1UEBhMCTkwxGTAXBgNVBAoMEFBvbGFyU1NMLCBD
+b21tYXMxGjAYBgNVBAMMEVBvbGFyU1NMIFNlcnZlciAxMIIBIjANBgkqhkiG9w0B
+AQEFAAOCAQ8AMIIBCgKCAQEAqQIfPUBq1VVTi/027oJlLhVhXom/uOhFkNvuiBZS
+0/FDUEeWEllkh2v9K+BG+XO+3c+S4ZFb7Wagb4kpeUWA0INq1UFDd185fAkER4Kw
+Vzlw7aPsFRkeqDMIR8EFQqn9TMO0390GH00QUUBncxMPQPhtgSVfCrFTxjB+FTms
++Vruf5KepgVb5xOXhbUjktnUJAbVCSWJdQfdphqPPwkZvq1lLGTrlZvc/kFeF6ba
+bFtpzAK6FCwWJJxK3M3Q91Jnc/EtoCP9fvQxyi1wyokLBNsupk9wbp7OvViJ4lNZ
+nm5akmXiiD8MlBmj3eXonZUT7Snbq3AS3FrKaxerUoJUsQIDAQABoAAwDQYJKoZI
+hvcNAQELBQADggEBAI7ZtRJYX6cMuwVhwXOizPV+WD17wby+273V4R8e9/6QA4nY
+RrSciAse+nWZz9Y6toBzLWr0K/9SCzwBX4OzMvLqu4A1G/wApODCDnbGaUPNUxRt
+6qbg8y7faBWvDGjk4+OpQ0suR/pdbM/L7pImqWRNwYdSPbJumNqIdB/Ewtso0TlA
+QVZ992RPe1LovXpDCfPP2p123L7/UHezNCtu5QmzLsDfQmN/rLhCJ2NZzTsnIdnP
+jp6XYU4kRV2BPDL65k38k8CSVWb6fw9XwPNUiyO3q1Zs6jpGJRYMLj9qTEoRN1np
+RME09CN2siMcgkv8UqDeDJ4Oa9qyXS6VXsDmSNI=
+-----END CERTIFICATE REQUEST-----
diff --git a/tests/suites/test_suite_asn1write.data b/tests/suites/test_suite_asn1write.data
index f844d48..725cbc2 100644
--- a/tests/suites/test_suite_asn1write.data
+++ b/tests/suites/test_suite_asn1write.data
@@ -91,8 +91,11 @@
 ASN.1 Write enum 2147483647
 mbedtls_asn1_write_enum:0x7fffffff:"0A047fffffff"
 
-#ASN.1 Write mpi 0
-#mbedtls_asn1_write_mpi:"00":"020100"
+ASN.1 Write mpi 0 (null)
+mbedtls_asn1_write_mpi:"":"020100"
+
+ASN.1 Write mpi 0 (1 limb)
+mbedtls_asn1_write_mpi:"00":"020100"
 
 ASN.1 Write mpi 1
 mbedtls_asn1_write_mpi:"01":"020101"
@@ -100,11 +103,17 @@
 ASN.1 Write mpi 0x7f
 mbedtls_asn1_write_mpi:"7f":"02017f"
 
-#ASN.1 Write mpi 0x80
-#mbedtls_asn1_write_mpi:"7f":"02020080"
+ASN.1 Write mpi 0x7f with leading 0 limb
+mbedtls_asn1_write_mpi:"00000000000000007f":"02017f"
 
-#ASN.1 Write mpi 0xff
-#mbedtls_asn1_write_mpi:"7f":"020200ff"
+ASN.1 Write mpi 0x80
+mbedtls_asn1_write_mpi:"80":"02020080"
+
+ASN.1 Write mpi 0x80 with leading 0 limb
+mbedtls_asn1_write_mpi:"000000000000000080":"02020080"
+
+ASN.1 Write mpi 0xff
+mbedtls_asn1_write_mpi:"ff":"020200ff"
 
 ASN.1 Write mpi 0x100
 mbedtls_asn1_write_mpi:"0100":"02020100"
@@ -112,17 +121,17 @@
 ASN.1 Write mpi, 127*8-1 bits
 mbedtls_asn1_write_mpi:"7f7b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8":"027f7f7b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8"
 
-#ASN.1 Write mpi, 127*8 bits
-#mbedtls_asn1_write_mpi:"e77b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8":"028180e77b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8"
+ASN.1 Write mpi, 127*8 bits
+mbedtls_asn1_write_mpi:"e77b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8":"02818000e77b16e05c1537de7c41cef1a0985d6a3ced98aec28e091874cbad6b5e40a5c956258f18861c28bed8ba808259339ee34b2e509c4080149474d5d5b86093f90c475a6443fc87e1a293d4151be625d652f1c32a00a018bba10c8a2ae5b2b0ee4be64e053dce9d07ec7919526c9dfcf2ec9fc3db485caa8e5a68a2cd0a427de8"
 
 ASN.1 Write mpi, 127*8+1 bits
-mbedtls_asn1_write_mpi:"108446d68934cc1af23c4cd909884d4bd737a1890e12f5ef8bf3d807d72feffa63c0bf2633345f8b8418d144617c871a7a0277ac0150eed4b3db7f9dff21114cd0d7f282400f03c931cb00c367550e374a1ed3762a1801ca714cfc8d5aac69707ca81e0661400ed0014d97cba48f94d835dd681fc3053c51958afbf7583cf49c":"028180108446d68934cc1af23c4cd909884d4bd737a1890e12f5ef8bf3d807d72feffa63c0bf2633345f8b8418d144617c871a7a0277ac0150eed4b3db7f9dff21114cd0d7f282400f03c931cb00c367550e374a1ed3762a1801ca714cfc8d5aac69707ca81e0661400ed0014d97cba48f94d835dd681fc3053c51958afbf7583cf49c"
+mbedtls_asn1_write_mpi:"018446d68934cc1af23c4cd909884d4bd737a1890e12f5ef8bf3d807d72feffa63c0bf2633345f8b8418d144617c871a7a0277ac0150eed4b3db7f9dff21114cd0d7f282400f03c931cb00c367550e374a1ed3762a1801ca714cfc8d5aac69707ca81e0661400ed0014d97cba48f94d835dd681fc3053c51958afbf7583cf49c":"028180018446d68934cc1af23c4cd909884d4bd737a1890e12f5ef8bf3d807d72feffa63c0bf2633345f8b8418d144617c871a7a0277ac0150eed4b3db7f9dff21114cd0d7f282400f03c931cb00c367550e374a1ed3762a1801ca714cfc8d5aac69707ca81e0661400ed0014d97cba48f94d835dd681fc3053c51958afbf7583cf49c"
 
 ASN.1 Write mpi, 255*8-1 bits
 mbedtls_asn1_write_mpi:"7bd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c":"0281ff7bd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c"
 
-#ASN.1 Write mpi, 255*8 bits
-#mbedtls_asn1_write_mpi:"fbd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c":"0282010000fbd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c"
+ASN.1 Write mpi, 255*8 bits
+mbedtls_asn1_write_mpi:"fbd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c":"0282010000fbd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c"
 
 ASN.1 Write mpi, 256*8-1 bits
 mbedtls_asn1_write_mpi:"7bd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c89":"028201007bd1913fcfb652896209ad3e62f5d04a8dfc71eb1698543c52200bd7bbf3c11dd9ff57c299a2f4da172b3d5bd7e29affddf8859be7d50a45537a0df15b17af603d18803fd17134847cba78d83e64bf9fee58364d6124add0541da7bad331cd35fb48186a74bc502ddb967602401c0db02b19e5d38f09e8618fa7f6a1a3f738629baffdc63d9d70d396007d943fd64ae696e5b7e88f2c6d6ec322b461dbddd36efa91d990343b66419cf4832a22dc9ad13021185a1bf007989a50ba3bfd1152b8db899482d3ed498d1b9fae243a3cdae9530d8b29fdb684f70cdc0c9b8527265312603b405e67d59d4b1d654ddc3b7fd5515acb32440dc80903c8474a2c136c89"
@@ -191,7 +200,7 @@
 mbedtls_asn1_write_string:MBEDTLS_ASN1_OID:"41":"060141"
 
 ASN.1 Write AlgorithmIdentifier, null parameters
-mbedtls_asn1_write_algorithm_identifier:"4f4944":8:"300d06034f4944"
+mbedtls_asn1_write_algorithm_identifier:"4f4944":0:"300706034f49440500"
 
 ASN.1 Write AlgorithmIdentifier, parameters (8 bytes)
 mbedtls_asn1_write_algorithm_identifier:"4f4944":8:"300d06034f4944"
diff --git a/tests/suites/test_suite_asn1write.function b/tests/suites/test_suite_asn1write.function
index 597d6ac..5aa4cbe 100644
--- a/tests/suites/test_suite_asn1write.function
+++ b/tests/suites/test_suite_asn1write.function
@@ -16,6 +16,8 @@
 int generic_write_start_step( generic_write_data_t *data )
 {
     mbedtls_test_set_step( data->size );
+    mbedtls_free( data->output );
+    data->output = NULL;
     ASSERT_ALLOC( data->output, data->size == 0 ? 1 : data->size );
     data->end = data->output + data->size;
     data->p = data->end;
@@ -45,8 +47,6 @@
     ok = 1;
 
 exit:
-    mbedtls_free( data->output );
-    data->output = NULL;
     return( ok );
 }
 
@@ -63,13 +63,14 @@
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = mbedtls_asn1_write_null( &data.p, data.start );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+        /* There's no parsing function for NULL. */
     }
 
 exit:
@@ -83,13 +84,21 @@
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = mbedtls_asn1_write_bool( &data.p, data.start, val );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        if( ret >= 0 )
+        {
+            int read = 0xdeadbeef;
+            TEST_EQUAL( mbedtls_asn1_get_bool( &data.p, data.end, &read ), 0 );
+            TEST_EQUAL( val, read );
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
     }
 
 exit:
@@ -103,13 +112,21 @@
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = mbedtls_asn1_write_int( &data.p, data.start, val );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        if( ret >= 0 )
+        {
+            int read = 0xdeadbeef;
+            TEST_EQUAL( mbedtls_asn1_get_int( &data.p, data.end, &read ), 0 );
+            TEST_EQUAL( val, read );
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
     }
 
 exit:
@@ -124,13 +141,21 @@
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = mbedtls_asn1_write_enum( &data.p, data.start, val );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        if( ret >= 0 )
+        {
+            int read = 0xdeadbeef;
+            TEST_EQUAL( mbedtls_asn1_get_enum( &data.p, data.end, &read ), 0 );
+            TEST_EQUAL( val, read );
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
     }
 
 exit:
@@ -142,25 +167,35 @@
 void mbedtls_asn1_write_mpi( data_t *val, data_t *expected )
 {
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
-    mbedtls_mpi mpi;
+    mbedtls_mpi mpi, read;
     int ret;
 
     mbedtls_mpi_init( &mpi );
+    mbedtls_mpi_init( &read );
     TEST_ASSERT( mbedtls_mpi_read_binary( &mpi, val->x, val->len ) == 0 );
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = mbedtls_asn1_write_mpi( &data.p, data.start, &mpi );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        if( ret >= 0 )
+        {
+            TEST_EQUAL( mbedtls_asn1_get_mpi( &data.p, data.end, &read ), 0 );
+            TEST_EQUAL( 0, mbedtls_mpi_cmp_mpi( &mpi, &read ) );
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
+        /* Skip some intermediate lengths, they're boring. */
         if( expected->len > 10 && data.size == 8 )
             data.size = expected->len - 2;
     }
 
 exit:
     mbedtls_mpi_free( &mpi );
+    mbedtls_mpi_free( &read );
     mbedtls_free( data.output );
 }
 /* END_CASE */
@@ -171,7 +206,7 @@
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
@@ -208,6 +243,8 @@
         }
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+        /* There's no parsing function for octet or character strings. */
+        /* Skip some intermediate lengths, they're boring. */
         if( expected->len > 10 && data.size == 8 )
             data.size = expected->len - 2;
     }
@@ -224,8 +261,11 @@
 {
     generic_write_data_t data = { NULL, NULL, NULL, NULL, 0 };
     int ret;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+    unsigned char *buf_complete = NULL;
+#endif /* MBEDTLS_ASN1_PARSE_C */
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
@@ -240,10 +280,69 @@
             ret -= par_len;
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        /* Only do a parse-back test if the parameters aren't too large for
+         * a small-heap environment. The boundary is somewhat arbitrary. */
+        if( ret >= 0 && par_len <= 1234 )
+        {
+            mbedtls_asn1_buf alg = {0, 0, NULL};
+            mbedtls_asn1_buf params = {0, 0, NULL};
+            /* The writing function doesn't write the parameters unless
+             * they're null: it only takes their length as input. But the
+             * parsing function requires the parameters to be present.
+             * Thus make up parameters. */
+            size_t data_len = data.end - data.p;
+            size_t len_complete = data_len + par_len;
+            unsigned char expected_params_tag;
+            size_t expected_params_len;
+            ASSERT_ALLOC( buf_complete, len_complete );
+            unsigned char *end_complete = buf_complete + len_complete;
+            memcpy( buf_complete, data.p, data_len );
+            if( par_len == 0 )
+            {
+                /* mbedtls_asn1_write_algorithm_identifier() wrote a NULL */
+                expected_params_tag = 0x05;
+                expected_params_len = 0;
+            }
+            else if( par_len >= 2 && par_len < 2 + 128 )
+            {
+                /* Write an OCTET STRING with a short length encoding */
+                expected_params_tag = buf_complete[data_len] = 0x04;
+                expected_params_len = par_len - 2;
+                buf_complete[data_len + 1] = (unsigned char) expected_params_len;
+            }
+            else if( par_len >= 4 + 128 && par_len < 3 + 256 * 256 )
+            {
+                /* Write an OCTET STRING with a two-byte length encoding */
+                expected_params_tag = buf_complete[data_len] = 0x04;
+                expected_params_len = par_len - 4;
+                buf_complete[data_len + 1] = 0x82;
+                buf_complete[data_len + 2] = (unsigned char) ( expected_params_len >> 8 );
+                buf_complete[data_len + 3] = (unsigned char) ( expected_params_len );
+            }
+            else
+            {
+                TEST_ASSERT( ! "Bad test data: invalid length of ASN.1 element" );
+            }
+            unsigned char *p = buf_complete;
+            TEST_EQUAL( mbedtls_asn1_get_alg( &p, end_complete,
+                                              &alg, &params ), 0 );
+            TEST_EQUAL( alg.tag, MBEDTLS_ASN1_OID );
+            ASSERT_COMPARE( alg.p, alg.len, oid->x, oid->len );
+            TEST_EQUAL( params.tag, expected_params_tag );
+            TEST_EQUAL( params.len, expected_params_len );
+            mbedtls_free( buf_complete );
+            buf_complete = NULL;
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
     }
 
 exit:
     mbedtls_free( data.output );
+#if defined(MBEDTLS_ASN1_PARSE_C)
+    mbedtls_free( buf_complete );
+#endif /* MBEDTLS_ASN1_PARSE_C */
 }
 /* END_CASE */
 
@@ -308,18 +407,63 @@
                    const unsigned char *buf, size_t bits ) =
         ( is_named ? mbedtls_asn1_write_named_bitstring :
           mbedtls_asn1_write_bitstring );
+#if defined(MBEDTLS_ASN1_PARSE_C)
+    unsigned char *masked_bitstring = NULL;
+#endif /* MBEDTLS_ASN1_PARSE_C */
 
-    for( data.size = 0; data.size < expected->len + 1; data.size++ )
+    /* The API expects `bitstring->x` to contain `bits` bits. */
+    size_t byte_length = ( bits + 7 ) / 8;
+    TEST_ASSERT( bitstring->len >= byte_length );
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+    ASSERT_ALLOC( masked_bitstring, byte_length );
+    if( byte_length != 0 )
+    {
+        memcpy( masked_bitstring, bitstring->x, byte_length );
+        if( bits % 8 != 0 )
+            masked_bitstring[byte_length - 1] &= ~( 0xff >> ( bits % 8 ) );
+    }
+    size_t value_bits = bits;
+    if( is_named )
+    {
+        /* In a named bit string, all trailing 0 bits are removed. */
+        while( byte_length > 0 && masked_bitstring[byte_length - 1] == 0 )
+            --byte_length;
+        value_bits = 8 * byte_length;
+        if( byte_length > 0 )
+        {
+            unsigned char last_byte = masked_bitstring[byte_length - 1];
+            for( unsigned b = 1; b < 0xff && ( last_byte & b ) == 0; b <<= 1 )
+                --value_bits;
+        }
+    }
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
+    for( data.size = 0; data.size <= expected->len + 1; data.size++ )
     {
         if( ! generic_write_start_step( &data ) )
             goto exit;
         ret = ( *func )( &data.p, data.start, bitstring->x, bits );
         if( ! generic_write_finish_step( &data, expected, ret ) )
             goto exit;
+#if defined(MBEDTLS_ASN1_PARSE_C)
+        if( ret >= 0 )
+        {
+            mbedtls_asn1_bitstring read = {0, 0, NULL};
+            TEST_EQUAL( mbedtls_asn1_get_bitstring( &data.p, data.end,
+                                                    &read ), 0 );
+            ASSERT_COMPARE( read.p, read.len,
+                            masked_bitstring, byte_length );
+            TEST_EQUAL( read.unused_bits, 8 * byte_length - value_bits );
+        }
+#endif /* MBEDTLS_ASN1_PARSE_C */
     }
 
 exit:
     mbedtls_free( data.output );
+#if defined(MBEDTLS_ASN1_PARSE_C)
+    mbedtls_free( masked_bitstring );
+#endif /* MBEDTLS_ASN1_PARSE_C */
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_x509parse.data b/tests/suites/test_suite_x509parse.data
index 7ac91f6..066d6e4 100644
--- a/tests/suites/test_suite_x509parse.data
+++ b/tests/suites/test_suite_x509parse.data
@@ -318,6 +318,10 @@
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_SHA512_C:MBEDTLS_RSA_C
 mbedtls_x509_csr_info:"data_files/server1.req.sha512":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=PolarSSL Server 1\nsigned using  \: RSA with SHA-512\nRSA key size  \: 2048 bits\n"
 
+X509 CSR Information RSA with SHA-256, containing commas
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_SHA256_C:MBEDTLS_RSA_C:MBEDTS_X509_INFO
+mbedtls_x509_csr_info:"data_files/server1.req.commas.sha256":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL\, Commas, CN=PolarSSL Server 1\nsigned using  \: RSA with SHA-256\nRSA key size  \: 2048 bits\n"
+
 X509 CSR Information EC with SHA1
 depends_on:MBEDTLS_ECDSA_C:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_SHA1_C
 mbedtls_x509_csr_info:"data_files/server5.req.sha1":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=localhost\nsigned using  \: ECDSA with SHA1\nEC key size   \: 256 bits\n"
@@ -399,6 +403,30 @@
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
 mbedtls_x509_dn_gets:"data_files/server2.crt":"issuer":"C=NL, O=PolarSSL, CN=PolarSSL Test CA"
 
+X509 Get Distinguished Name #5
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets:"data_files/server1.commas.crt":"subject":"C=NL, O=PolarSSL\, Commas, CN=PolarSSL Server 1"
+
+X509 Get Modified DN #1
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets_subject_replace:"data_files/server1.crt":"Modified":"C=NL, O=Modified, CN=PolarSSL Server 1":0
+
+X509 Get Modified DN #2 Name exactly 255 bytes
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets_subject_replace:"data_files/server1.crt":"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345":"C=NL, O=123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345, CN=PolarSSL Server 1":0
+
+X509 Get Modified DN #3 Name exceeds 255 bytes
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets_subject_replace:"data_files/server1.crt":"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456":"":MBEDTLS_ERR_X509_BUFFER_TOO_SMALL
+
+X509 Get Modified DN #4 Name exactly 255 bytes, with comma requiring escaping
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets_subject_replace:"data_files/server1.crt":"1234567890,1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234":"":MBEDTLS_ERR_X509_BUFFER_TOO_SMALL
+
+X509 Get Modified DN #5 Name exactly 255 bytes, ending with comma requiring escaping
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA1_C
+mbedtls_x509_dn_gets_subject_replace:"data_files/server1.crt":"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234,":"":MBEDTLS_ERR_X509_BUFFER_TOO_SMALL
+
 X509 Time Expired #1
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_HAVE_TIME_DATE:MBEDTLS_SHA1_C
 mbedtls_x509_time_is_past:"data_files/server1.crt":"valid_from":1
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index 00b6863..77f3d23 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -768,6 +768,37 @@
 }
 /* END_CASE */
 
+/* BEGIN_CASE depends_on:MBEDTLS_FS_IO:MBEDTLS_X509_CRT_PARSE_C:!MBEDTLS_X509_REMOVE_INFO */
+void mbedtls_x509_dn_gets_subject_replace( char * crt_file, char * new_subject_ou, char * result_str, int ret )
+{
+    mbedtls_x509_crt   crt;
+    char buf[2000];
+    int res = 0;
+
+    mbedtls_x509_crt_init( &crt );
+    memset( buf, 0, 2000 );
+
+    TEST_ASSERT( mbedtls_x509_crt_parse_file( &crt, crt_file ) == 0 );
+    crt.subject.next->val.p = (unsigned char *) new_subject_ou;
+    crt.subject.next->val.len = strlen( new_subject_ou );
+
+    res =  mbedtls_x509_dn_gets( buf, 2000, &crt.subject );
+
+    if ( ret != 0 )
+    {
+        TEST_ASSERT( res == ret );
+    }
+    else
+    {
+        TEST_ASSERT( res != -1 );
+        TEST_ASSERT( res != -2 );
+        TEST_ASSERT( strcmp( buf, result_str ) == 0 );
+    }
+exit:
+    mbedtls_x509_crt_free( &crt );
+}
+/* END_CASE */
+
 /* BEGIN_CASE depends_on:MBEDTLS_FS_IO:MBEDTLS_X509_CRT_PARSE_C */
 void mbedtls_x509_time_is_past( char * crt_file, char * entity, int result )
 {
diff --git a/tests/suites/test_suite_x509write.data b/tests/suites/test_suite_x509write.data
index 87f28a7..1c1cf30 100644
--- a/tests/suites/test_suite_x509write.data
+++ b/tests/suites/test_suite_x509write.data
@@ -112,7 +112,7 @@
 
 
 X509 String to Names #1
-mbedtls_x509_string_to_names:"C=NL,O=Offspark\, Inc., OU=PolarSSL":"C=NL, O=Offspark, Inc., OU=PolarSSL":0
+mbedtls_x509_string_to_names:"C=NL,O=Offspark\, Inc., OU=PolarSSL":"C=NL, O=Offspark\, Inc., OU=PolarSSL":0
 
 X509 String to Names #2
 mbedtls_x509_string_to_names:"C=NL, O=Offspark, Inc., OU=PolarSSL":"":MBEDTLS_ERR_X509_UNKNOWN_OID