gpt4 book ai didi

python - Pycryptodome 官方例子不清楚

转载 作者:行者123 更新时间:2023-11-28 17:13:02 27 4
gpt4 key购买 nike

我对 https://www.pycryptodome.org/en/latest/src/examples.html#encrypt-data-with-rsa 有疑问

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]

它说我应该使用 cipher.nonce,但是 cipher 在示例中是未定义的。我应该使用

cipher = AES.new(key, AES.MODE_EAX)
cipher = AES.new(key, AES.MODE_EAX, nonce)

还是别的?我赌 cipher = AES.new(key, AES.MODE_EAX, nonce),但我想确保它在密码学上是安全的。在那种情况下,cipher 所需的key 应该是recipient_key,对吗?

最佳答案

这段代码有效,但我不确定它的安全性,所以如果有人能证实这一点,我们将不胜感激。

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

data = "abc".encode("utf-8")

#print (open("pubkey.der").read())
recipient_key = RSA.import_key(open("pubkey.der").read())
session_key = get_random_bytes(16)
cipher_aes = AES.new(session_key, AES.MODE_EAX)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)

# Encrypt the data with the AES session key
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
enc_session_key = (cipher_rsa.encrypt(session_key))
encoded = [x for x in (cipher_aes.nonce, tag, ciphertext, enc_session_key) ]

#------------------------------------------------------

(cipher_aes_nonce, tag, ciphertext, enc_session_key) = encoded

private_key = RSA.import_key(open("privkey.der").read())

#print (enc_session_key, cipher.nonce, tag, ciphertext)

# Decrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)

print (data.decode("utf-8"))

关于python - Pycryptodome 官方例子不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46132222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com