简体   繁体   English

在python中使用用户定义的密钥进行RSA加密

[英]RSA Encryption using the user-defined keys in python

I am trying to encrypt a small amount of data using RSA algorithm using python.我正在尝试使用 python 使用 RSA 算法加密少量数据。 The problem is I have the public and private RSA key.问题是我有公共和私人 RSA 密钥。 Both are stored in .pem and .ppk respectively.两者都分别存储在 .pem 和 .ppk 中。 I am not able to find any help in google which will help me encrypt it using my keys.我无法在 google 中找到任何帮助我使用我的密钥对其进行加密的帮助。 All the code and examples I saw generates its own keys.我看到的所有代码和示例都会生成自己的密钥。 Is there a way where I can use my own keys to encrypt and decrypt the data?有没有办法可以使用我自己的密钥来加密和解密数据?

You can use the rsa module .您可以使用 rsa 模块。

import rsa
with open('public.ppm','r') as  key_pub_file:
     key_pub = key_pub_file.read()
     message = "hello".encode('utf8')
     enc_msg = rsa.encrypt(message, key_pub)
     print(enc_msg)
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from base64 import b64decode,b64encode
f1 = open('public.ppm','r')
pubkey = f1.read() 
#pubkey = 'MIGfMA0GCSqGSIb3DQEBA3UAWE0HSQ77CwP/8UbX07W2XKwng/nMT1R7vaz+2EeNR/FitFXwIDAQAB'
msg = "test"
keyDER = b64decode(pubkey)
keyPub = RSA.importKey(keyDER)
cipher = Cipher_PKCS1_v1_5.new(keyPub)
cipher_text = cipher.encrypt(msg.encode())
emsg = b64encode(cipher_text)
print(emsg)

While trying, I found this code to be working.在尝试时,我发现此代码有效。 msg variable contains the data to be encrypted and pubkey contains the public key which ill be taking from ppm file. msg 变量包含要加密的数据,pubkey 包含将从 ppm 文件中获取的公钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM