toSafe method
Encrypts the string using AES encryption with a provided password.
This method uses AES encryption in CBC mode. The password is adjusted to be exactly 32 bytes long, with the first 16 bytes used as the initialization vector (IV).
Example:
var originalText = 'Hello World';
var encrypted = originalText.toSafe('your-password-here');
print(encrypted); // Outputs encrypted base64 string
password
The password used for encryption. It is truncated or padded to 32 bytes.
Returns the encrypted string encoded in base64.
Implementation
String toSafe(String password) {
try {
if (password.length > 32) {
password = password.substring(0, 32);
} else if (password.length < 32) {
while (password.length != 32) {
password += '-';
}
}
var key = Key.fromUtf8(password);
password = password.substring(0, 16);
final iv = IV.fromUtf8(password);
final e = Encrypter(AES(key, mode: AESMode.cbc));
final encryptedData = e.encrypt(this, iv: iv);
return encryptedData.base64;
} catch (e) {
return '';
}
}