python AES ECB
时间: 2023-08-27 11:16:28 浏览: 196
AES (Advanced Encryption Standard) is a symmetric encryption algorithm that can be used for encryption and decryption of data. ECB (Electronic Codebook) is one of the modes of operation for AES.
In Python, you can use the `pycryptodome` library to perform AES encryption and decryption in ECB mode. Here's an example:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def pad(data):
length = 16 - (len(data) % 16)
return data + bytes([length] * length)
def unpad(data):
return data[:-data[-1]]
def encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_ECB)
padded_data = pad(plain_text)
encrypted_data = cipher.encrypt(padded_data)
return encrypted_data
def decrypt(encrypted_data, key):
cipher = AES.new(key, AES.MODE_ECB)
decrypted_data = cipher.decrypt(encrypted_data)
unpadded_data = unpad(decrypted_data)
return unpadded_data
# Example usage
key = get_random_bytes(16) # 128-bit key
plain_text = b"Hello, World!"
encrypted_data = encrypt(plain_text, key)
print("Encrypted data:", encrypted_data)
decrypted_data = decrypt(encrypted_data, key)
print("Decrypted data:", decrypted_data.decode())
```
Make sure to install the `pycryptodome` library using `pip install pycryptodome` before running the code. This example demonstrates how to encrypt and decrypt data using AES in ECB mode with a randomly generated 128-bit key. Remember that ECB mode is not secure for encrypting multiple blocks of data with the same key, as it does not provide semantic security. It is recommended to use other modes like CBC (Cipher Block Chaining) or CTR (Counter) for secure encryption.
阅读全文