From b100848f937397aaef3ed9ce7a108b356381f849 Mon Sep 17 00:00:00 2001 From: Nick Baum Date: Wed, 30 Jan 2019 15:28:11 -0800 Subject: [PATCH] Encode plaintext before padding it WARNING: I'm no crypto expert, so please review with care. I ran into this same issue when trying to encrypt utf-8 text: https://github.com/StackStorm/st2/issues/4513 I believe the problem is that the plaintext is padded before it's encoded, and the encoding changes the length of the data. Moving the encoding before the padding seems to resolve the issue. --- st2common/st2common/util/crypto.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/st2common/st2common/util/crypto.py b/st2common/st2common/util/crypto.py index e6b0ecfefd..2a5a9d401f 100644 --- a/st2common/st2common/util/crypto.py +++ b/st2common/st2common/util/crypto.py @@ -216,6 +216,10 @@ def cryptography_symmetric_encrypt(encrypt_key, plaintext): assert isinstance(aes_key_bytes, six.binary_type) assert isinstance(hmac_key_bytes, six.binary_type) + # Convert data to bytes + if isinstance(plaintext, (six.text_type, six.string_types)): + plaintext = plaintext.encode('utf-8') + # Pad data data = pkcs5_pad(plaintext) @@ -229,11 +233,6 @@ def cryptography_symmetric_encrypt(encrypt_key, plaintext): # NOTE: We don't care about actual Keyczar header value, we only care about the length (5 # bytes) so we simply add 5 0's header_bytes = b'00000' - - if isinstance(data, (six.text_type, six.string_types)): - # Convert data to bytes - data = data.encode('utf-8') - ciphertext_bytes = encryptor.update(data) + encryptor.finalize() msg_bytes = header_bytes + iv_bytes + ciphertext_bytes