crypto primitives

This commit is contained in:
Christien Rioux 2023-08-02 21:09:47 -04:00
parent 559ac5f162
commit 7ba795132b
10 changed files with 465 additions and 425 deletions

View file

@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:charcode/charcode.dart';
@ -184,4 +185,49 @@ abstract class VeilidCryptoSystem {
SharedSecret sharedSecret, Uint8List? associatedData);
Future<Uint8List> cryptNoAuth(
Uint8List body, Nonce nonce, SharedSecret sharedSecret);
Future<Uint8List> encryptNoAuthWithNonce(
Uint8List body, SharedSecret secret) async {
// generate nonce
final nonce = await randomNonce();
// crypt and append nonce
final b = BytesBuilder()
..add(await cryptNoAuth(body, nonce, secret))
..add(nonce.decode());
return b.toBytes();
}
Future<Uint8List> decryptNoAuthWithNonce(
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 cryptNoAuth(encryptedData, nonce, secret);
}
Future<Uint8List> encryptNoAuthWithPassword(
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 (await cryptNoAuth(body, nonce, sharedSecret))..addAll(saltBytes);
}
Future<Uint8List> decryptNoAuthWithPassword(
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 cryptNoAuth(bodyBytes, nonce, sharedSecret);
}
}