crypto primitives
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user