3

我在 Python 3.7.2 上安装pip install pycryptodome 。我遇到了obj = AES.new(key, AES.MODE_CBC, iv)行的异常。我的代码是:

from Crypto import Random
from Crypto.Cipher import AES
import random

def get_encryption():
    try:
        str = "This is input string"

        key = b'abcdefghijklmnop'  
        iv = Random.new().read(AES.block_size)

        obj = AES.new(key, AES.MODE_CBC, iv)
        encrypted = obj.encrypt(str)
        print(encrypted)
    except Exception as e:
        print(e)

我一直尝试但没有得到解决方法。

4

3 回答 3

3

在尝试了所有方法后,我得到了解决方案。我将密钥字符串转换为字节。代码是:

from Crypto import Random
from Crypto.Cipher import AES
import random

def get_encryption():
    try:
        strmsg = "This is input string"

        key = 'abcdefghijklmnop'  
        key1 = str.encode(key)

        iv = Random.new().read(AES.block_size)

        obj = AES.new(key1, AES.MODE_CBC, iv)
        encrypted = obj.encrypt(str.encode(strmsg))
        print(encrypted)
    except Exception as e:
        print(e)
于 2019-03-07T05:23:20.673 回答
1

//首先 pip install pycryptodome --(pycrypto 已过时并出现问题) // pip install pkcs7

from Crypto import Random
from Crypto.Cipher import AES
import base64
from pkcs7 import PKCS7Encoder
from app_settings.views import retrieve_settings # my custom settings

app_secrets = retrieve_settings(file_name='secrets');


def encrypt_data(text_data):
                    #limit to 32 bytes because my encryption key was too long
                    #yours could just be 'abcdefghwhatever' 
    encryption_key = app_secrets['ENCRYPTION_KEY'][:32]; 

    #convert to bytes. same as bytes(encryption_key, 'utf-8')
    encryption_key = str.encode(encryption_key); 
    
    #pad
    encoder = PKCS7Encoder();
    raw = encoder.encode(text_data) # Padding
    iv = Random.new().read(AES.block_size )

                                 # no need to set segment_size=BLAH
    cipher = AES.new( encryption_key, AES.MODE_CBC, iv ) 
    encrypted_text = base64.b64encode( iv + cipher.encrypt( str.encode(raw) ) ) 
    return encrypted_text;
于 2020-10-26T22:52:43.077 回答
0

将字符串转换为字节的最简单方法是使用binascii库:

from binascii import unhexlify, hexlify

def aes_encript(key, msg):
    c = unhexlify(key)
    m = unhexlify(msg)
    cipher = AES.new(c, AES.MODE_ECB)
    msg_en = cipher.encrypt(m)
    return hexlify(msg_en)
于 2022-01-23T07:35:55.880 回答