S
S
Someone01102021-08-18 18:49:20
Python
Someone0110, 2021-08-18 18:49:20

How to write an RSA decoder?

Hello, I wanted to try to write a function that encrypts a file .... But not without errors :( There is a main.py file, it contains the following:

import rsa
( public, private ) = rsa.newkeys(512)
name = input("Enter filename: ")

file = open(name, "rb")
r = file.read() #считываю данные,что бы зашифровать
file.close()

crypt = rsa.encrypt(r, public )

file = open(name, "wb")
file.write(crypt)
file.close()

file = open("public.txt", "w")
file.write(str(public))
file.close()

file = open("private.txt", "w")
file.write(str(private))
file.close()

The file was successfully encrypted, but how to write a decryptor? Given that the keys are stored in separate files.
I tried to write it myself, here is the code itself:
The decryptor file is called decrypt.py
import rsa

name = input("Enter filename: ")
key = input("Enter key: ")

file = open(name, "rb")
r = file.read()
file.close()

file2 = open(key, "rb")
r2 = file2.read()
file2.close()

msg = rsa.decypt(r, r2)

file3 = open(name, "w")
file3.write(str(msg))
file3.close()

But this error comes up:
Enter filename: text.txt
Enter key: private.txt
Trace back ( most recent call last ):
    File "C:\Users\root\Desktop\Main\Python\decrypt.py", 
       line 14, in <module>
    msg = rsa.decrypt(r, r2 )
    File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rsa\pkcs1.py", line 247, in decrypt
    block size = common.byte_size(priv_key.n)
AttributeError: 'str' object has no attribute 'n'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Developer, 2021-08-18
@samodum

msg = rsa.decrypt(r, r2 )
File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rsa\pkcs1.py", line 247, in decrypt
block size = common.byte_size(priv_key.n)
AttributeError: 'str' object has no attribute 'n'

This error indicates that the file format with the private key is incorrect. A PKCS standard format (some PEM) is expected so that the "n" field can be obtained. But since this is a different format, it does not find this field.
It is necessary to convert key files to another format, or write another decoder

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question