deriveKey method
Derives a cryptographic key using PBKDF2 with HMAC-SHA256.
This method manually performs key derivation using the provided password and salt. It produces a consistent 256-bit key (32 bytes) based on the number of iterations configured.
Returns a Uint8List containing the derived key.
Implementation
Uint8List deriveKey() {
final saltBytes = utf8.encode(salt);
final hmac = Hmac(sha256, utf8.encode(password));
// Initialize the derived key buffer
var derivedKey = List<int>.filled(keyLength, 0);
// Initial block index (big-endian format)
var blockIndex = 1;
// First hash (U1)
var u = hmac.convert([...saltBytes, 0, 0, 0, blockIndex]).bytes;
// Copy U1 into derived key
for (int i = 0; i < u.length; i++) {
derivedKey[i] = u[i];
}
// XOR with each subsequent hash iteration (U2, U3, ...)
for (int i = 1; i < iterations; i++) {
u = hmac.convert(u).bytes;
for (int j = 0; j < u.length; j++) {
derivedKey[j] ^= u[j];
}
}
return Uint8List.fromList(derivedKey);
}