如何在python中将字符串变量转换为字节类型?

How can I convert string variable into byte type in python?

本问题已经有最佳答案,请猛点这里访问。

我想加密使用Cryptography从用户输入获得的消息:

我有以下简单的代码:

1
2
3
4
5
6
7
8
9
10
11
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)

当我硬编码消息"秘密消息"与代码中的b前缀它工作正常。
我想要做的是使用messagesvariable从用户输入获取文本。

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

我已经尝试了几种方法将字符串类型从输入转换为字节类型并将其传递给encryptor.update方法,但对我来说没有任何作用。

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

版本:

Python 3.7.0

密码学2.4

苹果系统


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 13:23:27 2018

@author: myhaspl
@email:[email protected]
@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'
>>>

1
2
s = 'a secret message'
b = s.encode('utf-8')