Python3 RSA publickKey加密

2024-07-03 06:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个公钥可以使用,我需要用我得到的RSA公钥对一些文本进行加密

这是我目前掌握的代码:

import rsa

fKey = open('key','r')
publicKey = fKey.read()

cipher = rsa.encrypt('Test', publicKey)
print(cipher)

使用此代码,我不断收到以下错误:

Traceback (most recent call last):
  File "login.py", line 30, in <module>
    cipher = rsa.encrypt('Test', publicKey)
  File "/home/vagrant/.local/lib/python3.8/site-packages/rsa/pkcs1.py", line 169, in encrypt
    keylength = common.byte_size(pub_key.n)
AttributeError: 'str' object has no attribute 'n'

有人能给我指一下正确的方向吗

注意:我必须使用该公钥文件


Tags: key代码inpytest文本linersa
1条回答
网友
1楼 · 发布于 2024-07-03 06:18:22

我就是这样解决的

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from base64 import b64decode,b64encode

pubkey = open('key','r').read()
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)

相关问题 更多 >