如何解决尝试在python中使用AES进行加密和解密时收到类型错误
这是主要的python文件。当我运行它时,我得到以下输出。我认为这与数据类型有关。
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import tkinter
import tkinter.filedialog
import tkinter
import hashlib
key=b'\x07\x12>\x1fH#V\xc4\x15\xf6\x84@z;\x87#\xe1\x0b,\xbb\xc0\xb8\xfc\xd6(,I\xd3|\x9c\x1a\xbc'
def pad(s):
return s+ b"\0" * (AES.block_size- len(s)% AES.block_size)
def encrypt(message,key,key_size=256):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key,AES.MODE_CBC,iv)
return iv+cipher.encrypt(message)
def decrypt(ciphertext,key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key,iv)
plaintext = cipher.decrypt(ciphertext[:AES.block_size])
return plaintext.rstrip(b"\0") #this is use for remove padding character
test=encrypt("hello",key)
print(test)
以下是输出:
Traceback (most recent call last):
File "crypto1.py",line 31,in <module>
test=encrypt("hello",key)
File "crypto1.py",line 18,in encrypt
message = pad(message)
File "crypto1.py",line 15,in pad
return s+ b"\0" * (AES.block_size- len(s)% AES.block_size)
TypeError: can only concatenate str (not "bytes") to str
解决方法
在解决一些问题后,这是您的代码,在代码中已注释掉:
from Crypto.Cipher import AES
import os
# first you import so many library you dont use
key = b'\x07\x12>\x1fH#V\xc4\x15\xf6\x84@z;\x87#\xe1\x0b,\xbb\xc0\xb8\xfc\xd6(,I\xd3|\x9c\x1a\xbc'
def pad(s):
# Here you concatenate string to a bytes
# causing python to raise an error
return s + ("\0" * (AES.block_size - len(s) % AES.block_size))
def encrypt(message,key,key_size=256):
message = pad(message)
# I used os.urandom Here instead of crypto Random
# but you can use any cryptographic PRNG
iv = os.urandom(16)
cipher = AES.new(key,AES.MODE_CBC,iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext,key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key,iv)
# You use ciphertext[:AES.block_size] which will
# decrypt first 16 bytes(ie; decrypt iv)
# use ciphertext[AES.block_size:]
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0") # this is use for remove padding character
test = encrypt("hello World",key)
plaintext = decrypt(test,key)
print(test)
print(plaintext)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。