crypto_util.dart 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import 'dart:convert';
  2. import 'dart:typed_data';
  3. import 'dart:io' as io;
  4. import 'package:computer/computer.dart';
  5. import 'package:flutter_sodium/flutter_sodium.dart';
  6. import 'package:logging/logging.dart';
  7. import 'package:photos/models/encryption_result.dart';
  8. final int encryptionChunkSize = 4 * 1024 * 1024;
  9. final int decryptionChunkSize =
  10. encryptionChunkSize + Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
  11. Uint8List cryptoSecretboxEasy(Map<String, dynamic> args) {
  12. return Sodium.cryptoSecretboxEasy(args["source"], args["nonce"], args["key"]);
  13. }
  14. Uint8List cryptoSecretboxOpenEasy(Map<String, dynamic> args) {
  15. return Sodium.cryptoSecretboxOpenEasy(
  16. args["cipher"], args["nonce"], args["key"]);
  17. }
  18. Uint8List cryptoPwhashStr(Map<String, dynamic> args) {
  19. return Sodium.cryptoPwhashStr(
  20. args["input"], args["opsLimit"], args["memLimit"]);
  21. }
  22. bool cryptoPwhashStrVerify(Map<String, dynamic> args) {
  23. return Sodium.cryptoPwhashStrVerify(args["hash"], args["input"]) == 0;
  24. }
  25. EncryptionResult chachaEncryptFile(Map<String, dynamic> args) {
  26. final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
  27. final logger = Logger("ChaChaEncrypt");
  28. final sourceFile = io.File(args["sourceFilePath"]);
  29. final destinationFile = io.File(args["destinationFilePath"]);
  30. final sourceFileLength = sourceFile.lengthSync();
  31. logger.info("Encrypting file of size " + sourceFileLength.toString());
  32. final inputFile = sourceFile.openSync(mode: io.FileMode.read);
  33. final key = Sodium.cryptoSecretstreamXchacha20poly1305Keygen();
  34. final initPushResult =
  35. Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);
  36. var bytesRead = 0;
  37. var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
  38. while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
  39. var chunkSize = encryptionChunkSize;
  40. if (bytesRead + chunkSize >= sourceFileLength) {
  41. chunkSize = sourceFileLength - bytesRead;
  42. tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
  43. }
  44. final buffer = inputFile.readSync(chunkSize);
  45. bytesRead += chunkSize;
  46. final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
  47. initPushResult.state, buffer, null, tag);
  48. destinationFile.writeAsBytesSync(encryptedData, mode: io.FileMode.append);
  49. }
  50. inputFile.closeSync();
  51. logger.info("Encryption time: " +
  52. (DateTime.now().millisecondsSinceEpoch - encryptionStartTime).toString());
  53. return EncryptionResult(key: key, header: initPushResult.header);
  54. }
  55. void chachaDecrypt(Map<String, dynamic> args) {
  56. final logger = Logger("ChaChaDecrypt");
  57. final decryptionStartTime = DateTime.now().millisecondsSinceEpoch;
  58. final sourceFile = io.File(args["sourceFilePath"]);
  59. final destinationFile = io.File(args["destinationFilePath"]);
  60. final sourceFileLength = sourceFile.lengthSync();
  61. logger.info("Decrypting file of size " + sourceFileLength.toString());
  62. final inputFile = sourceFile.openSync(mode: io.FileMode.read);
  63. final pullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
  64. args["header"], args["key"]);
  65. var bytesRead = 0;
  66. var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
  67. while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
  68. var chunkSize = decryptionChunkSize;
  69. if (bytesRead + chunkSize >= sourceFileLength) {
  70. chunkSize = sourceFileLength - bytesRead;
  71. }
  72. final buffer = inputFile.readSync(chunkSize);
  73. bytesRead += chunkSize;
  74. final pullResult =
  75. Sodium.cryptoSecretstreamXchacha20poly1305Pull(pullState, buffer, null);
  76. destinationFile.writeAsBytesSync(pullResult.m, mode: io.FileMode.append);
  77. tag = pullResult.tag;
  78. }
  79. inputFile.closeSync();
  80. logger.info("ChaCha20 Decryption time: " +
  81. (DateTime.now().millisecondsSinceEpoch - decryptionStartTime).toString());
  82. }
  83. class CryptoUtil {
  84. static Future<EncryptionResult> encrypt(
  85. Uint8List source, Uint8List key) async {
  86. final nonce = Sodium.randombytesBuf(Sodium.cryptoSecretboxNoncebytes);
  87. final args = Map<String, dynamic>();
  88. args["source"] = source;
  89. args["nonce"] = nonce;
  90. args["key"] = key;
  91. final encryptedData = cryptoSecretboxEasy(args);
  92. return EncryptionResult(
  93. key: key, nonce: nonce, encryptedData: encryptedData);
  94. }
  95. static Future<Uint8List> decrypt(
  96. Uint8List cipher, Uint8List key, Uint8List nonce,
  97. {bool background = false}) async {
  98. final args = Map<String, dynamic>();
  99. args["cipher"] = cipher;
  100. args["nonce"] = nonce;
  101. args["key"] = key;
  102. if (background) {
  103. return Computer().compute(cryptoSecretboxOpenEasy, param: args);
  104. } else {
  105. return cryptoSecretboxOpenEasy(args);
  106. }
  107. }
  108. static EncryptionResult encryptChaCha(Uint8List source, Uint8List key) {
  109. final initPushResult =
  110. Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);
  111. final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
  112. initPushResult.state,
  113. source,
  114. null,
  115. Sodium.cryptoSecretstreamXchacha20poly1305TagFinal);
  116. return EncryptionResult(
  117. encryptedData: encryptedData, header: initPushResult.header);
  118. }
  119. static Uint8List decryptChaCha(
  120. Uint8List source, Uint8List key, Uint8List header) {
  121. final pullState =
  122. Sodium.cryptoSecretstreamXchacha20poly1305InitPull(header, key);
  123. final pullResult =
  124. Sodium.cryptoSecretstreamXchacha20poly1305Pull(pullState, source, null);
  125. return pullResult.m;
  126. }
  127. static Future<EncryptionResult> encryptFile(
  128. String sourceFilePath,
  129. String destinationFilePath,
  130. ) {
  131. final args = Map<String, dynamic>();
  132. args["sourceFilePath"] = sourceFilePath;
  133. args["destinationFilePath"] = destinationFilePath;
  134. return Computer().compute(chachaEncryptFile, param: args);
  135. }
  136. static Future<void> decryptFile(
  137. String sourceFilePath,
  138. String destinationFilePath,
  139. Uint8List header,
  140. Uint8List key,
  141. ) {
  142. final args = Map<String, dynamic>();
  143. args["sourceFilePath"] = sourceFilePath;
  144. args["destinationFilePath"] = destinationFilePath;
  145. args["header"] = header;
  146. args["key"] = key;
  147. return Computer().compute(chachaDecrypt, param: args);
  148. }
  149. static Uint8List generateMasterKey() {
  150. return Sodium.cryptoSecretboxKeygen();
  151. }
  152. static Uint8List getSaltToDeriveKey() {
  153. return Sodium.randombytesBuf(Sodium.cryptoPwhashSaltbytes);
  154. }
  155. static Uint8List deriveKey(Uint8List passphrase, Uint8List salt) {
  156. return Sodium.cryptoPwhash(
  157. Sodium.cryptoSecretboxKeybytes,
  158. passphrase,
  159. salt,
  160. Sodium.cryptoPwhashOpslimitInteractive,
  161. Sodium.cryptoPwhashMemlimitInteractive,
  162. Sodium.cryptoPwhashAlgDefault);
  163. }
  164. static Future<String> hash(Uint8List input) async {
  165. Sodium.init();
  166. final args = Map<String, dynamic>();
  167. args["input"] = input;
  168. args["opsLimit"] = Sodium.cryptoPwhashOpslimitSensitive;
  169. args["memLimit"] = Sodium.cryptoPwhashMemlimitModerate;
  170. return utf8.decode(await Computer().compute(cryptoPwhashStr, param: args));
  171. }
  172. static Future<bool> verifyHash(Uint8List input, String hash) async {
  173. final args = Map<String, dynamic>();
  174. args["input"] = input;
  175. args["hash"] = utf8.encode(hash);
  176. return await Computer().compute(cryptoPwhashStrVerify, param: args);
  177. }
  178. static Future<KeyPair> generateKeyPair() async {
  179. return Sodium.cryptoBoxKeypair();
  180. }
  181. }