发生异常:对象类型<class'str'=“”>无法传递给C代码

时间:2019-03-06 12:10:11

标签: python-3.x pycryptodome

我在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)

我一直尝试着,但是没有找到解决方法。

2 个答案:

答案 0 :(得分:0)

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

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)

答案 1 :(得分:0)

///第一个pip安装pycryptodome-(pycrypto已过时并出现问题) // pip安装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;