decryptFile method
Decrypt a file content The function takes ciphertext in an encrypted file, decrypt them using the key, and store the plaintext in the same file
Implementation
Future<void> decryptFile(String filePath, String fileName) async {
/// Encrypted file URL
//String encFileUrl = webId.replaceAll('profile/card#me', filePath + '/' + fileName);
/// Get ciphertext file content
String encFilePath = filePath + '/' + fileName;
String fileContent = await fetchFile(encFilePath);
EncProfile encFile = EncProfile(fileContent.toString());
String encFileCont = encFile.getEncFileCont();
String encIvVal = encFile.getEncIvVal();
/// Get encryption key that is stored in the local storage
String encKey = appStorage.getItem('encKey');
/// Decrypt the ciphertext
String plainFileCont = decryptVal(encKey, encFileCont, encIvVal);
/// Get the list of locations of files that are encrypted
var keyInfo = await fetchFile(encKeyFileLoc);
EncProfile keyFile = EncProfile(keyInfo.toString());
String encFileHash = keyFile.getEncFileHash();
String encFileIvVal = keyFile.getEncIvVal();
String encFilePlaintext = decryptVal(encKey, encFileHash, encFileIvVal);
List encFileList = jsonDecode(encFilePlaintext);
/// Delete the encrypted file
String delResponse = await deleteItem(true, encFilePath);
/// Create new file with plaintext content
String fileCreateRes =
await createItem(true, fileName, plainFileCont, fileLoc: filePath);
/// Update the list of encrypted files
encFileList.remove(encFilePath);
String newFileListStr = jsonEncode(encFileList);
String encKeyFileUrl = webId.replaceAll('profile/card#me', encKeyFileLoc);
List fileListEncRes = encryptVal(encKey, newFileListStr);
String fileListStrEnc = fileListEncRes[0];
String fileListIv = fileListEncRes[1];
// Update encrypted value
String dPopToken =
genDpopToken(encKeyFileUrl, rsaKeyPair, publicKeyJwk, 'PATCH');
String updateQuery = genSparqlQuery(
'UPDATE', '', encFilePred, fileListStrEnc,
prevObject: encFileHash);
String updateResponse =
await runQuery(encKeyFileUrl, dPopToken, updateQuery);
// Update IV value
String dPopTokenIv =
genDpopToken(encKeyFileUrl, rsaKeyPair, publicKeyJwk, 'PATCH');
String updateQueryIv = genSparqlQuery('UPDATE', '', ivValPred, fileListIv,
prevObject: encFileIvVal);
String updateResponseIv =
await runQuery(encKeyFileUrl, dPopTokenIv, updateQueryIv);
if (delResponse != 'ok' ||
fileCreateRes != 'ok' ||
updateResponse != 'ok' ||
updateResponseIv != 'ok') {
throw Exception('Failed to revoke encrypted file $encFilePath.');
}
}