From 7a3396dc2d1146e83a5851b74f72af4d280c33b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Douglas=20Mendiz=C3=A1bal?= Date: Fri, 9 Aug 2019 12:28:42 -0500 Subject: [PATCH] Fix py3 compatibility issue in PKCS#11 plugin This patch fixes a str to char * type cast that is only valid in Python 2. Change-Id: Ia3bcfe125c4e2c49e8a3e2a4cdb2d67e641ceadd (cherry picked from commit 5018d8502d7ae0e41d29c7cf54082ce77d8ecf98) --- barbican/plugin/crypto/pkcs11.py | 10 +++++++++- barbican/tests/plugin/crypto/test_pkcs11.py | 9 +++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/barbican/plugin/crypto/pkcs11.py b/barbican/plugin/crypto/pkcs11.py index a1033a98e..4775b10cd 100644 --- a/barbican/plugin/crypto/pkcs11.py +++ b/barbican/plugin/crypto/pkcs11.py @@ -16,6 +16,7 @@ import textwrap import cffi from cryptography.hazmat.primitives import padding +import six from barbican.common import exception from barbican.common import utils @@ -386,7 +387,7 @@ class PKCS11(object): self._check_error(rv) # Session options - self.login_passphrase = login_passphrase + self.login_passphrase = _to_bytes(login_passphrase) self.rw_session = rw_session self.slot_id = slot_id @@ -795,3 +796,10 @@ class PKCS11(object): if test_random == b'\x00' * 100: raise exception.P11CryptoPluginException( u._("Apparent RNG self-test failure.")) + + +def _to_bytes(string): + if isinstance(string, six.binary_type): + return string + else: + return string.encode('UTF-8') diff --git a/barbican/tests/plugin/crypto/test_pkcs11.py b/barbican/tests/plugin/crypto/test_pkcs11.py index afb9ffca5..1c0ef12bb 100644 --- a/barbican/tests/plugin/crypto/test_pkcs11.py +++ b/barbican/tests/plugin/crypto/test_pkcs11.py @@ -399,3 +399,12 @@ class WhenTestingPKCS11(utils.BaseTestCase): def test_check_error_with_token_error(self): self.assertRaises(exception.P11CryptoTokenException, self.pkcs11._check_error, 0xe0) + + def test_converting_unicode_to_bytes(self): + self.assertEqual(b'foo', pkcs11._to_bytes(u'foo')) + + def test_converting_default_str_type_to_bytes(self): + self.assertEqual(b'foo', pkcs11._to_bytes('foo')) + + def test_converting_bytes_to_bytes(self): + self.assertEqual(b'foo', pkcs11._to_bytes(b'foo'))