Mateo Gutierrez
Mateo Gutierrez

Reputation: 47

Python3 RSA publickKey encryption

I got a public key to work with and I need to cipher some text with the public RSA key I got.

This is the code I have so far:

import rsa

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

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

With this code I keep getting this error:

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'

Can someone please point me in the right direction?

Note: I must use that public key file

Upvotes: 0

Views: 2761

Answers (2)

jinn
jinn

Reputation: 1

Have you tried:

fKey = open('key','rb')
publicKey = rsa.PublicKey.load_pkcs1(fKey.read())

Upvotes: 0

Mateo Gutierrez
Mateo Gutierrez

Reputation: 47

This is how I solved it.

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)

Upvotes: 1

Related Questions