Reuben
Reuben

Reputation: 5736

Python RSA encryption with PKCS1_OAEP/PKCS1_v1_5 fails to decrypt special characters

I am using the following code to encrypt/decrypt only passwords. It works perfectly fine except special characters. As an example Pa$$w0rd returns Pa1705w0rd . Any idea how to fix it ? By the way, I have also tried PKCS1_v1_5, but same result !

def _encrypt(self, message):
    public_key = RSA.importKey(self._get_public_key())
    cipher = PKCS1_OAEP.new(public_key)
    encrypted_message = cipher.encrypt(message)
    print(base64.b64encode(encrypted_message))

def _decrypt(self, encoded_encrypted_message):
    encrypted_message = base64.b64decode(encoded_encrypted_message)
    private_key = RSA.importKey(self._get_private_key())
    cipher = PKCS1_OAEP.new(private_key)
    print(cipher.decrypt(encrypted_message))

Upvotes: 0

Views: 5163

Answers (1)

user4925383
user4925383

Reputation:

It's hard for me to give a precise answer on what's exactly wrong, because I can't see entire program required to execute it. In particular I don't know if you pass message in as a bytes, and if so using what encoding.

However, here is working code:

import base64

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA


def get_rsa_private_key():
    return RSA.generate(2048)


def encrypt(plaintext, public_key):
    cipher = PKCS1_OAEP.new(public_key)
    ciphertext = cipher.encrypt(bytes(plaintext, encoding="UTF-8"))
    return base64.b64encode(ciphertext)


def decrypt(base64_encoded_ciphertext, private_key):
    ciphertext = base64.b64decode(base64_encoded_ciphertext)
    cipher = PKCS1_OAEP.new(private_key)
    return cipher.decrypt(ciphertext)


key = get_rsa_private_key()
ciphertext = encrypt("Pa$$w0rd", key.publickey())
print("Base64-encoded ciphertext: %s" % str(ciphertext, encoding="UTF-8"))
decrypted_plaintext = decrypt(ciphertext, key)
print("Decrypted plaintext: %s" % str(decrypted_plaintext, encoding="UTF-8"))

Output:

Base64-encoded ciphertext: hy7dhLj8Hy1n1cjcn20x+dWG/bOjXv3zFEd1T/cm4oJgDHFTviD8uexe2pG+lMmoP6qP+1uRwjgfMnGkpLhRwk1w5eN9bjphsm+ekC8B+qjfIG6TLjL0GEcJKTWf/dgNNBSbTWI2bNXREBbxkVWW+11vUfWsP5ni2exhZIMrf29B1z2FAyixdsHQ5KKlvfTGE4LFbrCTNn4qp2tsMTylitdafwYhsSIm5qlwIRU+qTB5bz8nTJHnPyksEIffHXbCJNjUwJJKRihrTZ+vY78XccTY7Bmkw5fmf3KuDRqXR/2LvjWwBtqqrMQRnmArer9Qh3uTmRNvvhUOYsh10172LQ==
Decrypted plaintext: Pa$$w0rd

Upvotes: 2

Related Questions