crypto_util.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import 'dart:io' as io;
  2. import 'dart:typed_data';
  3. import 'package:computer/computer.dart';
  4. import 'package:flutter_sodium/flutter_sodium.dart';
  5. import 'package:logging/logging.dart';
  6. import 'package:photos/models/derived_key_result.dart';
  7. import 'package:photos/models/encryption_result.dart';
  8. const int encryptionChunkSize = 4 * 1024 * 1024;
  9. final int decryptionChunkSize =
  10. encryptionChunkSize + Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
  11. const int hashChunkSize = 4 * 1024 * 1024;
  12. Uint8List cryptoSecretboxEasy(Map<String, dynamic> args) {
  13. return Sodium.cryptoSecretboxEasy(args["source"], args["nonce"], args["key"]);
  14. }
  15. Uint8List cryptoSecretboxOpenEasy(Map<String, dynamic> args) {
  16. return Sodium.cryptoSecretboxOpenEasy(
  17. args["cipher"],
  18. args["nonce"],
  19. args["key"],
  20. );
  21. }
  22. Uint8List cryptoPwHash(Map<String, dynamic> args) {
  23. return Sodium.cryptoPwhash(
  24. Sodium.cryptoSecretboxKeybytes,
  25. args["password"],
  26. args["salt"],
  27. args["opsLimit"],
  28. args["memLimit"],
  29. Sodium.cryptoPwhashAlgDefault,
  30. );
  31. }
  32. // Returns the hash for a given file, chunking it in batches of hashChunkSize
  33. Future<Uint8List> cryptoGenericHash(Map<String, dynamic> args) async {
  34. final sourceFile = io.File(args["sourceFilePath"]);
  35. final sourceFileLength = await sourceFile.length();
  36. final inputFile = sourceFile.openSync(mode: io.FileMode.read);
  37. final state =
  38. Sodium.cryptoGenerichashInit(null, Sodium.cryptoGenerichashBytesMax);
  39. var bytesRead = 0;
  40. bool isDone = false;
  41. while (!isDone) {
  42. var chunkSize = hashChunkSize;
  43. if (bytesRead + chunkSize >= sourceFileLength) {
  44. chunkSize = sourceFileLength - bytesRead;
  45. isDone = true;
  46. }
  47. final buffer = await inputFile.read(chunkSize);
  48. bytesRead += chunkSize;
  49. Sodium.cryptoGenerichashUpdate(state, buffer);
  50. }
  51. await inputFile.close();
  52. return Sodium.cryptoGenerichashFinal(state, Sodium.cryptoGenerichashBytesMax);
  53. }
  54. EncryptionResult chachaEncryptData(Map<String, dynamic> args) {
  55. final initPushResult =
  56. Sodium.cryptoSecretstreamXchacha20poly1305InitPush(args["key"]);
  57. final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
  58. initPushResult.state,
  59. args["source"],
  60. null,
  61. Sodium.cryptoSecretstreamXchacha20poly1305TagFinal,
  62. );
  63. return EncryptionResult(
  64. encryptedData: encryptedData,
  65. header: initPushResult.header,
  66. );
  67. }
  68. // Encrypts a given file, in chunks of encryptionChunkSize
  69. Future<EncryptionResult> chachaEncryptFile(Map<String, dynamic> args) async {
  70. final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
  71. final logger = Logger("ChaChaEncrypt");
  72. final sourceFile = io.File(args["sourceFilePath"]);
  73. final destinationFile = io.File(args["destinationFilePath"]);
  74. final sourceFileLength = await sourceFile.length();
  75. logger.info("Encrypting file of size " + sourceFileLength.toString());
  76. final inputFile = sourceFile.openSync(mode: io.FileMode.read);
  77. final key = args["key"] ?? Sodium.cryptoSecretstreamXchacha20poly1305Keygen();
  78. final initPushResult =
  79. Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);
  80. var bytesRead = 0;
  81. var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
  82. while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
  83. var chunkSize = encryptionChunkSize;
  84. if (bytesRead + chunkSize >= sourceFileLength) {
  85. chunkSize = sourceFileLength - bytesRead;
  86. tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
  87. }
  88. final buffer = await inputFile.read(chunkSize);
  89. bytesRead += chunkSize;
  90. final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
  91. initPushResult.state,
  92. buffer,
  93. null,
  94. tag,
  95. );
  96. await destinationFile.writeAsBytes(encryptedData, mode: io.FileMode.append);
  97. }
  98. await inputFile.close();
  99. logger.info(
  100. "Encryption time: " +
  101. (DateTime.now().millisecondsSinceEpoch - encryptionStartTime)
  102. .toString(),
  103. );
  104. return EncryptionResult(key: key, header: initPushResult.header);
  105. }
  106. Future<void> chachaDecryptFile(Map<String, dynamic> args) async {
  107. final logger = Logger("ChaChaDecrypt");
  108. final decryptionStartTime = DateTime.now().millisecondsSinceEpoch;
  109. final sourceFile = io.File(args["sourceFilePath"]);
  110. final destinationFile = io.File(args["destinationFilePath"]);
  111. final sourceFileLength = await sourceFile.length();
  112. logger.info("Decrypting file of size " + sourceFileLength.toString());
  113. final inputFile = sourceFile.openSync(mode: io.FileMode.read);
  114. final pullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
  115. args["header"],
  116. args["key"],
  117. );
  118. var bytesRead = 0;
  119. var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
  120. while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
  121. var chunkSize = decryptionChunkSize;
  122. if (bytesRead + chunkSize >= sourceFileLength) {
  123. chunkSize = sourceFileLength - bytesRead;
  124. }
  125. final buffer = await inputFile.read(chunkSize);
  126. bytesRead += chunkSize;
  127. final pullResult =
  128. Sodium.cryptoSecretstreamXchacha20poly1305Pull(pullState, buffer, null);
  129. await destinationFile.writeAsBytes(pullResult.m, mode: io.FileMode.append);
  130. tag = pullResult.tag;
  131. }
  132. inputFile.closeSync();
  133. logger.info(
  134. "ChaCha20 Decryption time: " +
  135. (DateTime.now().millisecondsSinceEpoch - decryptionStartTime)
  136. .toString(),
  137. );
  138. }
  139. Uint8List chachaDecryptData(Map<String, dynamic> args) {
  140. final pullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
  141. args["header"],
  142. args["key"],
  143. );
  144. final pullResult = Sodium.cryptoSecretstreamXchacha20poly1305Pull(
  145. pullState,
  146. args["source"],
  147. null,
  148. );
  149. return pullResult.m;
  150. }
  151. class CryptoUtil {
  152. static final Computer _computer = Computer();
  153. static init() {
  154. _computer.turnOn(workersCount: 4);
  155. Sodium.init();
  156. }
  157. static Uint8List base642bin(
  158. String b64, {
  159. String? ignore,
  160. int variant = Sodium.base64VariantOriginal,
  161. }) {
  162. return Sodium.base642bin(b64, ignore: ignore, variant: variant);
  163. }
  164. static String bin2base64(
  165. Uint8List bin, {
  166. bool urlSafe = false,
  167. }) {
  168. return Sodium.bin2base64(
  169. bin,
  170. variant:
  171. urlSafe ? Sodium.base64VariantUrlsafe : Sodium.base64VariantOriginal,
  172. );
  173. }
  174. static String bin2hex(Uint8List bin) {
  175. return Sodium.bin2hex(bin);
  176. }
  177. static Uint8List hex2bin(String hex) {
  178. return Sodium.hex2bin(hex);
  179. }
  180. // Encrypts the given source, with the given key and a randomly generated
  181. // nonce, using XSalsa20 (w Poly1305 MAC).
  182. // This function runs on the same thread as the caller, so should be used only
  183. // for small amounts of data where thread switching can result in a degraded
  184. // user experience
  185. static EncryptionResult encryptSync(Uint8List source, Uint8List key) {
  186. final nonce = Sodium.randombytesBuf(Sodium.cryptoSecretboxNoncebytes);
  187. final args = <String, dynamic>{};
  188. args["source"] = source;
  189. args["nonce"] = nonce;
  190. args["key"] = key;
  191. final encryptedData = cryptoSecretboxEasy(args);
  192. return EncryptionResult(
  193. key: key,
  194. nonce: nonce,
  195. encryptedData: encryptedData,
  196. );
  197. }
  198. // Decrypts the given cipher, with the given key and nonce using XSalsa20
  199. // (w Poly1305 MAC).
  200. static Future<Uint8List> decrypt(
  201. Uint8List cipher,
  202. Uint8List key,
  203. Uint8List nonce,
  204. ) async {
  205. final args = <String, dynamic>{};
  206. args["cipher"] = cipher;
  207. args["nonce"] = nonce;
  208. args["key"] = key;
  209. return _computer.compute(cryptoSecretboxOpenEasy, param: args);
  210. }
  211. // Decrypts the given cipher, with the given key and nonce using XSalsa20
  212. // (w Poly1305 MAC).
  213. // This function runs on the same thread as the caller, so should be used only
  214. // for small amounts of data where thread switching can result in a degraded
  215. // user experience
  216. static Uint8List decryptSync(
  217. Uint8List cipher,
  218. Uint8List key,
  219. Uint8List nonce,
  220. ) {
  221. final args = <String, dynamic>{};
  222. args["cipher"] = cipher;
  223. args["nonce"] = nonce;
  224. args["key"] = key;
  225. return cryptoSecretboxOpenEasy(args);
  226. }
  227. // Encrypts the given source, with the given key and a randomly generated
  228. // nonce, using XChaCha20 (w Poly1305 MAC).
  229. // This function runs on the isolate pool held by `_computer`.
  230. // TODO: Remove "ChaCha", an implementation detail from the function name
  231. static Future<EncryptionResult> encryptChaCha(
  232. Uint8List source,
  233. Uint8List key,
  234. ) async {
  235. final args = <String, dynamic>{};
  236. args["source"] = source;
  237. args["key"] = key;
  238. return _computer.compute(chachaEncryptData, param: args);
  239. }
  240. // Decrypts the given source, with the given key and header using XChaCha20
  241. // (w Poly1305 MAC).
  242. // TODO: Remove "ChaCha", an implementation detail from the function name
  243. static Future<Uint8List> decryptChaCha(
  244. Uint8List source,
  245. Uint8List key,
  246. Uint8List header,
  247. ) async {
  248. final args = <String, dynamic>{};
  249. args["source"] = source;
  250. args["key"] = key;
  251. args["header"] = header;
  252. return _computer.compute(chachaDecryptData, param: args);
  253. }
  254. // Encrypts the file at sourceFilePath, with the key (if provided) and a
  255. // randomly generated nonce using XChaCha20 (w Poly1305 MAC), and writes it
  256. // to the destinationFilePath.
  257. // If a key is not provided, one is generated and returned.
  258. static Future<EncryptionResult> encryptFile(
  259. String sourceFilePath,
  260. String destinationFilePath, {
  261. Uint8List? key,
  262. }) {
  263. final args = <String, dynamic>{};
  264. args["sourceFilePath"] = sourceFilePath;
  265. args["destinationFilePath"] = destinationFilePath;
  266. args["key"] = key;
  267. return _computer.compute(chachaEncryptFile, param: args);
  268. }
  269. // Decrypts the file at sourceFilePath, with the given key and header using
  270. // XChaCha20 (w Poly1305 MAC), and writes it to the destinationFilePath.
  271. static Future<void> decryptFile(
  272. String sourceFilePath,
  273. String destinationFilePath,
  274. Uint8List header,
  275. Uint8List key,
  276. ) {
  277. final args = <String, dynamic>{};
  278. args["sourceFilePath"] = sourceFilePath;
  279. args["destinationFilePath"] = destinationFilePath;
  280. args["header"] = header;
  281. args["key"] = key;
  282. return _computer.compute(chachaDecryptFile, param: args);
  283. }
  284. // Generates and returns a 256-bit key.
  285. static Uint8List generateKey() {
  286. return Sodium.cryptoSecretboxKeygen();
  287. }
  288. // Generates and returns a random byte buffer of length
  289. // crypto_pwhash_SALTBYTES (16)
  290. static Uint8List getSaltToDeriveKey() {
  291. return Sodium.randombytesBuf(Sodium.cryptoPwhashSaltbytes);
  292. }
  293. // Generates and returns a secret key and the corresponding public key.
  294. static Future<KeyPair> generateKeyPair() async {
  295. return Sodium.cryptoBoxKeypair();
  296. }
  297. // Decrypts the input using the given publicKey-secretKey pair
  298. static Uint8List openSealSync(
  299. Uint8List input,
  300. Uint8List publicKey,
  301. Uint8List secretKey,
  302. ) {
  303. return Sodium.cryptoBoxSealOpen(input, publicKey, secretKey);
  304. }
  305. // Encrypts the input using the given publicKey
  306. static Uint8List sealSync(Uint8List input, Uint8List publicKey) {
  307. return Sodium.cryptoBoxSeal(input, publicKey);
  308. }
  309. // Derives a key for a given password and salt using Argon2id, v1.3.
  310. // The function first attempts to derive a key with both memLimit and opsLimit
  311. // set to their Sensitive variants.
  312. // If this fails, say on a device with insufficient RAM, we retry by halving
  313. // the memLimit and doubling the opsLimit, while ensuring that we stay within
  314. // the min and max limits for both parameters.
  315. // At all points, we ensure that the product of these two variables (the area
  316. // under the graph that determines the amount of work required) is a constant.
  317. static Future<DerivedKeyResult> deriveSensitiveKey(
  318. Uint8List password,
  319. Uint8List salt,
  320. ) async {
  321. assert(
  322. Sodium.cryptoPwhashAlgArgon2id13 == Sodium.cryptoPwhashAlgDefault,
  323. "mismatch in expected default pw hashing algo",
  324. );
  325. final logger = Logger("pwhash");
  326. int memLimit = Sodium.cryptoPwhashMemlimitSensitive;
  327. int opsLimit = Sodium.cryptoPwhashOpslimitSensitive;
  328. Uint8List key;
  329. while (memLimit >= Sodium.cryptoPwhashMemlimitMin &&
  330. opsLimit <= Sodium.cryptoPwhashOpslimitMax) {
  331. try {
  332. key = await deriveKey(password, salt, memLimit, opsLimit);
  333. return DerivedKeyResult(key, memLimit, opsLimit);
  334. } catch (e, s) {
  335. logger.severe(
  336. "failed to derive memLimit: $memLimit and opsLimit: $opsLimit",
  337. e,
  338. s,
  339. );
  340. }
  341. memLimit = (memLimit / 2).round();
  342. opsLimit = opsLimit * 2;
  343. }
  344. throw UnsupportedError("Cannot perform this operation on this device");
  345. }
  346. // Derives a key for the given password and salt, using Argon2id, v1.3
  347. // with memory and ops limit hardcoded to their Interactive variants
  348. // NOTE: This is only used while setting passwords for shared links, as an
  349. // extra layer of authentication (atop the access token and collection key).
  350. // More details @ https://ente.io/blog/building-shareable-links/
  351. static Future<DerivedKeyResult> deriveInteractiveKey(
  352. Uint8List password,
  353. Uint8List salt,
  354. ) async {
  355. assert(
  356. Sodium.cryptoPwhashAlgArgon2id13 == Sodium.cryptoPwhashAlgDefault,
  357. "mismatch in expected default pw hashing algo",
  358. );
  359. final int memLimit = Sodium.cryptoPwhashMemlimitInteractive;
  360. final int opsLimit = Sodium.cryptoPwhashOpslimitInteractive;
  361. final key = await deriveKey(password, salt, memLimit, opsLimit);
  362. return DerivedKeyResult(key, memLimit, opsLimit);
  363. }
  364. // Derives a key for a given password, salt, memLimit and opsLimit using
  365. // Argon2id, v1.3.
  366. static Future<Uint8List> deriveKey(
  367. Uint8List password,
  368. Uint8List salt,
  369. int memLimit,
  370. int opsLimit,
  371. ) {
  372. return _computer.compute(
  373. cryptoPwHash,
  374. param: {
  375. "password": password,
  376. "salt": salt,
  377. "memLimit": memLimit,
  378. "opsLimit": opsLimit,
  379. },
  380. );
  381. }
  382. // Computes and returns the hash of the source file
  383. static Future<Uint8List> getHash(io.File source) {
  384. return _computer.compute(
  385. cryptoGenericHash,
  386. param: {
  387. "sourceFilePath": source.path,
  388. },
  389. );
  390. }
  391. }