I am currently working on my first Flutter project and I would like to explain the situation first:
I am writing a Python Api using Flask which creates an RSA key pair as follows and stores them into files:
def generate_rsa_key_pair(self): key = RSA.generate(2048) private_key = key.export_key() file_out = open("private.pem", "wb") file_out.write(private_key) file_out.close() public_key = key.publickey().export_key() file_out = open("public.pem", "wb") file_out.write(public_key) file_out.close()The client, my Flutter app, now requests the public key to encrypt its messages with. This public key is then transmitted as follows:
public_key = RSA.import_key(open("public.pem").read()) keys["publicKey"] = public_key.exportKey("PEM").decode("utf-8")The public key that is stored in the file is also the same as the one in my Flutter app. I have already been able to verify this.
Now I want to encrypt a message in Flutter using RSA as follows. The public key is stored in the variable publicEncryptionKey:
import 'package:encrypt/encrypt.dart' as enc; String asymmetricEncrypt(String message) { enc.Encrypter encrypter = enc.Encrypter(enc.RSA(publicKey: publicEncryptionKey, encoding: enc.RSAEncoding.OAEP)); enc.Encrypted msg = encrypter.encrypt(message); return msg.base64; }I send the encrypted message back to my backend and now want to decrypt it with the private key. I do this as follows:
from Crypto.Cipher import PKCS1_OAEP @app.route('/add-element-enc', methods=['POST']) def add_element_enc(): values = request.get_json() if 'message' not in values: return "", 400 value1 = values['message'] private_key = RSA.import_key(open("private.pem", "rb").read()) decrypter = PKCS1_OAEP.new(private_key) new_value = bytes(value1, 'utf-8') msg = decrypter.decrypt(new_value) return "", 201
My problem now is that decrypting does not work on my python backend and I get the following error when I try to decrypt the message:
ValueError: Ciphertext with incorrect length.
I'm getting worn out because I can't get it done. Is there anyone who already had a similar problem?
PKCS1_OAEPcipher. In Dart, you useRSAEncoding.OAEP, but Dart also hasRSAEncoding.PKCS... have you tried using that instead?add_element_enc()the Base64 decoding of the ciphertext is missing (instead of the Utf-8 encoding). Furthermoremsgis not returned.