From 344caf335d94e7aa3a32bdd850ed1363088c896d Mon Sep 17 00:00:00 2001 From: Christian Heimes Date: Mon, 21 Sep 2015 14:44:50 +0200 Subject: Replace legacy Python base64 invocations with Py3-safe code Replace deprecated decodestring() and encodestring() with b64decode() and b64encode(). Provice specialized encode_cert() / decode_cert() functions to handle base64 encoding and decoding for X.509 certs in JSON strings. In Python 3 the base64 function don't suppor ASCII text, just ASCII bytes. --- base/common/python/pki/encoder.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'base/common/python/pki/encoder.py') diff --git a/base/common/python/pki/encoder.py b/base/common/python/pki/encoder.py index bf5d2e473..f83060103 100644 --- a/base/common/python/pki/encoder.py +++ b/base/common/python/pki/encoder.py @@ -1,11 +1,41 @@ from __future__ import absolute_import + +import base64 import json + +import six from six import iteritems, itervalues TYPES = {} NOTYPES = {} +def encode_cert(data): + """base64 encode X.509 certificate + + Python 3's base64.b64encode() doesn't support ASCII text. + + :param data: data as bytes or ASCII text + :type data: str, bytes + :rtype: bytes + """ + if isinstance(data, six.text_type): + data = data.encode('ascii') + return base64.b64encode(data) + + +def decode_cert(data): + """base64 decode X.509 certificate + + :param data: data as bytes or ASCII text + :type data: str, bytes + :rtype: bytes + """ + if isinstance(data, six.text_type): + data = data.encode('ascii') + return base64.b64decode(data) + + class CustomTypeEncoder(json.JSONEncoder): """ A custom JSONEncoder class that knows how to encode core custom -- cgit