sharp_c-tudent sharp_c-tudent - 1 month ago 7
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
m.encode(encoding='UTF-8',errors='strict')
bits = len(m)*4*8


EDIT:

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(
ciphertextD,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
message= str(message)
message.encode(encoding='UTF-8',errors='strict')
return message

Answer

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