在本文中,我们将为非对称密码实现Python实现,也称为公钥密码。讨论的算法将是使用公钥和私钥对进行RSA加密和解密以及ECC密钥交换。本文本身并没有解释上述算法,而是使用各种Python库为这些算法提供了Python实现。该Github存储库中将提供本文中使用的所有代码。
RSA(Rivest-Shamir-Adleman)
RSA是包含两个密钥的公共密钥加密,一个是公开密钥,可用于Internet上的所有用户,另一个是私有密钥,只有授权人员才能使用。RSA已用于加密/解密,数字签名,密钥交换。在这里,我们将实现基于RSA的加密和解密。此外,我们将生成公钥和私钥,并将它们存储在单独的文件中,然后再从这些文件导入以进行加密和解密。
我们需要安装一个名为“ PyCryptodome”的Python包才能使用RSA。
pip3 install pycryptodome
让我们看看RSA导入必要的模块
#RSA_cryptography.py
#Importing necessary modules
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from binascii import hexlify
#The message to be encrypted
message = b'Public and Private keys encryption'
#Generating private key (RsaKey object) of key length of 1024 bits
private_key = RSA.generate(1024)
#Generating the public key (RsaKey object) from the private key
public_key = private_key.publickey()
print(type(private_key), type(public_key))
#Converting the RsaKey objects to string
private_pem = private_key.export_key().decode()
public_pem = public_key.export_key().decode()
print(type(private_pem), type(public_pem))
#Writing down the private and public keys to 'pem' files
with open('private_pem.pem', 'w') as pr:
pr.write(private_pem)
with open('public_pem.pem', 'w') as pu:
pu.write(public_pem)
#Importing keys from files, converting it into the RsaKey object
pr_key = RSA.import_key(open('private_pem.pem', 'r').read())
pu_key = RSA.import_key(open('public_pem.pem', 'r').read())
print(type(pr_key), type(pu_key))
#Instantiating PKCS1_OAEP object with the public key for encryption
cipher = PKCS1_OAEP.new(key=pu_key)
#Encrypting the message with the PKCS1_OAEP object
cipher_text = cipher.encrypt(message)
print(cipher_text)
#Instantiating PKCS1_OAEP object with the private key for decryption
decrypt = PKCS1_OAEP.new(