encryptText method

String encryptText(
  1. String plainText
)

Encrypts the provided plainText using AES-256-CBC with PKCS7 padding.

A new, secure random IV is generated for each encryption. The output is a concatenated hexadecimal string: <cipherTextHex><ivHex>.

Example:

final encrypted = manager.encryptText('Hello World');

Returns the encrypted string in hex format with the IV appended.

Implementation

String encryptText(String plainText) {
  // Derive a 256-bit AES key using PBKDF2
  final key = encrypt.Key(crypto.deriveKey());

  // Generate a secure random IV of desired length (default: 16 bytes)
  final iv = encrypt.IV.fromSecureRandom(crypto.ivLength);

  // Create AES encrypter with CBC mode and PKCS7 padding
  final encryptor = encrypt.Encrypter(
    encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7'),
  );

  // Encrypt the plaintext using the generated IV
  final encrypted = encryptor.encrypt(plainText, iv: iv);

  // Convert ciphertext and IV to hexadecimal strings
  final encryptedHex = crypto.bytesToHex(encrypted.bytes);
  final ivHex = crypto.bytesToHex(iv.bytes);

  // Return the combined hex string: encrypted data + IV
  return encryptedHex + ivHex;
}