Search code examples
pythonrsapycryptodome

ValueError: Ciphertext with incorrect length


I have a problem that reads: "Suppose your RSA public-key factors are p = 6323 and q = 2833, and the public exponent e is 31. Suppose you were sent the Ciphertext 6627708. Write a program that takes the above parameters as input and implements the RSA Decryption function to recover the plaintext."

When trying to get the ciphertext decrypted I recieve the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-bb484f24f99a> in <module>
----> 1 cipher.decrypt((str(ciphertext)))

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/Crypto/Cipher/PKCS1_OAEP.py in decrypt(self, ciphertext)
    165         # Step 1b and 1c
    166         if len(ciphertext) != k or k<hLen+2:
--> 167             raise ValueError("Ciphertext with incorrect length.")
    168         # Step 2a (O2SIP)
    169         ct_int = bytes_to_long(ciphertext)

ValueError: Ciphertext with incorrect length.

My code currently looks like:

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

n = 17913059
e = 31
p = 6323
q = 2833
d = 13861087
ciphertext = 6627708

key = RSA.construct(rsa_components=(n,e,d,p,q))
cipher = PKCS1_OAEP.new(key)

cipher.decrypt((str(ciphertext)))

I was wondering more so if I am on the right track, or completely going off the rails. I am not too sure how to fix the length error. I was thinking maybe I need to pad like in AES, but I am not too sure. Thanks in advance for the help!


Solution

  • If you have c, d, and n, you can use the RSA formula to get the ciphertext:

    >>> pow(ciphertext, d, n)
    205
    

    This seems like a misformed message (they're usually hex or ASCII values) so this might be just an example problem.

    Your issue stems from pycryptodome's implementation of RFC 7.1.2, which states:

    C: ciphertext to be decrypted, an octet string of length k, where k = 2hLen + 2

    where:

    hLen denotes the length in octets of the hash function output

    So, technically your ciphertext is too short to be decrypted by RSA.