diff --git a/oslo_serialization/base64.py b/oslo_serialization/base64.py index 7ff6e57..401e036 100644 --- a/oslo_serialization/base64.py +++ b/oslo_serialization/base64.py @@ -22,6 +22,7 @@ Utilities to encode and decode Base64. from __future__ import absolute_import import base64 +import binascii import six @@ -64,13 +65,16 @@ def decode_as_bytes(encoded): :returns: decoded bytes string (bytes) Use decode_as_text() to get the decoded string as text. + + A TypeError is raised if the input is invalid (or incorrectly padded). """ if isinstance(encoded, bytes): encoded = encoded.decode('ascii') - if six.PY2: - return base64.decodestring(encoded) - else: + try: return base64.b64decode(encoded) + except binascii.Error as e: + # Transform this exception for consistency. + raise TypeError(str(e)) def decode_as_text(encoded, encoding='utf-8'): diff --git a/oslo_serialization/tests/test_base64.py b/oslo_serialization/tests/test_base64.py index 8b29d70..645f2ee 100644 --- a/oslo_serialization/tests/test_base64.py +++ b/oslo_serialization/tests/test_base64.py @@ -13,8 +13,6 @@ # License for the specific language governing permissions and limitations # under the License. -import binascii - from oslo_serialization import base64 from oslotest import base as test_base @@ -48,7 +46,7 @@ class Base64Tests(test_base.BaseTestCase): base64.decode_as_bytes(u'dGV4dA==')) def test_decode_as_bytes__error(self): - self.assertRaises(binascii.Error, + self.assertRaises(TypeError, base64.decode_as_bytes, 'hello world')