encrypt method

Uint8List encrypt(
  1. String data,
  2. String publicXml
)

Implementation

Uint8List encrypt(String data, String publicXml) {
  // Convert the data to bytes
  Uint8List dataBytes = Uint8List.fromList(utf8.encode(data));
  //print('Raw data bytes: ${dataBytes}'); // Log the raw data bytes

  // Decode the Base64-encoded public XML
  String decodedString = utf8.decode(base64.decode(publicXml));
  String modulusString = getXmlComponent(decodedString, "Modulus");
  String exponentString = getXmlComponent(decodedString, "Exponent");

  // Convert Base64 strings to byte arrays
  Uint8List modulusBytes = base64.decode(modulusString);
  Uint8List exponentBytes = base64.decode(exponentString);

  // Log modulus and exponent bytes
  //print('Modulus bytes: $modulusBytes');
  //print('Exponent bytes: $exponentBytes');

  // Convert the byte arrays to BigInt
  BigInt modulus = BigInt.parse(_bytesToHex(modulusBytes), radix: 16);
  BigInt exponent = BigInt.parse(_bytesToHex(exponentBytes), radix: 16);

  // Create the public key using RSAPublicKey
  RSAPublicKey publicKey = RSAPublicKey(modulus, exponent);

  // Prepare data with PKCS#1 v1.5 padding
  Uint8List paddedData = _padPKCS1v15(dataBytes, modulus.bitLength ~/ 8);
  //print('Padded data: $paddedData'); // Log the padded data

  // Initialize the RSA engine for encryption
  RSAEngine rsaEngine = RSAEngine()
    ..init(true, PublicKeyParameter<RSAPublicKey>(publicKey));

  // Encrypt the padded data
  Uint8List encryptedBytes = rsaEngine.process(paddedData);
  return encryptedBytes;
}