From 437e21b0fef0eb87b70530a77a19f19df9154706 Mon Sep 17 00:00:00 2001 From: Christien Rioux Date: Sun, 24 Sep 2023 22:36:15 -0400 Subject: [PATCH] encryption tools --- veilid-flutter/lib/veilid_crypto.dart | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/veilid-flutter/lib/veilid_crypto.dart b/veilid-flutter/lib/veilid_crypto.dart index a6b3bead..85d22397 100644 --- a/veilid-flutter/lib/veilid_crypto.dart +++ b/veilid-flutter/lib/veilid_crypto.dart @@ -186,6 +186,52 @@ abstract class VeilidCryptoSystem { Future cryptNoAuth( Uint8List body, Nonce nonce, SharedSecret sharedSecret); + Future encryptAeadWithNonce( + Uint8List body, SharedSecret secret) async { + // generate nonce + final nonce = await randomNonce(); + // crypt and append nonce + final b = BytesBuilder() + ..add(await encryptAead(body, nonce, secret, null)) + ..add(nonce.decode()); + return b.toBytes(); + } + + Future decryptAeadWithNonce( + Uint8List body, SharedSecret secret) async { + if (body.length < Nonce.decodedLength()) { + throw const FormatException('not enough data to decrypt'); + } + final nonce = + Nonce.fromBytes(body.sublist(body.length - Nonce.decodedLength())); + final encryptedData = body.sublist(0, body.length - Nonce.decodedLength()); + // decrypt + return decryptAead(encryptedData, nonce, secret, null); + } + + Future encryptAeadWithPassword( + Uint8List body, String password) async { + final ekbytes = Uint8List.fromList(utf8.encode(password)); + final nonce = await randomNonce(); + final saltBytes = nonce.decode(); + final sharedSecret = await deriveSharedSecret(ekbytes, saltBytes); + return Uint8List.fromList( + (await encryptAead(body, nonce, sharedSecret, null)) + saltBytes); + } + + Future decryptAeadWithPassword( + Uint8List body, String password) async { + if (body.length < Nonce.decodedLength()) { + throw const FormatException('not enough data to decrypt'); + } + final ekbytes = Uint8List.fromList(utf8.encode(password)); + final bodyBytes = body.sublist(0, body.length - Nonce.decodedLength()); + final saltBytes = body.sublist(body.length - Nonce.decodedLength()); + final nonce = Nonce.fromBytes(saltBytes); + final sharedSecret = await deriveSharedSecret(ekbytes, saltBytes); + return decryptAead(bodyBytes, nonce, sharedSecret, null); + } + Future encryptNoAuthWithNonce( Uint8List body, SharedSecret secret) async { // generate nonce