from Crypto.Cipher import AES
import socket
import base64
import os
class FileAES:
def __init__(self,key):
self.key = key
self.mode = AES.MODE_ECB
def encrypt(self,text):
file_aes = AES.new(self.key,self.mode)
text = text.encode('utf-8')
while len(text) % 16 != 0:
text += b'\x00'
en_text = file_aes.encrypt(text)
return str(base64.b64encode(en_text),encoding='utf-8')
def decrypt(self,text):
file_aes = AES.new(self.key,self.mode)
text = bytes(text,encoding='utf-8')
text = base64.b64decode(text)
de_text = file_aes.decrypt(text)
return str(de_text,encoding='utf-8').strip()
if not os.path.exists("PASSWORD"):
key=os.urandom(16)
print(key)
with open("PASSWORD","wb") as file:
file.write(key)
else:
key=open("PASSWORD","rb").read()
print(key)
data = ''
aes = FileAES(key)
data = aes.encrypt(data)
Traceback (most recent call last):
File "C:/Users/xxxx/xxxx.py", line 37, in <module>
data = aes.encrypt(data)
File "C:/Users/xxxx/xxxx.py", line 12, in encrypt
file_aes = AES.new(self.key,self.mode)
File "C:\Users\yuanx\AppData\Roaming\Python\Python39\site-packages\Crypto\Cipher\AES.py", line 232, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "C:\Users\yuanx\AppData\Roaming\Python\Python39\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "C:\Users\yuanx\AppData\Roaming\Python\Python39\site-packages\Crypto\Cipher\_mode_ecb.py", line 216, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "C:\Users\yuanx\AppData\Roaming\Python\Python39\site-packages\Crypto\Cipher\AES.py", line 93, in _create_base_cipher
raise ValueError("Incorrect AES key length (%d bytes)" % len(key))
ValueError: Incorrect AES key length (0 bytes)
我换了个包就跑出来了
from Cryptodome.Cipher import AES
import socket
import base64
import os
class FileAES:
def __init__(self, key):
self.key = key
self.mode = AES.MODE_ECB
def encrypt(self, text):
file_aes = AES.new(self.key, self.mode)
text = text.encode('utf-8')
while len(text) % 16 != 0:
text += b'\x00'
en_text = file_aes.encrypt(text)
return str(base64.b64encode(en_text), encoding='utf-8')
def decrypt(self, text):
file_aes = AES.new(self.key, self.mode)
text = bytes(text, encoding='utf-8')
text = base64.b64decode(text)
de_text = file_aes.decrypt(text)
return str(de_text, encoding='utf-8').strip()
if not os.path.exists("PASSWORD"):
key = os.urandom(16)
print(key)
with open("PASSWORD", "wb") as file:
file.write(key)
else:
key = open("PASSWORD", "rb").read()
print(key)
data = ''
aes = FileAES(key)
data = aes.encrypt(data)