'Getting errors while trying to decode string with rsa and base64
I'm trying to make a password manager with Python and encrypting the passwords with RSA. that part went smoothly. What's not going smoothly is the decryption. This is the code for the encryption
def encode(message_to_send):
b_message = message_to_send.encode()
encrypted = rsa.encrypt(b_message, publicKey)
encrypted_b64 = base64.b64encode(encrypted)
encrypted_b64_string = encrypted_b64.decode()
return(encrypted_b64_string)
I've saved the passwords in a text file and I'm taking them from the text file using this chunk of code
if os.path.isfile('passwords.txt'):
with open('passwords.txt', 'r') as f:
tempPass = f.read()
tempPass = tempPass.split(',')
passwords = [x for x in tempPass if x.strip()]
for app in passwords:
print(decode(app))
and then decrypting it with this function called decode()
def decode(message_to_recieve):
encrypted_b64 = message_to_recieve.encode()
encrypted = base64.b64decode(encrypted_b64)
b_final_message = rsa.decrypt(encrypted, privateKey)
final_message = b_final_message.decode()
return (final_message)
which is returning this error
File "/passmanager/main.py", line 64, in <module>
print(decode(app))
File "/passmanager/main.py", line 53, in decode
b_final_message = rsa.decrypt(encrypted, privateKey)
File "/home/horia/.local/lib/python3.10/site-packages/rsa/pkcs1.py", line 281, in decrypt
raise DecryptionError("Decryption failed")
rsa.pkcs1.DecryptionError: Decryption failed
Also the publicKey and privateKey are just
publicKey, privateKey = rsa.newKeys(512)
Solution 1:[1]
Recently I faced same issue, while doing so, I been found that, the problem is neither related to encrypting or decrypting functions nor with saving the message in encrypted form.
It is the problem of this part publicKey, privateKey = rsa.newKeys(512)
,
acutely the decrypting and encrypting part of rsa, will only work in your case, when both executes in one run instance or when you don't had to redefine publicKey, privateKey = rsa.newKeys(512)
this code block, since you are not saving the keys
In your case your taking an input message from user and saving it, into a text file in encrypted form, and trying to access it later.
Just encrypt, encode and save it into text file, then extract it from text file, decode and decrypt it, all in single execution of you entire program.
You can test your full code, with these suggestion it will work. Both encrypting & decrypting functions will execute successfully.
For example:
import rsa
from base64 import b64encode, b64decode
import pandas as pd
key = int(input("\nenter the key value : ")) #512
(publicKey, privateKey) = rsa.newkeys(key)
#or
#(publicKey, privateKey) = rsa.newkeys(512)
while True:
option = int(input('\n[1] to add data \n[2] to see data : '))
if option == 1:
paasword = input("\nenter password, to save : ")
print("\noriginal string: ", paasword)
# Encrypt the raw password
encpass = rsa.encrypt(paasword.encode(),publicKey)
print("\nencrypted string: ", encpass)
# Encode encrypted password to base64 and produce UTF-8 conform string
b64_enc_pass = b64encode(encpass).decode()
print("\nencoded string: ", b64_enc_pass)
# Save to CSV file
data={'Password':[b64_enc_pass], } # dict
df = pd.DataFrame(data) # create pandas DataFrame
df.to_csv('my_data.csv') # write a csv file
print('\nsaved successfully')
print('\n============================================================================\n')
if option == 2:
# Extract form CSV file
df = pd.read_csv("my_data.csv") #using 0th column (Name) as index
find_password = df['Password'][0] #column id , index of that row;
print("\nencoded string: ", find_password)
# Decode encrypted password from UTF-8 encoded string
find_password = b64decode(find_password.encode())
print("\nencrypted string: ", find_password)
# Decrypt the decode password string
decpass = rsa.decrypt(find_password, privateKey).decode()
print("\ndecrypted string: ", decpass)
print('\npassword: ', decpass) #decrypted form
print('\ndecrypted successfully')
print('\n============================================================================\n')
> enter the key value : 512
> [1] to add data
> [2] to see data : 1
> enter password, to save : password123
> original string: password123
> encrypted string: b'\x90oj\x83b{wp\xc1\x90\x8f\xcfE\xdf\x..............................................................'
> encoded string: kG9qg2J7d3DBkI/PRd+hLdC1mmeo....................................
> saved successfully
============================================================================
> [1] to add data
> [2] to see data : 2
> encoded string: kG9qg2J7d3DBkI/PRd+hLdC1mmeo........................................................
> encrypted string: b'\x90oj\x83b{wp\xc1\x90\x8f\xcfE\xdf\x........................................................'
> decrypted string: password123
> password: password123
> decrypted successfully
============================================================================
Here, I save and extract the password in single execution.
> enter the key value : 512
> [1] to add data
> [2] to see data : 2
> encoded string: kG9qg2J7d3DBkI/PRd+hLdC1mmeoJ.......................................
> encrypted string: b'\x90oj\x83b{wp\xc1\x90\x8f\xcfE\xdf\xa1.....................................................................'
> Error: DecryptionError: Decryption failed
I saved the password in above run instance of the program & here I'm trying to see/extract the decrypt form of same password, but i face error.
However, this doesn't satisfy your need, the password manager program is designed in a way in which you have to save the input password & access it later.
The rsa
is an asymmetric algorithm that uses a publicly known key for encryption, but requires a private key, known only to the intended recipient, for decryption.
For more on this : https://youtu.be/txz8wYLITGk
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |