Python XTEA加密报错:a bytes-like object is required, not 'str' 求助
Hey there! I totally get being stuck with crypto stuff when you're just starting out—let's sort this out together. The error you're seeing (TypeError: a bytes-like object is required, not 'str') is pointing straight at one obvious issue, but there are a couple other small fixes to make sure your encryption works as expected.
Let's Break Down the Problems
IV is a string, not bytes
The XTEA implementation you're using expects the IV (initialization vector) to be a bytes object matching the algorithm's block size (8 bytes for XTEA), but you passed a plain string"12345678". That's the immediate cause of your error.Incorrect data handling with
message * 8
Multiplying your input data by 8 isn't how block ciphers work—you need to pad your data to make its length a multiple of the block size (8 bytes) instead of just repeating it. Otherwise, you'll end up with way more data than you need, and it won't decrypt properly later.Potential key length mismatch
XTEA requires a 16-byte (128-bit) key. If yournormales_passwordencodes to something shorter or longer than 16 bytes, you'll run into unexpected behavior. We'll fix that by hashing the password to a consistent 16 bytes.
Corrected Code
First, add a padding function to handle data length properly:
def pkcs7_pad(data: bytes, block_size: int = 8) -> bytes: padding_length = block_size - (len(data) % block_size) padding = bytes([padding_length]) * padding_length return data + padding
Then fix your XTEA algorithm function:
from xtea import new, MODE_CFB import hashlib def xtea_algo(message: bytes, password: bytes): # Hash password to get a consistent 16-byte XTEA key key = hashlib.sha256(password).digest()[:16] # Take first 16 bytes to match XTEA's key length # Pad message to fit XTEA's 8-byte block size padded_message = pkcs7_pad(message) # IV is now a bytes object (notice the `b` prefix) iv = b"12345678" # Create CFB mode encryptor with valid bytes inputs cipher = new(key, mode=MODE_CFB, IV=iv) encrypted_data = cipher.encrypt(padded_message) return encrypted_data
Update your calling code to ensure all inputs are bytes:
# Make sure macpassword_hashed_versch, tea_password, txt_neu are already bytes # If they're strings, encode them first: e.g., txt_neu = "your_text".encode('utf-8') datas = macpassword_hashed_versch + tea_password + txt_neu normales_password_bytes = normales_password.encode('utf-8') data_en = xtea_algo(datas, normales_password_bytes)
Why This Works
- The
pkcs7_padfunction ensures your data fits neatly into XTEA's 8-byte blocks, a requirement for all block ciphers. - Hashing the password guarantees we get a valid 16-byte key, no matter how long your original password is.
- Using
b"12345678"converts the IV to a bytes object, fixing the immediate TypeError you encountered.
内容的提问来源于stack exchange,提问作者Nicole Cheesus

