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

Bahij Zeineh

以下代码

    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)

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

马丁·波德威斯

看起来该str()方法将3个字节添加到已经基本64位编码的数据中。

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

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


答案因为这个极好的答案而被编辑我想我本该让其他人查看实际字节。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章