from Crypto import Random
from Crypto.Cipher import AES
from passlib.hash import sha512_crypt
import os
import hashlib
import base64
import sys
import socket, select
def hash(password):
return hashlib.sha256(bytes(password, encoding= 'utf-8')).hexdigest()
def encrypt(raw_data):
pad = lambda s: s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
raw_data = pad(raw_data)
iv = Random.new().read(AES.block_size)
print(sys.getsizeof(iv)) #prints 49
print(sys.getsizeof(KEY)) # prints 113, shouldn't this be 32 bytes (256 bits) ?
cipher = AES.new(KEY, AES.MODE_CBC, iv) # error occurs here
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw_data))
def decrypt(encrypted_text):
unpad = lambda s : s[:-ord(s[len(s) -1:])]
encrypted_text = base64.urlsafe_b64decode(encrypted_text)
iv = encrypted_text[:AES.block_size]
cipher = AES.new(KEY, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(encrypted_text[AES.block_size:]))
password="mypassword"
KEY = hash(password)
encrypt("some data to encrypt") #error when calling this function
每次输入print(sys.getsizeof(KEY))
时,密码都是113。因为我使用的是sha256,所以不应该是32。
我相信这是我收到此错误的原因,但我不确定。任何帮助将不胜感激