python非对称加密_内存python中敏感数据的非对称加密

本文介绍了如何在Python中使用非对称加密算法来保护内存中的敏感数据,通过引用外部资源详细阐述了具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python非对称加密

Sometimes it is necessary to encrypt data between read and write cycles, where for instance we have a device which takes sensitive data and records it for processing. However, since the data is stored on the same device it is written we do not want the same key that is used to encrypt the data to be able to decrypt it. This is why we use asymmetric encryption.

有时有必要在读写周期之间对数据进行加密,例如,我们有一个设备可以接收敏感数据并将其记录下来进行处理。 但是,由于数据是存储在同一设备上的,因此我们不希望将用于加密数据的同一密钥解密。 这就是为什么我们使用非对称加密的原因。

非对称加密 (Asymmetric Encryption)

Asymmetric Encryption uses two keys for the data (a private and a public key). Here the public keys are used on each individual (vulnerable) device and serve only to encrypt the data. Once encrypted these cannot be used to decrypt it. The private key, however, is one which is only supplied to the owner and is what is used to read the encrypted data. It is also possible to encrypt data with the private key, such that it is only read using the public key, but this is bad practice and causes more problems than it solves.

非对称加密对数据使用两个密钥(私有密钥和公共密钥)。 此处,公钥用于每个单独的(易受攻击的)设备,并且仅用于加密数据。 一旦加密, 就不能用于解密。 但是,私钥是仅提供给所有者的密钥,用于读取加密数据。 也可以使用私钥加密数据,这样只能使用公钥读取数据,但这是一种不好的做法,并且会导致更多的问题而不是解决的。

密码学-python软件包 (Cryptography — the python package)

The python package which we shall be using is called cryptography and can be installed using pip install cryptography.

我们将使用的python软件包称为cryptography ,可以使用pip install cryptography

密钥生成 (Key Generation)

We begin by importing the required packages:

我们首先导入所需的软件包:

import cryptographyfrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives.asymmetric import rsafrom cryptography.hazmat.primitives import serialization

Next, we generate public and private keys. These have two arguments — the public exponent and the key size. The public exponent is a positive prime number (usually 65537) and the key size is the length of the modulus in bits (For keys in 2015 it is recommended that these are >2048 bits)

接下来,我们生成公钥和私钥。 这些有两个参数-公共指数和密钥大小。 公共指数是一个正质数(通常为65537 ),密钥大小是模数的长度(以位为单位)(对于2015年的密钥,建议这些值>2048位)

private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()

保存生成的密钥 (Saving the generated keys)

To save the generated keys we must first serialise them, and then write them to file:

要保存生成的密钥,我们必须首先序列化它们,然后将它们写入文件:

# private key
serial_private = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
with open('private_noshare.pem', 'wb') as f: f.write(serial_private)
# public key
serial_pub = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_shared.pem', 'wb') as f: f.write(serial_pub)

读取加密密钥 (Reading the encryption keys)

# make sure the following are imported
# from cryptography.hazmat.backends import default_backend
# from cryptography.hazmat.primitives import serialization######### Private device only ##########
def read_private (filename = "private_noshare.pem):
with open(filename, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
return private_key
######### Public (shared) device only ##########
def read_public (filename = "public_shared.pem"):
with open("public_shared.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
return public_key

加密 (Encryption)

To store some sensitive information (for instance a persons weight) we can encrypt it using the following:

要存储一些敏感信息(例如人的体重),我们可以使用以下方法对其进行加密:

# make sure the following are imported
# from cryptography.hazmat.primitives import hashes
# from cryptography.hazmat.primitives.asymmetric import padding######### Public (shared) device only #########data = [b'My secret weight', b'My secret id']
public_key = read_public()open('test.txt', "wb").close() # clear file
for encode in data:
encrypted = public_key.encrypt(
encode,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
with open('test.txt', "ab") as f: f.write(encrypted)

解密方式 (Decryption)

As each data section is encoded within the same number of bytes, it is possible to read the file in chunks. This allows us to read and decode each chunk, recreating the original dataset.

由于每个数据段均以相同数量的字节编码,因此可以分块读取文件。 这使我们能够读取和解码每个块,从而重新创建原始数据集。

# make sure the following are imported
# from cryptography.hazmat.primitives import hashes
# from cryptography.hazmat.primitives.asymmetric import padding######### Private device only ##########read_data = []
private_key = read_private()with open('test.txt', "rb") as f:
for encrypted in f:
read_data.append(
private_key.decrypt(
encrypted,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)))# >>> read_data = [b'My secret weight', b'My secret id']

结论 (Conclusion)

So there you have it, an easy way to encrypt data (in memory), for public-facing devices, such that you need a separate key to decode it again externally.

这样就为面向公众的设备提供了一种(在内存中)加密数据的简便方法,因此您需要一个单独的密钥才能在外部再次对其进行解码。

翻译自: https://towardsdatascience.com/asymmetric-encrypting-of-sensitive-data-in-memory-python-e20fdebc521c

python非对称加密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值