-2

I want to encrypt a messages which I got from user input using Cryptography:

I have the following simple code:

import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
backend = default_backend()
messages = input("Please, insert messages to encrypt: ")
key = os.urandom(24)
print(key)
cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
cryptogram = encryptor.update(b"a secret message") + encryptor.finalize()
print(cryptogram)

When I hard code the messages "a secret message" with b prefix in the code it works fine. What I wanted to do is to use messagesvariable to get the text from user input.

messages = input("Please, insert messages to encrypt: ")

I've tried several ways to covert the string type from the input to byte type and pass it to encryptor.update method but nothing works for me.

messages = input(b"Please, insert messages to encrypt: ")
cryptogram = encryptor.update(byte, message) + encryptor.finalize()
...

Versions:

Python 3.7.0

Cryptography 2.4

Mac OS

Sallyerik
  • 489
  • 2
  • 11
  • 24
  • This was trivial to search. Please look for a duplicate question the next time. It will save you the effort of writing up a long question and us the effort of closing it. – timgeb Oct 22 '18 at 10:18
  • Thanks for the advise, sorry but I couldn't find it. – Sallyerik Oct 22 '18 at 12:42

2 Answers2

0
s = 'a secret message'
b = s.encode('utf-8')
Vikrant Sharma
  • 419
  • 3
  • 6
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 13:23:27 2018

@author: myhaspl
@email:myhaspl@myhaspl.com
@blog:dmyhaspl.github.io
"""
import os
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()
key = os.urandom(32)
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
messages = input("Please input your message: ")
messages=bytes(messages,"utf-8")
padded_data = padder.update(messages )
padded_data += padder.finalize()
print(padded_data)
ct = encryptor.update(padded_data) + encryptor.finalize()
decryptor = cipher.decryptor()
decryptorData=decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
data = unpadder.update(decryptorData)
print(data + unpadder.finalize())

Please input your message: hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io
b'hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io\x08\x08\x08\x08\x08\x08\x08\x08'
b'hello,world! I am dmyhaspl.my blog is dmyhaspl.github.io'
>>> 
myhaspldeep
  • 226
  • 2
  • 7