进行RSA加密然后在AES密钥上解密的奇数错误

问题描述

以下代码

    key = sec.generateAESKey()
    print(key,': ',len(key))
    
    key = b64encode(key)
    print(key,len(key))
    
    key = sec.encryptasymmetric(str(key))
    key = sec.decryptasymmetric(key)
    print(key,len(key))
    
    key = b64decode(key)
    print(key,len(key))

输出

b'\ xae \ xfe \ x8b \ xb8 \ xbe \ x86 = \ xe8 \ x979 / @ \ xf58 \ xf9 \ x95':16

b'rv6LuL6GPeiXOS9A9Tj5lQ ==':24

b'rv6LuL6GPeiXOS9A9Tj5lQ ==':27

b'n \ xbb \ xfa。\ xe2 \ xfa \ x18 \ xf7 \ xa2 \\ xe4 \ xbd \ x03 \ xd4 \ xe3 \ xe6T':17

如您所见,非对称加密和解密出了点问题,因为密钥在b64decoding之前获得了3个字节,在b64decoding之后获得了1个字节。

基本功能是:

from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
from Cryptodome.Hash import SHA256
from base64 import b64decode
from base64 import b64encode
import re

# important global vars,don't need to re-generate these
public_key_plain = open("public.pem").read()
public_key = RSA.import_key(public_key_plain)
private_key = RSA.import_key(open("private.pem").read())

# constants
KEY_SIZE = 16
AUTH_TOKEN_EXPIRY = 15 # minutes

# encrypt using our public key
# data should be in a string format
def encryptasymmetric(data):
    # convert the data to utf-8
    data = data.encode("utf-8")
    # generate the cipher
    cipher = PKCS1_OAEP.new(public_key,hashAlgo=SHA256)
    # encrypt
    return b64encode(cipher.encrypt(data))

# decrypt some cipher text using our private key
def decryptasymmetric(ciphertext):
    # generate the cipher
    cipher = PKCS1_OAEP.new(private_key,hashAlgo=SHA256)
    # decrypt
    return cipher.decrypt(b64decode(ciphertext)).decode()

# generates a key for aes
def generateAESKey():
    return get_random_bytes(KEY_SIZE)

上面产生此错误代码是一些写在后端的单元测试的一部分。当客户端进行非对称加密而服务器进行解密时,这些功能可以正常工作。由于某种原因,它在这里失败了,但我不明白为什么。 如果有人可以看到非对称加密和解密出了什么问题,以及为什么它更改了真正有用的密钥。 预先感谢

解决方法

我没有您的.pem文件,因此无法按照您的方式进行复制,但是我可以这样:

>>> key = b'rv6LuL6GPeiXOS9A9Tj5lQ=='
>>> print(key,': ',len(key))
b'rv6LuL6GPeiXOS9A9Tj5lQ==' :  24

>>> key = str(key)
>>> print(key,len(key))
b'rv6LuL6GPeiXOS9A9Tj5lQ==' :  27

三个额外的字符只是在开头的b'和在结尾的'。如果您改为使用repr打印表示形式,则会看到它:

>>> key = b'rv6LuL6GPeiXOS9A9Tj5lQ=='
>>> print(repr(key),len(key))
b'rv6LuL6GPeiXOS9A9Tj5lQ==' :  24

>>> key = str(key)
>>> print(repr(key),len(key))
"b'rv6LuL6GPeiXOS9A9Tj5lQ=='" :  27

在原始密钥中,b''不是bytes字符串的一部分,它们只是表明它是{{1} } -string及其边界。就像bytes字符串周围的"一样,它也不是该字符串的一部分。但是在那个字符串中,strb' 是字符串的一部分。

不确定为什么将'转换为bytes,但是不应该使用str。我会使用它的str(key)方法。这样就很好了,您有一个decode()字符串,没有那些多余的字符:

str
,

看起来str()方法向已经以64为基数的编码数据中增加了3个字节。

base 64编码器返回ASCII编码的字节。因此,base 64编码器将返回 bytes ,而不仅仅是返回一个字符串(您将用于文本)。现在,如果将它们转换为字符串,则可能会看到它 just 包含ASCII。但是,似乎__str__实例上使用bytes方法时,Python中的标准编码器总是会重新生成3个字节,因为它会重新生成完整的字符串。

仅使用str(key,encoding='ascii')将字节解码为ASCII似乎可以解决此问题。但是,最好为此使用显式decode方法。


由于此superb答案而对答案进行了编辑。我想我本该让其他人查看实际字节。