首页 > 解决方案 > 用 Python 实现 RSA 密码函数

问题描述

我在一个 python 文件中获得了这段代码,其中包含有关如何对用户输入的样本数据实施 RSA 加密技术的方法和导入。问题是加密方法以public密钥为参数,而解密方法以private 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)
msg=input("Enter the message you would like to encrypt?")
##create a public key for encryption
enkey=newkeys(10)
##encrypt the message with a public key
encrypt(msg,enkey)
##get a decipher variable
cipher=encrypt(msg,enkey)
##try to decrypt
##the problem is here, how do i get the private key from the sole newkeys method to decrypt with
decrypt(msg,dekey)
decrypt(cipher,

我也不确定使用的密钥encryption是私有的还是公共的,因为方法返回public, private。感谢您的帮助

标签: pythonencryptionrsa

解决方案


推荐阅读