python3 实现AES/CBC/PKCS5padding算法加解密

这篇博客介绍了如何使用Python3的pycryptodome库实现AES加密的CBC模式和PKCS5填充。文章通过对比Java的加密解密示例,详细解释了Python代码的实现过程,并强调了密钥和偏移量的处理以及加密模式、填充方式和字符编码等关键点。
摘要由CSDN通过智能技术生成

一、背景

将java代码的AES加密demo用python语言实现(通过pycryptodome包)

二、关键词

Python3、pycryptodome、AES/CBC/PKCS5padding、中文

三、java代码加密demo

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

private static String sKey = "********************************"; //密钥是string类型
private static String ivParameter = sKey.substring(0, 16); ; //偏移量是密钥截取16位,也是string类型

/**
* AES 加密
* @param str 明文
* @param key 秘钥
* @return 返回加密密文
* @throws Exception
*/
public static String encrypt(String str) throws Exception {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();  // 密钥转成byte
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); //偏移量转成byte
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(str.getBytes("utf-8"));
        return Base64.encodeBase64String(encrypted); //base64编码
    } catch (Exception ex) {
        return null;
    }
}

四、java代码解密demo

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

pri
### 回答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一个对称加密算法,加密和解密需要使用相同的密钥。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值