用python实现AES加密、解密。
时间: 2023-09-15 15:06:02 浏览: 67
### 回答1:
下面是使用 Python 实现 AES 加密和解密的示例代码:
```
import base64
import hashlib
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding, serialization
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes
)
def generate_key(password: str, salt: bytes, iterations: int = 100000, key_size: int = 32):
kdf = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations, key_size)
return kdf
def encrypt(plaintext: str, password: str, salt: bytes):
# Generate key
key = generate_key(password, salt)
# Add padding to the plaintext
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_plaintext = padder.update(plaintext.encode()) + padder.finalize()
# Generate a random IV
iv = os.urandom(16)
# Encrypt the plaintext
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
# Concatenate the IV and the ciphertext
encrypted_message = iv + ciphertext
# Encode the encrypted message as a base64 string
encoded_encrypted_message = base64.b64encode(encrypted_message)
return encoded_encrypted_message
def decrypt(encoded_encrypted_message: str, password: str, salt: bytes):
# Decode the encrypted message from a base64 string
encrypted_message = base64.b64decode(encoded_encrypted_message)
# Split the IV and the ciphertext
iv = encrypted_message[:16]
ciphertext = encrypted_message[16:]
# Generate key
key = generate_key(password, salt)
# Decrypt the ciphertext
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# Remove padding from the plaintext
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
return plaintext.decode()
```
使用示例:
```
password = "secret password"
salt = b"salt"
plaintext = "hello world"
encoded_encrypted_message = encrypt(plaintext, password, salt)
print("Encrypted message:", encoded_encrypted_message)
decrypted_plaintext = decrypt(encoded_encrypted_message,
### 回答2:
使用Python实现AES加密和解密可以使用PyCryptodome库。首先需要安装PyCryptodome库,使用pip安装命令:pip install pycryptodome。
以下是使用Python实现AES加密和解密的示例代码:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# 定义密钥和初始化向量
key = get_random_bytes(16)
iv = get_random_bytes(16)
def encrypt(plaintext):
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
return ciphertext
def decrypt(ciphertext):
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode()
# 测试加密和解密功能
plaintext = "Hello, AES!"
print("Plaintext:", plaintext)
ciphertext = encrypt(plaintext)
print("Ciphertext:", ciphertext)
decrypted_text = decrypt(ciphertext)
print("Decrypted Text:", decrypted_text)
```
这个示例代码实现了AES加密和解密的功能。首先定义了一个随机生成的16字节密钥和初始化向量。然后定义了`encrypt`函数和`decrypt`函数分别用于加密和解密。
在加密函数中,使用AES.MODE_CBC模式创建了一个AES加密器,并使用密钥和初始化向量进行初始化。然后使用`pad`函数对明文进行填充,并调用加密器的`encrypt`方法进行加密。
在解密函数中,同样使用AES.MODE_CBC模式创建一个AES解密器,并使用密钥和初始化向量进行初始化。解密器调用`decrypt`方法对密文进行解密,并使用`unpad`函数去除填充。
最后,测试加密和解密功能。将明文传递给`encrypt`函数进行加密,得到密文。然后将密文传递给`decrypt`函数进行解密,得到原始的明文。
请注意,这个示例代码中的密钥和初始化向量是随机生成的,每次运行代码都会生成不同的密钥和向量。在实际应用中,应该将密钥和向量保存下来,以便在解密时使用相同的密钥和向量。
### 回答3:
在Python中,可以使用Crypto库来实现AES加密和解密功能。首先需要安装Crypto库,可以使用pip命令进行安装。
加密过程如下:
```
from Crypto.Cipher import AES
def encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_ECB)
encrypted_text = cipher.encrypt(plain_text)
return encrypted_text
key = b'1234567890123456' # 16字节的密钥
plain_text = b'Hello World!' # 待加密的明文
encrypted_text = encrypt(plain_text, key)
print('加密后的结果:', encrypted_text)
```
解密过程如下:
```
from Crypto.Cipher import AES
def decrypt(encrypted_text, key):
cipher = AES.new(key, AES.MODE_ECB)
plain_text = cipher.decrypt(encrypted_text)
return plain_text
key = b'1234567890123456' # 16字节的密钥
encrypted_text = b'\xd6#\x82\xa9W\x8c\xf1\x15J\'=0\xe8\x99' # 待解密的密文
decrypted_text = decrypt(encrypted_text, key)
print('解密后的结果:', decrypted_text)
```
需要注意的是,使用AES进行加密和解密时,需要保证密钥的长度是16、24或32字节,分别对应AES-128、AES-192和AES-256算法。此外,AES是一个对称加密算法,加密和解密需要使用相同的密钥。