首页 > Python资料 博客日记

Python pycryptodome类库使用学习总结

2024-09-20 00:30:03Python资料围观6

文章Python pycryptodome类库使用学习总结分享给大家,欢迎收藏Python资料网,专注分享技术知识

AES数据加解密

以下代码生成一个新的AES-128密钥,并将一段数据加密到一个文件中。我们使用 CTR 模式(这是一种 经典操作模式, 简单但不再推荐)。
仅使用CTR,接收者无法检测到密文(即加密数据)在传输过程中是否被修改。为了应对这种风险,例中还附加了一个MAC身份验证标签(采用SHA256模式的HMAC),该标签由第二个密钥制成。

# -*- coding:utf-8 -*-


from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
from Crypto.Random import get_random_bytes

data = 'secret data to transmit'.encode()

aes_key = get_random_bytes(16) # 返回一个包含适合加密使用的随机字节的字节对象
print('aes_key: ', aes_key) # aes_key:  b'\xf6Ke|/M\x93tv\n\xec\x1ej\xb4k\xab'

cipher = AES.new(aes_key, AES.MODE_CTR) # 创建一个 AES cipher
ciphertext = cipher.encrypt(data) # 加密数据,返回字节对象

hmac_key = get_random_bytes(16)
print('hmac_key: ', hmac_key) # hmac_key:  b'hU\xe6O\x8a\xc5\xa4g\xf3"\xc1K,f\x96\xdb'

hmac = HMAC.new(hmac_key, digestmod=SHA256)
tag = hmac.update(cipher.nonce + ciphertext).digest()

with open("encrypted.bin", "wb") as f:
    f.write(tag)
    f.write(cipher.nonce)
    f.write(ciphertext)

# 与接收者安全共享 aes_key和hmc_key
# encrypted.bin 可通过非安全信道传输

最后,接收者可以安全地加载回数据(如果他们知道这两个密钥(aes_keyhmc_key的话))。请注意,当检测到篡改时,代码会抛出ValueError异常。

import sys
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256

aes_key = b'\xf6Ke|/M\x93tv\n\xec\x1ej\xb4k\xab'
hmac_key = b'hU\xe6O\x8a\xc5\xa4g\xf3"\xc1K,f\x96\xdb'

with open("encrypted.bin", "rb") as f:
    tag = f.read(32)
    nonce = f.read(8)
    ciphertext = f.read()

try:
    hmac = HMAC.new(hmac_key, digestmod=SHA256)
    tag = hmac.update(nonce + ciphertext).verify(tag)
except ValueError:
    print("The message was modified!")
    sys.exit(1)

cipher = AES.new(aes_key, AES.MODE_CTR, nonce=nonce)
message = cipher.decrypt(ciphertext) # 解密数据,返回字节对象
print("Message:", message.decode())  # 输出:Message: secret data to transmit

一步完成数据加密和验证

上一节中的代码包含三个微妙但重要的设计决策:ciphernonce经过验证,验证在加密后执行,且加密和验证使用两个不相关的密钥。安全地组合加密原语并不容易,因此已经创建了更现代的加密cipher模式,OCB mode (查阅其它 经过身份验证的加密模式EAX, GCM, CCM, SIV)。

# -*- coding:utf-8 -*-

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

data = 'secret data to transmit'.encode()

aes_key = get_random_bytes(16)
print('aes_key: ', aes_key) # aes_key:  b'p.\xb7iD\x8a\xb6\xdc\x1e\x80E\xf4k:\xb4q'

cipher = AES.new(aes_key, AES.MODE_OCB)
ciphertext, tag = cipher.encrypt_and_digest(data)
assert len(cipher.nonce) == 15

with open("encrypted.bin", "wb") as f:
    f.write(tag)
    f.write(cipher.nonce)
    f.write(ciphertext)

# 与接收者安全共享 aes_key
# encrypted.bin 可通过非安全信道传输

数据解密

# -*- coding:utf-8 -*-


from Crypto.Cipher import AES

aes_key = b'p.\xb7iD\x8a\xb6\xdc\x1e\x80E\xf4k:\xb4q'

with open("encrypted.bin", "rb") as f:
    tag = f.read(16)
    nonce = f.read(15)
    ciphertext = f.read()

cipher = AES.new(aes_key, AES.MODE_OCB, nonce=nonce)
try:
    message = cipher.decrypt_and_verify(ciphertext, tag)
except ValueError:
    print("The message was modified!")
    exit(1)

print("Message:", message.decode())

RSA数据加解密

生成RSA秘钥

以下代码生成一个新的RSA密钥对(secret),并将其保存到一个受密码保护的文件中。使用 脚本 密钥推导函数,以阻止字典攻击。最后,代码以ASCII/PEM格式打印RSA公钥:

from Crypto.PublicKey import RSA

secret_code = "Unguessable"
key = RSA.generate(2048)
encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
                              protection="scryptAndAES128-CBC",
                              prot_params={'iteration_count':131072})

with open("rsa_key.bin", "wb") as f:
    f.write(encrypted_key)

print(key.publickey().export_key())

以下代码读取私钥RSA,然后再次打印公钥

from Crypto.PublicKey import RSA

secret_code = "Unguessable"
encoded_key = open("rsa_key.bin", "rb").read()
key = RSA.import_key(encoded_key, passphrase=secret_code)

print(key.publickey().export_key())

生成公钥和私钥

以下代码生成存储在receiver.pem中的公钥和存储在private.pem中的私钥。这些文件将在下面的示例中使用。每次生成不同的公钥和私钥对。

from Crypto.PublicKey import RSA

key = RSA.generate(2048)
private_key = key.export_key()
with open("private.pem", "wb") as f:
    f.write(private_key)

public_key = key.publickey().export_key()
with open("receiver.pem", "wb") as f:
    f.write(public_key)

使用RSA加解密数据

以下代码为我们拥有RSA公钥的接收者加密了一段数据。RSA公钥存储在一个名为receiver.pem的文件中。

为了能够加密任意数量的数据,使用混合加密方案。为AES会话密钥的非对称加密,使用RSA及PKCS1OAEP 。然后,会话密钥可用于加密所有实际数据。

与第一个示例一样,使用EAX模式来检测未经授权的修改

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

data = "I met aliens in UFO. Here is the map.".encode("utf-8")

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

# 使用公钥加密会话key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)

# 使用AES会话key加密数据
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)

with open("encrypted_data.bin", "wb") as f:
    f.write(enc_session_key)
    f.write(cipher_aes.nonce)
    f.write(tag)
    f.write(ciphertext)

接收方拥有RSA私钥。将首先使用它解密会话密钥,然后解密文件的其余部分::

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

private_key = RSA.import_key(open("private.pem").read())

with open("encrypted_data.bin", "rb") as f:
    enc_session_key = f.read(private_key.size_in_bytes())
    nonce = f.read(16)
    tag = f.read(16)
    ciphertext = f.read()

# 使用私钥解密会话key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# 使用AES会话key解密数据
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))

参考连接

https://www.pycryptodome.org/src/examples


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐