extractEncryptedResponse function
Extracts encrypted components from a server response.
This function processes a response map and extracts the encrypted key, encrypted data, and initialization vector (IV) from the specified key.
response
: The response map to extract data from.topLevelKey
: The top-level key in the response containing encrypted data (default is'en'
).dataKeyName
: The key name for the encrypted key inside the top-level key (default is'encryptedKey'
).hasTopLevelKey
: Specifies if the encrypted data is nested under a top-level key (default istrue
).separator
: The separator used to split the encrypted key into parts (default is'$aA'
).
Returns an Encryptionextraction object containing the extracted components.
Throws:
FormatException
: If the response structure is invalid, keys are missing, or theencryptedKey
format is incorrect.Exception
: For other unexpected errors during extraction.
Implementation
Encryptionextraction extractEncryptedResponse(
Map<String, dynamic> response, {
String topLevelKey = 'en',
String dataKeyName = 'encryptedKey',
bool hasTopLevelKey = true,
String separator = '\$aA',
}) {
try {
String? ek;
if (hasTopLevelKey) {
if (response[topLevelKey] is! Map ||
response[topLevelKey][dataKeyName] == null) {
throw FormatException(
"Invalid response: '$topLevelKey' or '$dataKeyName' key not found.");
}
ek = response[topLevelKey][dataKeyName] as String?;
} else {
ek = response[dataKeyName] as String?;
}
if (ek == null || ek.isEmpty) {
throw FormatException(
"Invalid response: '$dataKeyName' is missing or empty.");
}
final parts = ek.split(separator);
if (parts.length != 3) {
throw FormatException(
"Invalid encryptedKey format. Expected 3 parts separated by '$separator', but got ${parts.length} parts.");
}
return Encryptionextraction(
encryptedKey: parts[0],
encryptedData: parts[1],
iv: parts[2],
);
} catch (e) {
throw Exception("Failed to extract encryption data: $e");
}
}