balena / python-smime

S/MIME encoder in pure python
Apache License 2.0
18 stars 17 forks source link

ValueError: The length of the provided data is not a multiple of the block length. #13

Open dobeerman7 opened 4 years ago

dobeerman7 commented 4 years ago

The problem is with special characters. When I trying to encrypt any non utf-8 characters, it fails with the following exception:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-82-46ba27e8d637> in <module>
     13 # with open('smime.cer', 'rb') as pem:
     14 key = obj.get()["Body"].read()
---> 15 message = smime.encrypt(message, key)
     16 
     17 # message = '\n'.join(message)

~/dev/jupyter/venv/lib/python3.8/site-packages/smime/encrypt.py in encrypt(message, certs, algorithm)
     62 
     63     # Encode the content
---> 64     encrypted_content_info = block_cipher.encrypt(content)
     65 
     66     # Build the enveloped data and encode in base64

~/dev/jupyter/venv/lib/python3.8/site-packages/smime/block.py in encrypt(self, data)
     49     def encrypt(self, data):
     50         padded_data = self._pad(data, self.block_size)
---> 51         encrypted_content = self._encryptor.update(padded_data.encode('utf-8')) + self._encryptor.finalize()
     52         return {
     53             'content_type': 'data',

~/dev/jupyter/venv/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/base.py in finalize(self)
    157         if self._ctx is None:
    158             raise AlreadyFinalized("Context was already finalized.")
--> 159         data = self._ctx.finalize()
    160         self._ctx = None
    161         return data

~/dev/jupyter/venv/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ciphers.py in finalize(self)
    176                 )
    177             )
--> 178             raise ValueError(
    179                 "The length of the provided data is not a multiple of "
    180                 "the block length."

ValueError: The length of the provided data is not a multiple of the block length.
message = "Beste Grüße,\nIhr Team von Team\n£619"
message = smime.encrypt(message, key)

Any ideas, how to encrypt strings like this?