File size: 1,620 Bytes
1f1b4db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
37
38
39
40
41
42
43
44
45
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64


def encrypt(message: str, key: str) -> str:
    """Encrypt error message using AES-128"""
    # Convert the key to bytes and ensure it's 16 bytes (128 bits)
    key_bytes = key.encode('utf-8')[:16].ljust(16, b'\0')
    
    # Create cipher
    cipher = AES.new(key_bytes, AES.MODE_CBC)
    
    # Pad and encrypt the message
    ct_bytes = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
    
    # Combine IV and ciphertext and encode as base64
    encrypted = base64.b16encode(cipher.iv + ct_bytes).decode('utf-8')
    return encrypted

def decrypt(encrypted: str, key: str) -> str:
    """Decrypt AES-128 encrypted message"""
    # Convert the key to bytes and ensure it's 16 bytes (128 bits)
    key_bytes = key.encode('utf-8')[:16].ljust(16, b'\0')
    
    # Decode the base64 message
    enc_bytes = base64.b16decode(encrypted)
    
    # Extract IV (first 16 bytes) and ciphertext
    iv = enc_bytes[:16]
    ct_bytes = enc_bytes[16:]
    
    # Create cipher with same key and IV
    cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
    
    # Decrypt and unpad the message
    pt_bytes = unpad(cipher.decrypt(ct_bytes), AES.block_size)
    
    # Convert back to string
    return pt_bytes.decode('utf-8')

if __name__ == "__main__":
    decrypted = decrypt("8HF8LyqjywlLR6DglBkvMxG2qdcAGiC2WHga8P982exv6fp/EXmrcwp6vYiZ1lVS/6nv+xJ72Nd6xV9cya6w3yjBr70U0ziiOtsyKFWAzLNa/swvZn9Ses2ZIbq/nZfkRv+Va19GqwPxV6mDpbuZp0Tl4VQtxJth+RzVX74i71G4mpp5luW8GTZSlnU+KPI8m6BbNKWXYou6ttS41IJubA==", "1923a821")
    print(decrypted)