3

Im able to decrypt the message running the script, but not when I use the user input method to get the encrypted message.

I have this simple script:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
padder = padding.PKCS7(128).padder()
backend = default_backend()

def operation_getmessage():
    messagesinput = input("Please, insert messages to decrypt: ")
    messagesinput = bytes(messagesinput, "utf-8")
    message = padder.update(messagesinput)
    message += padder.finalize()
    return message

keyinput = input("Please insert the key used for encrypt : ")
print(keyinput)
key = bytes(str(keyinput), 'ascii')
print("key value is :", key)
message = operation_getmessage()

cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
message_encrypt = encryptor.update(message) + encryptor.finalize()
print("Value of message_encrypted:", message_encrypt)
test = operation_getmessage()
print("Value of test: ", test)
decryptor = cipher.decryptor()
message_decrypt = decryptor.update(test) + decryptor.finalize()
print("Value of message_decrypted is: ", message_decrypt)
unpadder = padding.PKCS7(128).unpadder()
data = unpadder.update(message_decrypt)
print("Value of message is: ", data + unpadder.finalize())

As I said it works when I run the script skipping the user input message test = operation_getmessage(), but if I tried to get the message from the input I receiving this error:

  Traceback (most recent call last):
    File "/Users/JMD/PycharmProjects/M-CM-Task1/Test.py", line 23, in <module>
      test = operation_getmessage()
    File "/Users/JMD/PycharmProjects/M-CM-Task1/Test.py", line 10, in   operation_getmessage
      message = padder.update(messagesinput)
    File ".../lib/python3.7/site-packages/cryptography/hazmat/primitives/padding.py", line 118, in update
      self._buffer, data, self.block_size)
    File ".../lib/python3.7/site packages/cryptography/hazmat/primitives/padding.py", line 41, in _byte_padding_update
      raise AlreadyFinalized("Context was already finalized.")
    cryptography.exceptions.AlreadyFinalized: Context was already finalised.

this is the whole script exit:

Please insert the key used for encrypt : 123456789012345678901234
123456789012345678901234
key value is : b'123456789012345678901234'
Please, insert messages to decrypt: a secure message
Value of message_encrypted: b'\xe0\xd9\xa7\x85\x07\xe4\x1d;\x19\xcb\xce\xa1*\xbbo\xefT\xae\x15|v\xce\xa2\x88T\xae\x15|v\xce\xa2\x88'
Please, insert messages to decrypt: b'\xe0\xd9\xa7\x85\x07\xe4\x1d;\x19\xcb\xce\xa1*\xbbo\xefT\xae\x15|v\xce\xa2\x88T\xae\x15|v\xce\xa2\x88'

Traceback (most recent call last):
  File "Test.py", line 23, in <module>
test = operation_getmessage()
  File "Test.py", line 10, in operation_getmessage
message = padder.update(messagesinput)
  File ".../lib/python3.7/site-packages/cryptography/hazmat/primitives/padding.py", line 118, in update
self._buffer, data, self.block_size)
  File ".../lib/python3.7/site- packages/cryptography/hazmat/primitives/padding.py", line 41, in _byte_padding_update
raise AlreadyFinalized("Context was already finalized.")
cryptography.exceptions.AlreadyFinalized: Context was already finalized.

Process finished with exit code 1
2
  • 1
    You should better encode your encrypted text (in Base64 for example) so that you have only printables (and inputables) characters. Commented Oct 24, 2018 at 9:34
  • you can also generate public/private keys Pairs at both end, Generate Diffi Hellman keys using one's public key and others private key and then use AES encryption for messeges. Commented Oct 24, 2018 at 9:38

2 Answers 2

4

Looking at the docs:

After finalize() has been called this object can no longer be used; update() and finalize() will raise an AlreadyFinalized exception.

Try initializing the padder inside the function operation_getmessage(), so that it is a new padder every time the function gets called.

def operation_getmessage():
    padder = padding.PKCS7(128).padder()
    ...
    return message
Sign up to request clarification or add additional context in comments.

Comments

3

I have used the suggestions from @Ralf and @Kevin_Fontaine to fix your code so it works. Here is the corrected script, a few lines are changed and marked with comments:

import base64   # new line here
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding

backend = default_backend()

def operation_getmessage():
    padder = padding.PKCS7(128).padder()  # new line here
    messagesinput = input("Please, insert messages to decrypt: ")
    messagesinput = bytes(messagesinput, "utf-8")
    message = padder.update(messagesinput)
    message += padder.finalize()
    return message

keyinput = input("Please insert the key used for encrypt : ")
print(keyinput)
key = bytes(str(keyinput), 'ascii')
print("key value is :", key)
message = operation_getmessage()

cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
message_encrypt = encryptor.update(message) + encryptor.finalize()
print("Value of message_encrypted:", base64.b64encode(message_encrypt))  # new line here
test = operation_getmessage()
test = base64.b64decode(test)  # new line here
print("Value of test: ", test)
decryptor = cipher.decryptor()
message_decrypt = decryptor.update(test) + decryptor.finalize()
print("Value of message_decrypted is: ", message_decrypt)
unpadder = padding.PKCS7(128).unpadder()
data = unpadder.update(message_decrypt)
print("Value of message is: ", data + unpadder.finalize())

1 Comment

Works fine encoding it base64, great!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.