📜  RSA密码加密

📅  最后修改于: 2020-11-08 08:38:30             🧑  作者: Mango


在本章中,我们将重点介绍RSA密码加密的不同实现及其涉及的功能。您可以引用或包含此Python文件以实现RSA密码算法实现。

加密算法包含的模块如下-

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

为了更好的安全性,我们将哈希值初始化为SHA-256。我们将使用以下代码使用一个函数来生成新密钥或一对公钥和私钥。

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private
def importKey(externKey):
   return RSA.importKey(externKey)

对于加密,使用以下函数,该函数遵循RSA算法-

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

两个参数是必需的: messagepub_key ,它指的是公钥。公钥用于加密,私钥用于解密。

下面提到了完整的加密程序程序-

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private

def importKey(externKey):
   return RSA.importKey(externKey)

def getpublickey(priv_key):
   return priv_key.publickey()

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)