Skip to content
Advertisement

Sending RSA encoded message from JavaScript React to Python. Ciphertext length must be equal to key size. issue

I receive the error “Ciphertext length must be equal to key size.” when trying to send an encoded message from javascript to python. I have encoded the bytesarray to base64 in javascript and decoded the base64 back to a bytes array in Python. Yet, the issue seems to persist.

Key Generation (Python):

JavaScript

Import Key (Javascript):

JavaScript

Encrypt Data (Javascript):

JavaScript

Transmit Data (Javascript):

JavaScript

Receive and decode data (Python):

JavaScript

Advertisement

Answer

encrypt() returns the ciphertext as an ArrayBuffer. However, btoa() requires a binary string. Therefore the ArrayBuffer must be converted to a binary string first (see ab2b64() below). With this fix a valid ciphertext is produced:

JavaScript
JavaScript

Test:

The resulting ciphertext can be decrypted with Python:

JavaScript

A note about the encoding of the plaintext: Keep in mind that str2ab(msg) in encrypt() requires a string for msg where charCodeAt() returns a value less than 256, i.e. a single byte, for each character.
For the plaintext in the above example, this is satisfied. For arbitrary plaintexts, however, this is usually not true (e.g. € (U+20AC) equals 2 bytes). Therefore, to support arbitrary plaintexts, UTF-8 encoding should be used, e.g. new TextEncoder().encode(msg) instead of str2ab(msg).
For str2ab(binaryDerString) in importRsaKey() this is not critical, since binaryDerString is a binary string where each character corresponds to a single byte.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement