【问题标题】:TypeError: Object type <class 'str'> cannot be passed to C codeTypeError:对象类型 <class 'str'> 无法传递给 C 代码
【发布时间】:2020-10-27 08:22:02
【问题描述】:

我正在尝试在python中实现aes加密和解密。当我执行代码时,它返回错误。我已经在我的机器上安装了 anaconda。我在 jupyter notebook 中运行脚本。

!pip install pycryptodome

import base64
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[0:-ord(s[-1])]

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:] ))

cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret')
decrypted = cipher.decrypt(encrypted)
print(encrypted)
print(decrypted)

如何解决?

【问题讨论】:

  • 请修正缩进。错误是什么? (哪条线等...)
  • 原始=垫(原始)。 TypeError: 对象类型 不能传递给 C 代码
  • 您的代码是为 Python2 编写的,在 Python3 中 strbytes 是不同的对象。您必须用字节替换所有字符串(请参阅str.encode)。
  • 我对上面的代码做了如下改动。 pwd=b"mysecretpassword" cipher = AESCipher(pwd) msg​​=b"Secret" encrypted = cipher.encrypt(msg) print(encrypted) print(decrypted) 它返回 TypeError: can't concat str to bytes

标签: python encryption


【解决方案1】:

只需将 unpad 更新为 unpad = lambda s : s[0:-ord(s[-1:])] 如果您尝试打印 s[-1] 的值, ord() 期望长度为 1 的字符串的主要问题它会打印 10 不是一个字符而是 s [-1:] 打印值为 b'\n' 这是一个字符

还将密钥编码为字节 bytes(key, 'utf-8') 和 pad

pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')

确保所有输入都是字节

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

BS = 16
pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
unpad = lambda s : s[0:-ord(s[-1:])]

class AESCipher:

    def __init__( self, key ):
        self.key = bytes(key, 'utf-8')

    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:] )).decode('utf8')

cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret')
decrypted = cipher.decrypt(encrypted)

print(encrypted)
print(decrypted)

【讨论】:

  • 它再次返回相同的错误。 TypeError: 对象类型 不能传递给 C 代码
  • @Jozf 我已经更新了我的答案我认为它现在工作正常我在 jjupyter notebook 上试过了
  • 谢谢。但是在输出中,在加密和解密数据之前都有 b。你看见了吗 ? b'6tx+0XpByP2w2cluCcDgYLnx3Zu65vbM8+Db2su4yKg=' b'Secret' 我们如何删除它?
  • @Jozf 只是解码结果 .decode('utf8') 我在回答中更新了它
【解决方案2】:

//首先 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 16 bytes because my encryption key was too long
                    #yours could just be 'abcdefghwhatever' 
    encryption_key = app_secrets['ENCRYPTION_KEY'][:16]; 

    #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 ) #AES.block_size defaults to 16

                                 # 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;

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多