You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cloudsolutions-atoms/lib/new_views/pages/AesHelper.dart

43 lines
1.5 KiB
Dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
class AesHelper {
static String secretKey = "BRIL7VWSHDSY5G2SEVTI4SNAUEE66B3E";
static Uint8List _deriveKey(String key) {
final keyBytes = utf8.encode(key);
final hash = sha256.convert(keyBytes);
return Uint8List.fromList(hash.bytes); // 32 bytes
}
static String encryptText(String plainText) {
if (plainText.isEmpty) {
throw ArgumentError('plainText cannot be null or empty');
}
final keyBytes = _deriveKey(secretKey);
final key = encrypt.Key(keyBytes);
final iv = encrypt.IV.fromSecureRandom(16);
final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7'));
final encrypted = encrypter.encryptBytes(utf8.encode(plainText), iv: iv);
final combined = Uint8List.fromList(iv.bytes + encrypted.bytes);
return base64.encode(combined);
}
static String decryptText(String cipherTextBase64) {
final keyBytes = _deriveKey(secretKey);
final key = encrypt.Key(keyBytes);
final fullBytes = base64.decode(cipherTextBase64);
final ivBytes = fullBytes.sublist(0, 16);
final cipherBytes = fullBytes.sublist(16);
final iv = encrypt.IV(Uint8List.fromList(ivBytes));
final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7'));
final decrypted = encrypter.decryptBytes(encrypt.Encrypted(Uint8List.fromList(cipherBytes)), iv: iv);
return utf8.decode(decrypted);
}
}