diff --git a/securesystemslib/formats.py b/securesystemslib/formats.py index 1dea7759..b19f6eb7 100755 --- a/securesystemslib/formats.py +++ b/securesystemslib/formats.py @@ -68,7 +68,6 @@ import binascii import calendar -import re import datetime import time @@ -613,7 +612,7 @@ def _canonical_string_encoder(string): A string with the canonical-encoded 'string' embedded. """ - string = '"%s"' % re.sub(r'(["\\])', r'\\\1', string) + string = '"%s"' % string.replace('\\', '\\\\').replace('"', '\\"') return string diff --git a/tests/test_formats.py b/tests/test_formats.py index bae97828..6d76279b 100755 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -283,6 +283,11 @@ def test_encode_canonical(self): self.assertEqual('{"x":3,"y":null}', encode({"x": 3, "y": None})) + # Test condition with escaping " and \ + self.assertEqual('"\\""', encode("\"")) + self.assertEqual('"\\\\"', encode("\\")) + self.assertEqual('"\\\\\\""', encode("\\\"")) + # Condition where 'encode()' sends the result to the callable # 'output'. self.assertEqual(None, encode([1, 2, 3], output))