sharp_c-tudent sharp_c-tudent - 4 months ago 35
Python Question

python cryptography library - ValueError: Ciphertext length must be equal to key size

I'm implementing the RSA algorithm using python's library cryptography, however I have come to a halt when the following exception was raised:

ValueError: Ciphertext length must be equal to key size.

From what I gathered this seems to be a restriction of the library itself, not something usual on other libraries implementation.

This exception is raised when I try to decrypt a previously crypted message but what can I do to avoid it? When I create the public and private keys I can't know the length of the cyphertext (crypted message) I will get later on... Do I really have control over this?

I think the problem is in the creation of the keys, I have been trying to give the same amount of bits on the original decrypted message as an argument to create the keys with that same ammount of bits but it's still raising the same exception...

I have been using this to find out the number of bits on the original message, maybe I'm doing it wrong...?

m = message
bits = len(m)*4*8


My code is very long because it has other things too, but I can put some key points

privateKeySender , publicKeySender = generateKeys(bits)
privatekeyReceptor, publickeyReceptor = generateKeys(bits)

ciphertext = myencrypt(publickeyReceptor , message)
signature = sign(ciphertext, publickeyReceptor )
decryptMessage = mydecrypt(ciphertext, privatekeyReceptor)
validation = validateSignature(message,signature, publicKeySender)

the exception is thrown on the decrypt method

def mydecrypt(ciphertext, privateKey):
ciphertextD = base64.b64decode(ciphertext) if not isinstance(ciphertext, bytes) else ciphertext

message= privateKey.decrypt(
message= str(message)
return message


The problem was on the encoding of the ciphertext, it was not encoded right on the encrypt method.