关于base64和AES结合加密解密中python3报错的情况

python2执行下面代码可以成功,python3中中文总是不能加密

'''

#coding: utf-8


import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES


BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[:-ord(s[len(s)-1:])]


import base64
from Crypto.Cipher import AES
from Crypto import Random


class AESCipher:
    def __init__( self, key ):
        self.key = key


    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) ) 


    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))


xxx = AESCipher('1234567812345678')
text = 'abcd中国'


text1 = xxx.encrypt(text)
text2 = xxx.decrypt(text1)


print text
print text2

'''

其中一种解决办法就是改变加密模式:

AES.new(self.key, MODE_CFB, iv )

在Python,你可以使用`cryptography`这个流行的库来实现AES(高级加密标准)的加密和解密功能。首先,你需要安装这个库,如果你还没有安装,可以使用pip命令: ```bash pip install cryptography ``` 然后,下面是一个简单的示例,展示了如何使用AES模式(如CBC、ECB等)对数据进行加解密: ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC import base64 # 密码哈希(这里假设密码已存在) password = b"your_secret_password" salt = b'some_salt' kdf = PBKDF2HMAC( algorithm=hashlib.sha256, length=32, # AES key长度 salt=salt, iterations=100000, # 可调整迭代次数增加安全性 backend=default_backend() ) # 加密函数 def encrypt(plaintext, key): cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]), backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext) + encryptor.finalize() return base64.b64encode(ciphertext).decode('utf-8') # 解密函数 def decrypt(ciphertext, key): key = kdf.derive(key) ciphertext_b64 = base64.b64decode(ciphertext.encode('utf-8')) cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]), backend=default_backend()) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext_b64) + decryptor.finalize() return plaintext.decode('utf-8') # 示例 plaintext = "Hello, World!" key = kdf.derive(password) ciphertext = encrypt(plaintext.encode('utf-8'), key) print("Encrypted:", ciphertext) decrypted_text = decrypt(ciphertext, password) print("Decrypted:", decrypted_text) ``` 在这个例子,我们使用了PKCS5薛定谔盐(PBKDF2)对密码进行了安全的哈希,生成了一个密钥。注意实际应用需要妥善处理用户输入和存储的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值