python实现非对称加密算法_使用Python进行非对称加密

在本文中,我们将为非对称密码实现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(

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值