veilidchat/lib/tools/secret_crypto.dart

47 lines
1.4 KiB
Dart
Raw Normal View History

2023-08-02 21:09:28 -04:00
import 'dart:typed_data';
import '../entities/local_account.dart';
2023-09-26 18:46:02 -04:00
import '../veilid_init.dart';
2023-08-02 21:09:28 -04:00
import '../veilid_support/veilid_support.dart';
Future<Uint8List> encryptSecretToBytes(
{required SecretKey secret,
required CryptoKind cryptoKind,
EncryptionKeyType encryptionKeyType = EncryptionKeyType.none,
String encryptionKey = ''}) async {
final veilid = await eventualVeilid.future;
2023-09-24 22:35:54 -04:00
late final Uint8List secretBytes;
2023-08-02 21:09:28 -04:00
switch (encryptionKeyType) {
case EncryptionKeyType.none:
2023-09-24 22:35:54 -04:00
secretBytes = secret.decode();
2023-08-02 21:09:28 -04:00
case EncryptionKeyType.pin:
case EncryptionKeyType.password:
final cs = await veilid.getCryptoSystem(cryptoKind);
2023-09-24 22:35:54 -04:00
secretBytes =
await cs.encryptAeadWithPassword(secret.decode(), encryptionKey);
2023-08-02 21:09:28 -04:00
}
2023-09-24 22:35:54 -04:00
return secretBytes;
}
Future<SecretKey> decryptSecretFromBytes(
{required Uint8List secretBytes,
required CryptoKind cryptoKind,
EncryptionKeyType encryptionKeyType = EncryptionKeyType.none,
String encryptionKey = ''}) async {
final veilid = await eventualVeilid.future;
late final SecretKey secret;
switch (encryptionKeyType) {
case EncryptionKeyType.none:
secret = SecretKey.fromBytes(secretBytes);
case EncryptionKeyType.pin:
case EncryptionKeyType.password:
final cs = await veilid.getCryptoSystem(cryptoKind);
secret = SecretKey.fromBytes(
await cs.decryptAeadWithPassword(secretBytes, encryptionKey));
}
return secret;
2023-08-02 21:09:28 -04:00
}