style: Format using dart format
This commit is contained in:
@@ -6,7 +6,8 @@ import 'package:omemo_dart/src/keys.dart';
|
||||
/// it indicates which of [kp] ([identityKey] == 1) or [pk] ([identityKey] == 2)
|
||||
/// is the identity key. This is needed since the identity key pair/public key is
|
||||
/// an Ed25519 key, but we need them as X25519 keys for DH.
|
||||
Future<List<int>> omemoDH(OmemoKeyPair kp, OmemoPublicKey pk, int identityKey) async {
|
||||
Future<List<int>> omemoDH(
|
||||
OmemoKeyPair kp, OmemoPublicKey pk, int identityKey,) async {
|
||||
var ckp = kp;
|
||||
var cpk = pk;
|
||||
|
||||
@@ -17,15 +18,14 @@ Future<List<int>> omemoDH(OmemoKeyPair kp, OmemoPublicKey pk, int identityKey) a
|
||||
}
|
||||
|
||||
final shared = await Cryptography.instance.x25519().sharedSecretKey(
|
||||
keyPair: await ckp.asKeyPair(),
|
||||
remotePublicKey: cpk.asPublicKey(),
|
||||
);
|
||||
keyPair: await ckp.asKeyPair(),
|
||||
remotePublicKey: cpk.asPublicKey(),
|
||||
);
|
||||
|
||||
return shared.extractBytes();
|
||||
}
|
||||
|
||||
class HkdfKeyResult {
|
||||
|
||||
const HkdfKeyResult(this.encryptionKey, this.authenticationKey, this.iv);
|
||||
final List<int> encryptionKey;
|
||||
final List<int> authenticationKey;
|
||||
@@ -35,7 +35,8 @@ class HkdfKeyResult {
|
||||
/// cryptography _really_ wants to check the MAC output from AES-256-CBC. Since
|
||||
/// we don't have it, we need the MAC check to always "pass".
|
||||
class NoMacSecretBox extends SecretBox {
|
||||
NoMacSecretBox(super.cipherText, { required super.nonce }) : super(mac: Mac.empty);
|
||||
NoMacSecretBox(super.cipherText, {required super.nonce})
|
||||
: super(mac: Mac.empty);
|
||||
|
||||
@override
|
||||
Future<void> checkMac({
|
||||
@@ -59,13 +60,15 @@ Future<HkdfKeyResult> deriveEncryptionKeys(List<int> input, String info) async {
|
||||
info: utf8.encode(info),
|
||||
);
|
||||
final bytes = await result.extractBytes();
|
||||
|
||||
return HkdfKeyResult(bytes.sublist(0, 32), bytes.sublist(32, 64), bytes.sublist(64, 80));
|
||||
|
||||
return HkdfKeyResult(
|
||||
bytes.sublist(0, 32), bytes.sublist(32, 64), bytes.sublist(64, 80),);
|
||||
}
|
||||
|
||||
/// A small helper function to make AES-256-CBC easier. Encrypt [plaintext] using [key] as
|
||||
/// the encryption key and [iv] as the IV. Returns the ciphertext.
|
||||
Future<List<int>> aes256CbcEncrypt(List<int> plaintext, List<int> key, List<int> iv) async {
|
||||
Future<List<int>> aes256CbcEncrypt(
|
||||
List<int> plaintext, List<int> key, List<int> iv,) async {
|
||||
final algorithm = AesCbc.with256bits(
|
||||
macAlgorithm: MacAlgorithm.empty,
|
||||
);
|
||||
@@ -80,7 +83,8 @@ Future<List<int>> aes256CbcEncrypt(List<int> plaintext, List<int> key, List<int>
|
||||
|
||||
/// A small helper function to make AES-256-CBC easier. Decrypt [ciphertext] using [key] as
|
||||
/// the encryption key and [iv] as the IV. Returns the ciphertext.
|
||||
Future<List<int>> aes256CbcDecrypt(List<int> ciphertext, List<int> key, List<int> iv) async {
|
||||
Future<List<int>> aes256CbcDecrypt(
|
||||
List<int> ciphertext, List<int> key, List<int> iv,) async {
|
||||
final algorithm = AesCbc.with256bits(
|
||||
macAlgorithm: MacAlgorithm.empty,
|
||||
);
|
||||
|
||||
@@ -10,13 +10,16 @@ const encryptHkdfInfoString = 'OMEMO Message Key Material';
|
||||
/// Signals ENCRYPT function as specified by OMEMO 0.8.3.
|
||||
/// Encrypt [plaintext] using the message key [mk], given associated_data [associatedData]
|
||||
/// and the AD output from the X3DH [sessionAd].
|
||||
Future<List<int>> encrypt(List<int> mk, List<int> plaintext, List<int> associatedData, List<int> sessionAd) async {
|
||||
Future<List<int>> encrypt(List<int> mk, List<int> plaintext,
|
||||
List<int> associatedData, List<int> sessionAd,) async {
|
||||
// Generate encryption, authentication key and IV
|
||||
final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString);
|
||||
final ciphertext = await aes256CbcEncrypt(plaintext, keys.encryptionKey, keys.iv);
|
||||
|
||||
final header = OmemoMessage.fromBuffer(associatedData.sublist(sessionAd.length))
|
||||
..ciphertext = ciphertext;
|
||||
final ciphertext =
|
||||
await aes256CbcEncrypt(plaintext, keys.encryptionKey, keys.iv);
|
||||
|
||||
final header =
|
||||
OmemoMessage.fromBuffer(associatedData.sublist(sessionAd.length))
|
||||
..ciphertext = ciphertext;
|
||||
final headerBytes = header.writeToBuffer();
|
||||
final hmacInput = concat([sessionAd, headerBytes]);
|
||||
final hmacResult = await truncatedHmac(hmacInput, keys.authenticationKey);
|
||||
@@ -29,10 +32,11 @@ Future<List<int>> encrypt(List<int> mk, List<int> plaintext, List<int> associate
|
||||
/// Signals DECRYPT function as specified by OMEMO 0.8.3.
|
||||
/// Decrypt [ciphertext] with the message key [mk], given the associated_data [associatedData]
|
||||
/// and the AD output from the X3DH.
|
||||
Future<List<int>> decrypt(List<int> mk, List<int> ciphertext, List<int> associatedData, List<int> sessionAd) async {
|
||||
Future<List<int>> decrypt(List<int> mk, List<int> ciphertext,
|
||||
List<int> associatedData, List<int> sessionAd,) async {
|
||||
// Generate encryption, authentication key and IV
|
||||
final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString);
|
||||
|
||||
|
||||
// Assumption ciphertext is a OMEMOAuthenticatedMessage
|
||||
final message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
|
||||
final header = OmemoMessage.fromBuffer(message.message!);
|
||||
|
||||
@@ -42,7 +42,7 @@ class SkippedKey {
|
||||
'n': n,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SkippedKey && other.dh == dh && other.n == n;
|
||||
@@ -56,12 +56,12 @@ class OmemoDoubleRatchet {
|
||||
OmemoDoubleRatchet(
|
||||
this.dhs, // DHs
|
||||
this.dhr, // DHr
|
||||
this.rk, // RK
|
||||
this.rk, // RK
|
||||
this.cks, // CKs
|
||||
this.ckr, // CKr
|
||||
this.ns, // Ns
|
||||
this.nr, // Nr
|
||||
this.pn, // Pn
|
||||
this.ns, // Ns
|
||||
this.nr, // Nr
|
||||
this.pn, // Pn
|
||||
this.ik,
|
||||
this.sessionAd,
|
||||
this.mkSkipped, // MKSKIPPED
|
||||
@@ -69,7 +69,7 @@ class OmemoDoubleRatchet {
|
||||
this.kexTimestamp,
|
||||
this.kex,
|
||||
);
|
||||
|
||||
|
||||
factory OmemoDoubleRatchet.fromJson(Map<String, dynamic> data) {
|
||||
/*
|
||||
{
|
||||
@@ -99,7 +99,8 @@ class OmemoDoubleRatchet {
|
||||
// NOTE: Dart has some issues with just casting a List<dynamic> to List<Map<...>>, as
|
||||
// such we need to convert the items by hand.
|
||||
final mkSkipped = Map<SkippedKey, List<int>>.fromEntries(
|
||||
(data['mkskipped']! as List<dynamic>).map<MapEntry<SkippedKey, List<int>>>(
|
||||
(data['mkskipped']! as List<dynamic>)
|
||||
.map<MapEntry<SkippedKey, List<int>>>(
|
||||
(entry) {
|
||||
final map = entry as Map<String, dynamic>;
|
||||
final key = SkippedKey.fromJson(map);
|
||||
@@ -110,7 +111,7 @@ class OmemoDoubleRatchet {
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
return OmemoDoubleRatchet(
|
||||
OmemoKeyPair.fromBytes(
|
||||
base64.decode(data['dhs_pub']! as String),
|
||||
@@ -135,7 +136,7 @@ class OmemoDoubleRatchet {
|
||||
data['kex'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Sending DH keypair
|
||||
OmemoKeyPair dhs;
|
||||
|
||||
@@ -159,7 +160,7 @@ class OmemoDoubleRatchet {
|
||||
/// The IK public key from the chat partner. Not used for the actual encryption but
|
||||
/// for verification purposes
|
||||
final OmemoPublicKey ik;
|
||||
|
||||
|
||||
final List<int> sessionAd;
|
||||
|
||||
final Map<SkippedKey, List<int>> mkSkipped;
|
||||
@@ -170,18 +171,19 @@ class OmemoDoubleRatchet {
|
||||
|
||||
/// The key exchange that was used for initiating the session.
|
||||
final String? kex;
|
||||
|
||||
|
||||
/// Indicates whether we received an empty OMEMO message after building a session with
|
||||
/// the device.
|
||||
/// the device.
|
||||
bool acknowledged;
|
||||
|
||||
/// Create an OMEMO session using the Signed Pre Key [spk], the shared secret [sk] that
|
||||
/// was obtained using a X3DH and the associated data [ad] that was also obtained through
|
||||
/// a X3DH. [ik] refers to Bob's (the receiver's) IK public key.
|
||||
static Future<OmemoDoubleRatchet> initiateNewSession(OmemoPublicKey spk, OmemoPublicKey ik, List<int> sk, List<int> ad, int timestamp) async {
|
||||
static Future<OmemoDoubleRatchet> initiateNewSession(OmemoPublicKey spk,
|
||||
OmemoPublicKey ik, List<int> sk, List<int> ad, int timestamp,) async {
|
||||
final dhs = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
|
||||
final dhr = spk;
|
||||
final rk = await kdfRk(sk, await omemoDH(dhs, dhr, 0));
|
||||
final rk = await kdfRk(sk, await omemoDH(dhs, dhr, 0));
|
||||
final cks = rk;
|
||||
|
||||
return OmemoDoubleRatchet(
|
||||
@@ -206,7 +208,8 @@ class OmemoDoubleRatchet {
|
||||
/// Pre Key keypair [spk], the shared secret [sk] that was obtained through a X3DH and
|
||||
/// the associated data [ad] that was also obtained through a X3DH. [ik] refers to
|
||||
/// Alice's (the initiator's) IK public key.
|
||||
static Future<OmemoDoubleRatchet> acceptNewSession(OmemoKeyPair spk, OmemoPublicKey ik, List<int> sk, List<int> ad, int kexTimestamp) async {
|
||||
static Future<OmemoDoubleRatchet> acceptNewSession(OmemoKeyPair spk,
|
||||
OmemoPublicKey ik, List<int> sk, List<int> ad, int kexTimestamp,) async {
|
||||
return OmemoDoubleRatchet(
|
||||
spk,
|
||||
null,
|
||||
@@ -226,14 +229,15 @@ class OmemoDoubleRatchet {
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> toJson() async {
|
||||
final mkSkippedSerialised = List<Map<String, dynamic>>.empty(growable: true);
|
||||
final mkSkippedSerialised =
|
||||
List<Map<String, dynamic>>.empty(growable: true);
|
||||
for (final entry in mkSkipped.entries) {
|
||||
final result = await entry.key.toJson();
|
||||
result['key'] = base64.encode(entry.value);
|
||||
|
||||
mkSkippedSerialised.add(result);
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
'dhs': base64.encode(await dhs.sk.getBytes()),
|
||||
'dhs_pub': base64.encode(await dhs.pk.getBytes()),
|
||||
@@ -258,8 +262,9 @@ class OmemoDoubleRatchet {
|
||||
final curveKey = await ik.toCurve25519();
|
||||
return HEX.encode(await curveKey.getBytes());
|
||||
}
|
||||
|
||||
Future<List<int>?> _trySkippedMessageKeys(OmemoMessage header, List<int> ciphertext) async {
|
||||
|
||||
Future<List<int>?> _trySkippedMessageKeys(
|
||||
OmemoMessage header, List<int> ciphertext,) async {
|
||||
final key = SkippedKey(
|
||||
OmemoPublicKey.fromBytes(header.dhPub!, KeyPairType.x25519),
|
||||
header.n!,
|
||||
@@ -268,7 +273,8 @@ class OmemoDoubleRatchet {
|
||||
final mk = mkSkipped[key]!;
|
||||
mkSkipped.remove(key);
|
||||
|
||||
return decrypt(mk, ciphertext, concat([sessionAd, header.writeToBuffer()]), sessionAd);
|
||||
return decrypt(mk, ciphertext,
|
||||
concat([sessionAd, header.writeToBuffer()]), sessionAd,);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -320,7 +326,8 @@ class OmemoDoubleRatchet {
|
||||
|
||||
return RatchetStep(
|
||||
header,
|
||||
await encrypt(mk, plaintext, concat([sessionAd, header.writeToBuffer()]), sessionAd),
|
||||
await encrypt(mk, plaintext, concat([sessionAd, header.writeToBuffer()]),
|
||||
sessionAd,),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -328,7 +335,8 @@ class OmemoDoubleRatchet {
|
||||
/// Ratchet. Returns the decrypted (raw) plaintext.
|
||||
///
|
||||
/// Throws an SkippingTooManyMessagesException if too many messages were to be skipped.
|
||||
Future<List<int>> ratchetDecrypt(OmemoMessage header, List<int> ciphertext) async {
|
||||
Future<List<int>> ratchetDecrypt(
|
||||
OmemoMessage header, List<int> ciphertext,) async {
|
||||
// Check if we skipped too many messages
|
||||
final plaintext = await _trySkippedMessageKeys(header, ciphertext);
|
||||
if (plaintext != null) {
|
||||
@@ -343,14 +351,15 @@ class OmemoDoubleRatchet {
|
||||
await _skipMessageKeys(header.pn!);
|
||||
await _dhRatchet(header);
|
||||
}
|
||||
|
||||
|
||||
await _skipMessageKeys(header.n!);
|
||||
final newCkr = await kdfCk(ckr!, kdfCkNextChainKey);
|
||||
final mk = await kdfCk(ckr!, kdfCkNextMessageKey);
|
||||
ckr = newCkr;
|
||||
nr++;
|
||||
|
||||
return decrypt(mk, ciphertext, concat([sessionAd, header.writeToBuffer()]), sessionAd);
|
||||
return decrypt(
|
||||
mk, ciphertext, concat([sessionAd, header.writeToBuffer()]), sessionAd,);
|
||||
}
|
||||
|
||||
OmemoDoubleRatchet clone() {
|
||||
@@ -358,12 +367,8 @@ class OmemoDoubleRatchet {
|
||||
dhs,
|
||||
dhr,
|
||||
rk,
|
||||
cks != null ?
|
||||
List<int>.from(cks!) :
|
||||
null,
|
||||
ckr != null ?
|
||||
List<int>.from(ckr!) :
|
||||
null,
|
||||
cks != null ? List<int>.from(cks!) : null,
|
||||
ckr != null ? List<int>.from(ckr!) : null,
|
||||
ns,
|
||||
nr,
|
||||
pn,
|
||||
@@ -381,12 +386,8 @@ class OmemoDoubleRatchet {
|
||||
dhs,
|
||||
dhr,
|
||||
rk,
|
||||
cks != null ?
|
||||
List<int>.from(cks!) :
|
||||
null,
|
||||
ckr != null ?
|
||||
List<int>.from(ckr!) :
|
||||
null,
|
||||
cks != null ? List<int>.from(cks!) : null,
|
||||
ckr != null ? List<int>.from(ckr!) : null,
|
||||
ns,
|
||||
nr,
|
||||
pn,
|
||||
@@ -398,35 +399,36 @@ class OmemoDoubleRatchet {
|
||||
kex,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@visibleForTesting
|
||||
Future<bool> equals(OmemoDoubleRatchet other) async {
|
||||
final dhrMatch = dhr == null ?
|
||||
other.dhr == null :
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
other.dhr != null && await dhr!.equals(other.dhr!);
|
||||
final ckrMatch = ckr == null ?
|
||||
other.ckr == null :
|
||||
other.ckr != null && listsEqual(ckr!, other.ckr!);
|
||||
final cksMatch = cks == null ?
|
||||
other.cks == null :
|
||||
other.cks != null && listsEqual(cks!, other.cks!);
|
||||
|
||||
final dhrMatch = dhr == null
|
||||
? other.dhr == null
|
||||
:
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
other.dhr != null && await dhr!.equals(other.dhr!);
|
||||
final ckrMatch = ckr == null
|
||||
? other.ckr == null
|
||||
: other.ckr != null && listsEqual(ckr!, other.ckr!);
|
||||
final cksMatch = cks == null
|
||||
? other.cks == null
|
||||
: other.cks != null && listsEqual(cks!, other.cks!);
|
||||
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
final dhsMatch = await dhs.equals(other.dhs);
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
final ikMatch = await ik.equals(other.ik);
|
||||
|
||||
return dhsMatch &&
|
||||
ikMatch &&
|
||||
dhrMatch &&
|
||||
listsEqual(rk, other.rk) &&
|
||||
cksMatch &&
|
||||
ckrMatch &&
|
||||
ns == other.ns &&
|
||||
nr == other.nr &&
|
||||
pn == other.pn &&
|
||||
listsEqual(sessionAd, other.sessionAd) &&
|
||||
kexTimestamp == other.kexTimestamp;
|
||||
ikMatch &&
|
||||
dhrMatch &&
|
||||
listsEqual(rk, other.rk) &&
|
||||
cksMatch &&
|
||||
ckrMatch &&
|
||||
ns == other.ns &&
|
||||
nr == other.nr &&
|
||||
pn == other.pn &&
|
||||
listsEqual(sessionAd, other.sessionAd) &&
|
||||
kexTimestamp == other.kexTimestamp;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@ abstract class OmemoException {}
|
||||
|
||||
/// Triggered during X3DH if the signature if the SPK does verify to the actual SPK.
|
||||
class InvalidSignatureException extends OmemoException implements Exception {
|
||||
String errMsg() => 'The signature of the SPK does not match the provided signature';
|
||||
String errMsg() =>
|
||||
'The signature of the SPK does not match the provided signature';
|
||||
}
|
||||
|
||||
/// Triggered by the Double Ratchet if the computed HMAC does not match the attached HMAC.
|
||||
/// Triggered by the Session Manager if the computed HMAC does not match the attached HMAC.
|
||||
class InvalidMessageHMACException extends OmemoException implements Exception {
|
||||
@@ -12,12 +14,14 @@ class InvalidMessageHMACException extends OmemoException implements Exception {
|
||||
|
||||
/// Triggered by the Double Ratchet if skipping messages would cause skipping more than
|
||||
/// MAXSKIP messages
|
||||
class SkippingTooManyMessagesException extends OmemoException implements Exception {
|
||||
class SkippingTooManyMessagesException extends OmemoException
|
||||
implements Exception {
|
||||
String errMsg() => 'Skipping messages would cause a skip bigger than MAXSKIP';
|
||||
}
|
||||
|
||||
/// Triggered by the Session Manager if the message key is not encrypted for the device.
|
||||
class NotEncryptedForDeviceException extends OmemoException implements Exception {
|
||||
class NotEncryptedForDeviceException extends OmemoException
|
||||
implements Exception {
|
||||
String errMsg() => 'Not encrypted for this device';
|
||||
}
|
||||
|
||||
@@ -41,7 +45,8 @@ class InvalidKeyExchangeException extends OmemoException implements Exception {
|
||||
|
||||
/// Triggered by the Session Manager when a message's sequence number is smaller than we
|
||||
/// expect it to be.
|
||||
class MessageAlreadyDecryptedException extends OmemoException implements Exception {
|
||||
class MessageAlreadyDecryptedException extends OmemoException
|
||||
implements Exception {
|
||||
String errMsg() => 'The message has already been decrypted';
|
||||
}
|
||||
|
||||
@@ -49,6 +54,8 @@ class MessageAlreadyDecryptedException extends OmemoException implements Excepti
|
||||
/// no key material available. That happens, for example, when we want to create a
|
||||
/// ratchet session with a JID we had no session with but fetching the device bundle
|
||||
/// failed.
|
||||
class NoKeyMaterialAvailableException extends OmemoException implements Exception {
|
||||
String errMsg() => 'No key material available to create a ratchet session with';
|
||||
class NoKeyMaterialAvailableException extends OmemoException
|
||||
implements Exception {
|
||||
String errMsg() =>
|
||||
'No key material available to create a ratchet session with';
|
||||
}
|
||||
|
||||
@@ -43,7 +43,8 @@ int generateRandom32BitNumber() {
|
||||
return Random.secure().nextInt(4294967295 /*pow(2, 32) - 1*/);
|
||||
}
|
||||
|
||||
OmemoPublicKey? decodeKeyIfNotNull(Map<String, dynamic> map, String key, KeyPairType type) {
|
||||
OmemoPublicKey? decodeKeyIfNotNull(
|
||||
Map<String, dynamic> map, String key, KeyPairType type,) {
|
||||
if (map[key] == null) return null;
|
||||
|
||||
return OmemoPublicKey.fromBytes(
|
||||
|
||||
@@ -21,7 +21,7 @@ class OmemoPublicKey {
|
||||
}
|
||||
|
||||
final SimplePublicKey _pubkey;
|
||||
|
||||
|
||||
KeyPairType get type => _pubkey.type;
|
||||
|
||||
/// Return the bytes that comprise the public key.
|
||||
@@ -31,7 +31,8 @@ class OmemoPublicKey {
|
||||
Future<String> asBase64() async => base64Encode(_pubkey.bytes);
|
||||
|
||||
Future<OmemoPublicKey> toCurve25519() async {
|
||||
assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 public key to X25519');
|
||||
assert(type == KeyPairType.ed25519,
|
||||
'Cannot convert non-Ed25519 public key to X25519',);
|
||||
|
||||
final pkc = Uint8List(publicKeyLength);
|
||||
TweetNaClExt.crypto_sign_ed25519_pk_to_x25519_pk(
|
||||
@@ -39,17 +40,19 @@ class OmemoPublicKey {
|
||||
Uint8List.fromList(await getBytes()),
|
||||
);
|
||||
|
||||
return OmemoPublicKey(SimplePublicKey(List<int>.from(pkc), type: KeyPairType.x25519));
|
||||
return OmemoPublicKey(
|
||||
SimplePublicKey(List<int>.from(pkc), type: KeyPairType.x25519),);
|
||||
}
|
||||
|
||||
SimplePublicKey asPublicKey() => _pubkey;
|
||||
|
||||
@visibleForTesting
|
||||
Future<bool> equals(OmemoPublicKey key) async {
|
||||
return type == key.type && listsEqual(
|
||||
await getBytes(),
|
||||
await key.getBytes(),
|
||||
);
|
||||
return type == key.type &&
|
||||
listsEqual(
|
||||
await getBytes(),
|
||||
await key.getBytes(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,9 +62,10 @@ class OmemoPrivateKey {
|
||||
final KeyPairType type;
|
||||
|
||||
Future<List<int>> getBytes() async => _privkey;
|
||||
|
||||
|
||||
Future<OmemoPrivateKey> toCurve25519() async {
|
||||
assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 private key to X25519');
|
||||
assert(type == KeyPairType.ed25519,
|
||||
'Cannot convert non-Ed25519 private key to X25519',);
|
||||
|
||||
final skc = Uint8List(privateKeyLength);
|
||||
TweetNaClExt.crypto_sign_ed25519_sk_to_x25519_sk(
|
||||
@@ -74,10 +78,11 @@ class OmemoPrivateKey {
|
||||
|
||||
@visibleForTesting
|
||||
Future<bool> equals(OmemoPrivateKey key) async {
|
||||
return type == key.type && listsEqual(
|
||||
await getBytes(),
|
||||
await key.getBytes(),
|
||||
);
|
||||
return type == key.type &&
|
||||
listsEqual(
|
||||
await getBytes(),
|
||||
await key.getBytes(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +92,8 @@ class OmemoKeyPair {
|
||||
|
||||
/// Create an OmemoKeyPair just from a [type] and the bytes of the private and public
|
||||
/// key.
|
||||
factory OmemoKeyPair.fromBytes(List<int> publicKey, List<int> privateKey, KeyPairType type) {
|
||||
factory OmemoKeyPair.fromBytes(
|
||||
List<int> publicKey, List<int> privateKey, KeyPairType type,) {
|
||||
return OmemoKeyPair(
|
||||
OmemoPublicKey.fromBytes(
|
||||
publicKey,
|
||||
@@ -104,7 +110,8 @@ class OmemoKeyPair {
|
||||
/// Generate a completely new random OmemoKeyPair of type [type]. [type] must be either
|
||||
/// KeyPairType.ed25519 or KeyPairType.x25519.
|
||||
static Future<OmemoKeyPair> generateNewPair(KeyPairType type) async {
|
||||
assert(type == KeyPairType.ed25519 || type == KeyPairType.x25519, 'Keypair must be either Ed25519 or X25519');
|
||||
assert(type == KeyPairType.ed25519 || type == KeyPairType.x25519,
|
||||
'Keypair must be either Ed25519 or X25519',);
|
||||
|
||||
SimpleKeyPair kp;
|
||||
if (type == KeyPairType.ed25519) {
|
||||
@@ -119,7 +126,7 @@ class OmemoKeyPair {
|
||||
}
|
||||
|
||||
final kpd = await kp.extract();
|
||||
|
||||
|
||||
return OmemoKeyPair(
|
||||
OmemoPublicKey(await kp.extractPublicKey()),
|
||||
OmemoPrivateKey(await kpd.extractPrivateKeyBytes(), type),
|
||||
@@ -130,10 +137,11 @@ class OmemoKeyPair {
|
||||
final KeyPairType type;
|
||||
final OmemoPublicKey pk;
|
||||
final OmemoPrivateKey sk;
|
||||
|
||||
|
||||
/// Return the bytes that comprise the public key.
|
||||
Future<OmemoKeyPair> toCurve25519() async {
|
||||
assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 keypair to X25519');
|
||||
assert(type == KeyPairType.ed25519,
|
||||
'Cannot convert non-Ed25519 keypair to X25519',);
|
||||
|
||||
return OmemoKeyPair(
|
||||
await pk.toCurve25519(),
|
||||
@@ -153,7 +161,7 @@ class OmemoKeyPair {
|
||||
@visibleForTesting
|
||||
Future<bool> equals(OmemoKeyPair pair) async {
|
||||
return type == pair.type &&
|
||||
await pk.equals(pair.pk) &&
|
||||
await sk.equals(pair.sk);
|
||||
await pk.equals(pair.pk) &&
|
||||
await sk.equals(pair.sk);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'package:hex/hex.dart';
|
||||
import 'package:omemo_dart/src/keys.dart';
|
||||
|
||||
class OmemoBundle {
|
||||
|
||||
const OmemoBundle(
|
||||
this.jid,
|
||||
this.id,
|
||||
@@ -14,17 +13,23 @@ class OmemoBundle {
|
||||
this.ikEncoded,
|
||||
this.opksEncoded,
|
||||
);
|
||||
|
||||
/// The bare Jid the Bundle belongs to
|
||||
final String jid;
|
||||
|
||||
/// The device Id
|
||||
final int id;
|
||||
|
||||
/// The SPK but base64 encoded
|
||||
final String spkEncoded;
|
||||
final int spkId;
|
||||
|
||||
/// The SPK signature but base64 encoded
|
||||
final String spkSignatureEncoded;
|
||||
|
||||
/// The IK but base64 encoded
|
||||
final String ikEncoded;
|
||||
|
||||
/// The mapping of a OPK's id to the base64 encoded data
|
||||
final Map<int, String> opksEncoded;
|
||||
|
||||
|
||||
@@ -91,9 +91,10 @@ class OmemoDevice {
|
||||
opks,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Generate a completely new device, i.e. cryptographic identity.
|
||||
static Future<OmemoDevice> generateNewDevice(String jid, { int opkAmount = 100 }) async {
|
||||
static Future<OmemoDevice> generateNewDevice(String jid,
|
||||
{int opkAmount = 100,}) async {
|
||||
final id = generateRandom32BitNumber();
|
||||
final ik = await OmemoKeyPair.generateNewPair(KeyPairType.ed25519);
|
||||
final spk = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
|
||||
@@ -110,7 +111,7 @@ class OmemoDevice {
|
||||
|
||||
/// Our bare Jid
|
||||
final String jid;
|
||||
|
||||
|
||||
/// The device Id
|
||||
final int id;
|
||||
|
||||
@@ -119,13 +120,16 @@ class OmemoDevice {
|
||||
|
||||
/// The signed prekey...
|
||||
final OmemoKeyPair spk;
|
||||
|
||||
/// ...its Id, ...
|
||||
final int spkId;
|
||||
|
||||
/// ...and its signature
|
||||
final List<int> spkSignature;
|
||||
|
||||
/// The old Signed Prekey...
|
||||
final OmemoKeyPair? oldSpk;
|
||||
|
||||
/// ...and its Id
|
||||
final int? oldSpkId;
|
||||
|
||||
@@ -137,7 +141,7 @@ class OmemoDevice {
|
||||
@internal
|
||||
Future<OmemoDevice> replaceOnetimePrekey(int id) async {
|
||||
opks[id] = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
|
||||
|
||||
|
||||
return OmemoDevice(
|
||||
jid,
|
||||
this.id,
|
||||
@@ -188,7 +192,7 @@ class OmemoDevice {
|
||||
opks,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Converts this device into an OmemoBundle that could be used for publishing.
|
||||
Future<OmemoBundle> toBundle() async {
|
||||
final encodedOpks = <int, String>{};
|
||||
@@ -214,7 +218,7 @@ class OmemoDevice {
|
||||
final curveKey = await ik.pk.toCurve25519();
|
||||
return HEX.encode(await curveKey.getBytes());
|
||||
}
|
||||
|
||||
|
||||
/// Serialise the device information.
|
||||
Future<Map<String, dynamic>> toJson() async {
|
||||
/// Serialise the OPKs
|
||||
@@ -226,7 +230,7 @@ class OmemoDevice {
|
||||
'private': base64.encode(await entry.value.sk.getBytes()),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
'jid': jid,
|
||||
'id': id,
|
||||
@@ -251,7 +255,9 @@ class OmemoDevice {
|
||||
} else {
|
||||
for (final entry in opks.entries) {
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
final matches = await other.opks[entry.key]?.equals(entry.value) ?? false;
|
||||
final matches =
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
await other.opks[entry.key]?.equals(entry.value) ?? false;
|
||||
if (!matches) {
|
||||
opksMatch = false;
|
||||
}
|
||||
@@ -263,15 +269,18 @@ class OmemoDevice {
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
final spkMatch = await spk.equals(other.spk);
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
final oldSpkMatch = oldSpk != null ? await oldSpk!.equals(other.oldSpk!) : other.oldSpk == null;
|
||||
final oldSpkMatch = oldSpk != null
|
||||
// ignore: invalid_use_of_visible_for_testing_member
|
||||
? await oldSpk!.equals(other.oldSpk!)
|
||||
: other.oldSpk == null;
|
||||
return id == other.id &&
|
||||
ikMatch &&
|
||||
spkMatch &&
|
||||
oldSpkMatch &&
|
||||
jid == other.jid &&
|
||||
listsEqual(spkSignature, other.spkSignature) &&
|
||||
spkId == other.spkId &&
|
||||
oldSpkId == other.oldSpkId &&
|
||||
opksMatch;
|
||||
ikMatch &&
|
||||
spkMatch &&
|
||||
oldSpkMatch &&
|
||||
jid == other.jid &&
|
||||
listsEqual(spkSignature, other.spkSignature) &&
|
||||
spkId == other.spkId &&
|
||||
oldSpkId == other.oldSpkId &&
|
||||
opksMatch;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'package:meta/meta.dart';
|
||||
/// <keys /> header.
|
||||
@immutable
|
||||
class EncryptedKey {
|
||||
|
||||
const EncryptedKey(this.jid, this.rid, this.value, this.kex);
|
||||
final String jid;
|
||||
final int rid;
|
||||
|
||||
@@ -5,11 +5,12 @@ import 'package:omemo_dart/src/omemo/ratchet_map_key.dart';
|
||||
|
||||
@immutable
|
||||
class EncryptionResult {
|
||||
const EncryptionResult(this.ciphertext, this.encryptedKeys, this.deviceEncryptionErrors, this.jidEncryptionErrors);
|
||||
|
||||
const EncryptionResult(this.ciphertext, this.encryptedKeys,
|
||||
this.deviceEncryptionErrors, this.jidEncryptionErrors,);
|
||||
|
||||
/// The actual message that was encrypted.
|
||||
final List<int>? ciphertext;
|
||||
|
||||
|
||||
/// Mapping of the device Id to the key for decrypting ciphertext, encrypted
|
||||
/// for the ratchet with said device Id.
|
||||
final List<EncryptedKey> encryptedKeys;
|
||||
@@ -22,5 +23,7 @@ class EncryptionResult {
|
||||
|
||||
/// True if the encryption was a success. This means that we could encrypt for
|
||||
/// at least one ratchet.
|
||||
bool isSuccess(int numberOfRecipients) => encryptedKeys.isNotEmpty && jidEncryptionErrors.length < numberOfRecipients;
|
||||
bool isSuccess(int numberOfRecipients) =>
|
||||
encryptedKeys.isNotEmpty &&
|
||||
jidEncryptionErrors.length < numberOfRecipients;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@ abstract class OmemoEvent {}
|
||||
|
||||
/// Triggered when a ratchet has been modified
|
||||
class RatchetModifiedEvent extends OmemoEvent {
|
||||
RatchetModifiedEvent(this.jid, this.deviceId, this.ratchet, this.added, this.replaced);
|
||||
RatchetModifiedEvent(
|
||||
this.jid, this.deviceId, this.ratchet, this.added, this.replaced,);
|
||||
final String jid;
|
||||
final int deviceId;
|
||||
final OmemoDoubleRatchet ratchet;
|
||||
|
||||
@@ -9,8 +9,8 @@ class DeviceFingerprint {
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is DeviceFingerprint &&
|
||||
fingerprint == other.fingerprint &&
|
||||
deviceId == other.deviceId;
|
||||
fingerprint == other.fingerprint &&
|
||||
deviceId == other.deviceId;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -33,7 +33,8 @@ class _InternalDecryptionResult {
|
||||
this.ratchetCreated,
|
||||
this.ratchetReplaced,
|
||||
this.payload,
|
||||
) : assert(!ratchetCreated || !ratchetReplaced, 'Ratchet must be either replaced or created');
|
||||
) : assert(!ratchetCreated || !ratchetReplaced,
|
||||
'Ratchet must be either replaced or created',);
|
||||
final bool ratchetCreated;
|
||||
final bool ratchetReplaced;
|
||||
final String? payload;
|
||||
@@ -55,7 +56,8 @@ class OmemoManager {
|
||||
|
||||
/// Send an empty OMEMO:2 message using the encrypted payload @result to
|
||||
/// @recipientJid.
|
||||
final Future<void> Function(EncryptionResult result, String recipientJid) sendEmptyOmemoMessageImpl;
|
||||
final Future<void> Function(EncryptionResult result, String recipientJid)
|
||||
sendEmptyOmemoMessageImpl;
|
||||
|
||||
/// Fetch the list of device ids associated with @jid. If the device list cannot be
|
||||
/// fetched, return null.
|
||||
@@ -66,16 +68,20 @@ class OmemoManager {
|
||||
|
||||
/// Subscribe to the device list PEP node of @jid.
|
||||
final Future<void> Function(String jid) subscribeToDeviceListNodeImpl;
|
||||
|
||||
|
||||
/// Map bare JID to its known devices
|
||||
Map<String, List<int>> _deviceList = {};
|
||||
|
||||
/// Map bare JIDs to whether we already requested the device list once
|
||||
final Map<String, bool> _deviceListRequested = {};
|
||||
|
||||
/// Map bare a ratchet key to its ratchet. Note that this is also locked by
|
||||
/// _ratchetCriticalSectionLock.
|
||||
Map<RatchetMapKey, OmemoDoubleRatchet> _ratchetMap = {};
|
||||
|
||||
/// Map bare JID to whether we already tried to subscribe to the device list node.
|
||||
final Map<String, bool> _subscriptionMap = {};
|
||||
|
||||
/// For preventing a race condition in encryption/decryption
|
||||
final Map<String, Queue<Completer<void>>> _ratchetCriticalSectionQueue = {};
|
||||
final Lock _ratchetCriticalSectionLock = Lock();
|
||||
@@ -83,14 +89,15 @@ class OmemoManager {
|
||||
/// The OmemoManager's trust management
|
||||
final TrustManager _trustManager;
|
||||
TrustManager get trustManager => _trustManager;
|
||||
|
||||
|
||||
/// Our own keys...
|
||||
final Lock _deviceLock = Lock();
|
||||
// ignore: prefer_final_fields
|
||||
OmemoDevice _device;
|
||||
|
||||
|
||||
/// The event bus of the session manager
|
||||
final StreamController<OmemoEvent> _eventStreamController = StreamController<OmemoEvent>.broadcast();
|
||||
final StreamController<OmemoEvent> _eventStreamController =
|
||||
StreamController<OmemoEvent>.broadcast();
|
||||
Stream<OmemoEvent> get eventStream => _eventStreamController.stream;
|
||||
|
||||
/// Enter the critical section for performing cryptographic operations on the ratchets
|
||||
@@ -110,7 +117,7 @@ class OmemoManager {
|
||||
await completer.future;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Leave the critical section for the ratchets.
|
||||
Future<void> _leaveRatchetCriticalSection(String jid) async {
|
||||
await _ratchetCriticalSectionLock.synchronized(() {
|
||||
@@ -124,22 +131,25 @@ class OmemoManager {
|
||||
});
|
||||
}
|
||||
|
||||
Future<String?> _decryptAndVerifyHmac(List<int>? ciphertext, List<int> keyAndHmac) async {
|
||||
Future<String?> _decryptAndVerifyHmac(
|
||||
List<int>? ciphertext, List<int> keyAndHmac,) async {
|
||||
// Empty OMEMO messages should just have the key decrypted and/or session set up.
|
||||
if (ciphertext == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
final key = keyAndHmac.sublist(0, 32);
|
||||
final hmac = keyAndHmac.sublist(32, 48);
|
||||
final derivedKeys = await deriveEncryptionKeys(key, omemoPayloadInfoString);
|
||||
final computedHmac = await truncatedHmac(ciphertext, derivedKeys.authenticationKey);
|
||||
final computedHmac =
|
||||
await truncatedHmac(ciphertext, derivedKeys.authenticationKey);
|
||||
if (!listsEqual(hmac, computedHmac)) {
|
||||
throw InvalidMessageHMACException();
|
||||
}
|
||||
|
||||
|
||||
return utf8.decode(
|
||||
await aes256CbcDecrypt(ciphertext, derivedKeys.encryptionKey, derivedKeys.iv),
|
||||
await aes256CbcDecrypt(
|
||||
ciphertext, derivedKeys.encryptionKey, derivedKeys.iv,),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -167,13 +177,15 @@ class OmemoManager {
|
||||
_ratchetMap[key] = ratchet;
|
||||
|
||||
// Commit the ratchet
|
||||
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, true, false));
|
||||
_eventStreamController
|
||||
.add(RatchetModifiedEvent(jid, deviceId, ratchet, true, false));
|
||||
}
|
||||
|
||||
/// Build a new session with the user at [jid] with the device [deviceId] using data
|
||||
/// from the key exchange [kex]. In case [kex] contains an unknown Signed Prekey
|
||||
/// identifier an UnknownSignedPrekeyException will be thrown.
|
||||
Future<OmemoDoubleRatchet> _addSessionFromKeyExchange(String jid, int deviceId, OmemoKeyExchange kex) async {
|
||||
Future<OmemoDoubleRatchet> _addSessionFromKeyExchange(
|
||||
String jid, int deviceId, OmemoKeyExchange kex,) async {
|
||||
// Pick the correct SPK
|
||||
final device = await getDevice();
|
||||
OmemoKeyPair spk;
|
||||
@@ -212,7 +224,8 @@ class OmemoManager {
|
||||
/// Create a ratchet session initiated by Alice to the user with Jid [jid] and the device
|
||||
/// [deviceId] from the bundle [bundle].
|
||||
@visibleForTesting
|
||||
Future<OmemoKeyExchange> addSessionFromBundle(String jid, int deviceId, OmemoBundle bundle) async {
|
||||
Future<OmemoKeyExchange> addSessionFromBundle(
|
||||
String jid, int deviceId, OmemoBundle bundle,) async {
|
||||
final device = await getDevice();
|
||||
final kexResult = await x3dhFromBundle(
|
||||
bundle,
|
||||
@@ -235,13 +248,14 @@ class OmemoManager {
|
||||
..ik = await device.ik.pk.getBytes()
|
||||
..ek = await kexResult.ek.pk.getBytes();
|
||||
}
|
||||
|
||||
|
||||
/// In case a decryption error occurs, the Double Ratchet spec says to just restore
|
||||
/// the ratchet to its old state. As such, this function restores the ratchet at
|
||||
/// [mapKey] with [oldRatchet].
|
||||
/// NOTE: Must be called from within the ratchet critical section
|
||||
void _restoreRatchet(RatchetMapKey mapKey, OmemoDoubleRatchet oldRatchet) {
|
||||
_log.finest('Restoring ratchet ${mapKey.jid}:${mapKey.deviceId} to ${oldRatchet.nr}');
|
||||
_log.finest(
|
||||
'Restoring ratchet ${mapKey.jid}:${mapKey.deviceId} to ${oldRatchet.nr}',);
|
||||
_ratchetMap[mapKey] = oldRatchet;
|
||||
|
||||
// Commit the ratchet
|
||||
@@ -255,7 +269,7 @@ class OmemoManager {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/// Attempt to decrypt [ciphertext]. [keys] refers to the <key /> elements inside the
|
||||
/// <keys /> element with a "jid" attribute matching our own. [senderJid] refers to the
|
||||
/// bare Jid of the sender. [senderDeviceId] refers to the "sid" attribute of the
|
||||
@@ -268,14 +282,19 @@ class OmemoManager {
|
||||
/// element, then [ciphertext] must be set to null. In this case, this function
|
||||
/// will return null as there is no message to be decrypted. This, however, is used
|
||||
/// to set up sessions or advance the ratchets.
|
||||
Future<_InternalDecryptionResult> _decryptMessage(List<int>? ciphertext, String senderJid, int senderDeviceId, List<EncryptedKey> keys, int timestamp) async {
|
||||
Future<_InternalDecryptionResult> _decryptMessage(
|
||||
List<int>? ciphertext,
|
||||
String senderJid,
|
||||
int senderDeviceId,
|
||||
List<EncryptedKey> keys,
|
||||
int timestamp,) async {
|
||||
// Try to find a session we can decrypt with.
|
||||
var device = await getDevice();
|
||||
final rawKey = keys.firstWhereOrNull((key) => key.rid == device.id);
|
||||
if (rawKey == null) {
|
||||
throw NotEncryptedForDeviceException();
|
||||
}
|
||||
|
||||
|
||||
final decodedRawKey = base64.decode(rawKey.value);
|
||||
List<int>? keyAndHmac;
|
||||
OmemoAuthenticatedMessage authMessage;
|
||||
@@ -292,17 +311,20 @@ class OmemoManager {
|
||||
|
||||
// Guard against old key exchanges
|
||||
if (oldRatchet != null) {
|
||||
_log.finest('KEX for existent ratchet ${ratchetKey.toJsonKey()}. ${oldRatchet.kexTimestamp} > $timestamp: ${oldRatchet.kexTimestamp > timestamp}');
|
||||
_log.finest(
|
||||
'KEX for existent ratchet ${ratchetKey.toJsonKey()}. ${oldRatchet.kexTimestamp} > $timestamp: ${oldRatchet.kexTimestamp > timestamp}',);
|
||||
if (oldRatchet.kexTimestamp > timestamp) {
|
||||
throw InvalidKeyExchangeException();
|
||||
}
|
||||
}
|
||||
|
||||
final r = await _addSessionFromKeyExchange(senderJid, senderDeviceId, kex);
|
||||
final r =
|
||||
await _addSessionFromKeyExchange(senderJid, senderDeviceId, kex);
|
||||
|
||||
// Try to decrypt with the new ratchet r
|
||||
try {
|
||||
keyAndHmac = await r.ratchetDecrypt(message, authMessage.writeToBuffer());
|
||||
keyAndHmac =
|
||||
await r.ratchetDecrypt(message, authMessage.writeToBuffer());
|
||||
final result = await _decryptAndVerifyHmac(ciphertext, keyAndHmac);
|
||||
|
||||
// Add the new ratchet
|
||||
@@ -339,20 +361,21 @@ class OmemoManager {
|
||||
authMessage = OmemoAuthenticatedMessage.fromBuffer(decodedRawKey);
|
||||
message = OmemoMessage.fromBuffer(authMessage.message!);
|
||||
}
|
||||
|
||||
|
||||
final devices = _deviceList[senderJid];
|
||||
if (devices?.contains(senderDeviceId) != true) {
|
||||
throw NoDecryptionKeyException();
|
||||
}
|
||||
|
||||
// TODO(PapaTutuWawa): When receiving a message that is not an OMEMOKeyExchange from a device there is no session with, clients SHOULD create a session with that device and notify it about the new session by responding with an empty OMEMO message as per Sending a message.
|
||||
|
||||
|
||||
// We can guarantee that the ratchet exists at this point in time
|
||||
final ratchet = getRatchet(ratchetKey)!;
|
||||
|
||||
try {
|
||||
if (rawKey.kex) {
|
||||
keyAndHmac = await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer());
|
||||
keyAndHmac =
|
||||
await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer());
|
||||
} else {
|
||||
keyAndHmac = await ratchet.ratchetDecrypt(message, decodedRawKey);
|
||||
}
|
||||
@@ -378,7 +401,7 @@ class OmemoManager {
|
||||
false,
|
||||
await _decryptAndVerifyHmac(ciphertext, keyAndHmac),
|
||||
);
|
||||
} catch (_) {
|
||||
} catch (_) {
|
||||
_restoreRatchet(ratchetKey, oldRatchet!);
|
||||
rethrow;
|
||||
}
|
||||
@@ -393,25 +416,25 @@ class OmemoManager {
|
||||
Future<List<OmemoBundle>> _fetchNewBundles(String jid) async {
|
||||
// Check if we already requested the device list for [jid]
|
||||
List<int> bundlesToFetch;
|
||||
if (!_deviceListRequested.containsKey(jid) || !_deviceList.containsKey(jid)) {
|
||||
if (!_deviceListRequested.containsKey(jid) ||
|
||||
!_deviceList.containsKey(jid)) {
|
||||
// We don't have an up-to-date version of the device list
|
||||
final newDeviceList = await fetchDeviceListImpl(jid);
|
||||
if (newDeviceList == null) return [];
|
||||
|
||||
_deviceList[jid] = newDeviceList;
|
||||
bundlesToFetch = newDeviceList
|
||||
.where((id) {
|
||||
return !_ratchetMap.containsKey(RatchetMapKey(jid, id)) ||
|
||||
_deviceList[jid]?.contains(id) == false;
|
||||
}).toList();
|
||||
bundlesToFetch = newDeviceList.where((id) {
|
||||
return !_ratchetMap.containsKey(RatchetMapKey(jid, id)) ||
|
||||
_deviceList[jid]?.contains(id) == false;
|
||||
}).toList();
|
||||
|
||||
// Trigger an event with the new device list
|
||||
_eventStreamController.add(DeviceListModifiedEvent(_deviceList));
|
||||
} else {
|
||||
// We already have an up-to-date version of the device list
|
||||
bundlesToFetch = _deviceList[jid]!
|
||||
.where((id) => !_ratchetMap.containsKey(RatchetMapKey(jid, id)))
|
||||
.toList();
|
||||
.where((id) => !_ratchetMap.containsKey(RatchetMapKey(jid, id)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (bundlesToFetch.isNotEmpty) {
|
||||
@@ -429,7 +452,7 @@ class OmemoManager {
|
||||
|
||||
return newBundles;
|
||||
}
|
||||
|
||||
|
||||
/// Encrypt the key [plaintext] for all known bundles of the Jids in [jids]. Returns a
|
||||
/// map that maps the device Id to the ciphertext of [plaintext].
|
||||
///
|
||||
@@ -437,7 +460,8 @@ class OmemoManager {
|
||||
/// does not contain a <payload /> element. This means that the ciphertext attribute of
|
||||
/// the result will be null as well.
|
||||
/// NOTE: Must be called within the ratchet critical section
|
||||
Future<EncryptionResult> _encryptToJids(List<String> jids, String? plaintext) async {
|
||||
Future<EncryptionResult> _encryptToJids(
|
||||
List<String> jids, String? plaintext,) async {
|
||||
final encryptedKeys = List<EncryptedKey>.empty(growable: true);
|
||||
|
||||
var ciphertext = const <int>[];
|
||||
@@ -498,12 +522,14 @@ class OmemoManager {
|
||||
var ratchet = _ratchetMap[ratchetKey];
|
||||
if (ratchet == null) {
|
||||
_log.severe('Ratchet ${ratchetKey.toJsonKey()} does not exist.');
|
||||
deviceEncryptionErrors[ratchetKey] = NoKeyMaterialAvailableException();
|
||||
deviceEncryptionErrors[ratchetKey] =
|
||||
NoKeyMaterialAvailableException();
|
||||
continue;
|
||||
}
|
||||
|
||||
final ciphertext = (await ratchet.ratchetEncrypt(keyPayload)).ciphertext;
|
||||
|
||||
final ciphertext =
|
||||
(await ratchet.ratchetEncrypt(keyPayload)).ciphertext;
|
||||
|
||||
if (kex.containsKey(ratchetKey)) {
|
||||
// The ratchet did not exist
|
||||
final k = kex[ratchetKey]!
|
||||
@@ -523,9 +549,10 @@ class OmemoManager {
|
||||
} else if (!ratchet.acknowledged) {
|
||||
// The ratchet exists but is not acked
|
||||
if (ratchet.kex != null) {
|
||||
final oldKex = OmemoKeyExchange.fromBuffer(base64.decode(ratchet.kex!))
|
||||
..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
|
||||
|
||||
final oldKex =
|
||||
OmemoKeyExchange.fromBuffer(base64.decode(ratchet.kex!))
|
||||
..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
|
||||
|
||||
encryptedKeys.add(
|
||||
EncryptedKey(
|
||||
jid,
|
||||
@@ -536,7 +563,8 @@ class OmemoManager {
|
||||
);
|
||||
} else {
|
||||
// The ratchet is not acked but we don't have the old key exchange
|
||||
_log.warning('Ratchet for $jid:$deviceId is not acked but the kex attribute is null');
|
||||
_log.warning(
|
||||
'Ratchet for $jid:$deviceId is not acked but the kex attribute is null',);
|
||||
encryptedKeys.add(
|
||||
EncryptedKey(
|
||||
jid,
|
||||
@@ -559,13 +587,13 @@ class OmemoManager {
|
||||
}
|
||||
|
||||
// Commit the ratchet
|
||||
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
|
||||
_eventStreamController
|
||||
.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
|
||||
}
|
||||
}
|
||||
|
||||
return EncryptionResult(
|
||||
plaintext != null ?
|
||||
ciphertext : null,
|
||||
plaintext != null ? ciphertext : null,
|
||||
encryptedKeys,
|
||||
deviceEncryptionErrors,
|
||||
jidEncryptionErrors,
|
||||
@@ -581,14 +609,13 @@ class OmemoManager {
|
||||
unawaited(subscribeToDeviceListNodeImpl(stanza.bareSenderJid));
|
||||
_subscriptionMap[stanza.bareSenderJid] = true;
|
||||
}
|
||||
|
||||
final ratchetKey = RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId);
|
||||
|
||||
final ratchetKey =
|
||||
RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId);
|
||||
final _InternalDecryptionResult result;
|
||||
try {
|
||||
result = await _decryptMessage(
|
||||
stanza.payload != null ?
|
||||
base64.decode(stanza.payload!) :
|
||||
null,
|
||||
stanza.payload != null ? base64.decode(stanza.payload!) : null,
|
||||
stanza.bareSenderJid,
|
||||
stanza.senderDeviceId,
|
||||
stanza.keys,
|
||||
@@ -604,7 +631,8 @@ class OmemoManager {
|
||||
|
||||
// Check if the ratchet is acked
|
||||
final ratchet = getRatchet(ratchetKey);
|
||||
assert(ratchet != null, 'We decrypted the message, so the ratchet must exist');
|
||||
assert(
|
||||
ratchet != null, 'We decrypted the message, so the ratchet must exist',);
|
||||
|
||||
if (ratchet!.acknowledged) {
|
||||
// Ratchet is acknowledged
|
||||
@@ -674,20 +702,22 @@ class OmemoManager {
|
||||
);
|
||||
await sendEmptyOmemoMessageImpl(result, jid);
|
||||
}
|
||||
|
||||
|
||||
/// Mark the ratchet for device [deviceId] from [jid] as acked.
|
||||
Future<void> ratchetAcknowledged(String jid, int deviceId, { bool enterCriticalSection = true }) async {
|
||||
Future<void> ratchetAcknowledged(String jid, int deviceId,
|
||||
{bool enterCriticalSection = true,}) async {
|
||||
if (enterCriticalSection) await _enterRatchetCriticalSection(jid);
|
||||
|
||||
final key = RatchetMapKey(jid, deviceId);
|
||||
if (_ratchetMap.containsKey(key)) {
|
||||
final ratchet = _ratchetMap[key]!
|
||||
..acknowledged = true;
|
||||
final ratchet = _ratchetMap[key]!..acknowledged = true;
|
||||
|
||||
// Commit it
|
||||
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
|
||||
_eventStreamController
|
||||
.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
|
||||
} else {
|
||||
_log.severe('Attempted to acknowledge ratchet ${key.toJsonKey()}, even though it does not exist');
|
||||
_log.severe(
|
||||
'Attempted to acknowledge ratchet ${key.toJsonKey()}, even though it does not exist',);
|
||||
}
|
||||
|
||||
if (enterCriticalSection) await _leaveRatchetCriticalSection(jid);
|
||||
@@ -703,7 +733,7 @@ class OmemoManager {
|
||||
_eventStreamController.add(DeviceModifiedEvent(_device));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/// Returns the device used for encryption and decryption.
|
||||
Future<OmemoDevice> getDevice() => _deviceLock.synchronized(() => _device);
|
||||
|
||||
@@ -714,18 +744,19 @@ class OmemoManager {
|
||||
Future<OmemoBundle> getDeviceBundle() async => (await getDevice()).toBundle();
|
||||
|
||||
/// Directly aquire the current device's fingerprint.
|
||||
Future<String> getDeviceFingerprint() async => (await getDevice()).getFingerprint();
|
||||
|
||||
Future<String> getDeviceFingerprint() async =>
|
||||
(await getDevice()).getFingerprint();
|
||||
|
||||
/// Returns the fingerprints for all devices of [jid] that we have a session with.
|
||||
/// If there are not sessions with [jid], then returns null.
|
||||
Future<List<DeviceFingerprint>?> getFingerprintsForJid(String jid) async {
|
||||
if (!_deviceList.containsKey(jid)) return null;
|
||||
|
||||
await _enterRatchetCriticalSection(jid);
|
||||
|
||||
|
||||
final fingerprintKeys = _deviceList[jid]!
|
||||
.map((id) => RatchetMapKey(jid, id))
|
||||
.where((key) => _ratchetMap.containsKey(key));
|
||||
.map((id) => RatchetMapKey(jid, id))
|
||||
.where((key) => _ratchetMap.containsKey(key));
|
||||
|
||||
final fingerprints = List<DeviceFingerprint>.empty(growable: true);
|
||||
for (final key in fingerprintKeys) {
|
||||
@@ -741,7 +772,7 @@ class OmemoManager {
|
||||
await _leaveRatchetCriticalSection(jid);
|
||||
return fingerprints;
|
||||
}
|
||||
|
||||
|
||||
/// Ensures that the device list is fetched again on the next message sending.
|
||||
void onNewConnection() {
|
||||
_deviceListRequested.clear();
|
||||
@@ -757,7 +788,8 @@ class OmemoManager {
|
||||
_eventStreamController.add(DeviceListModifiedEvent(_deviceList));
|
||||
}
|
||||
|
||||
void initialize(Map<RatchetMapKey, OmemoDoubleRatchet> ratchetMap, Map<String, List<int>> deviceList) {
|
||||
void initialize(Map<RatchetMapKey, OmemoDoubleRatchet> ratchetMap,
|
||||
Map<String, List<int>> deviceList,) {
|
||||
_deviceList = deviceList;
|
||||
_ratchetMap = ratchetMap;
|
||||
}
|
||||
@@ -782,7 +814,7 @@ class OmemoManager {
|
||||
|
||||
// Remove trust decisions
|
||||
await _trustManager.removeTrustDecisionsForJid(jid);
|
||||
|
||||
|
||||
await _leaveRatchetCriticalSection(jid);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,10 +20,12 @@ class RatchetMapKey {
|
||||
String toJsonKey() {
|
||||
return '$deviceId:$jid';
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is RatchetMapKey && jid == other.jid && deviceId == other.deviceId;
|
||||
return other is RatchetMapKey &&
|
||||
jid == other.jid &&
|
||||
deviceId == other.deviceId;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -2,12 +2,11 @@ import 'package:omemo_dart/src/helpers.dart';
|
||||
import 'package:omemo_dart/src/protobuf/protobuf.dart';
|
||||
|
||||
class OmemoAuthenticatedMessage {
|
||||
|
||||
OmemoAuthenticatedMessage();
|
||||
|
||||
factory OmemoAuthenticatedMessage.fromBuffer(List<int> data) {
|
||||
var i = 0;
|
||||
|
||||
|
||||
// required bytes mac = 1;
|
||||
if (data[0] != fieldId(1, fieldTypeByteArray)) {
|
||||
throw Exception();
|
||||
@@ -24,7 +23,7 @@ class OmemoAuthenticatedMessage {
|
||||
..mac = mac
|
||||
..message = message;
|
||||
}
|
||||
|
||||
|
||||
List<int>? mac;
|
||||
List<int>? message;
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ class OmemoKeyExchange {
|
||||
..ek = ek
|
||||
..message = message;
|
||||
}
|
||||
|
||||
|
||||
int? pkId;
|
||||
int? spkId;
|
||||
List<int>? ik;
|
||||
|
||||
@@ -2,12 +2,11 @@ import 'package:omemo_dart/src/helpers.dart';
|
||||
import 'package:omemo_dart/src/protobuf/protobuf.dart';
|
||||
|
||||
class OmemoMessage {
|
||||
|
||||
OmemoMessage();
|
||||
|
||||
factory OmemoMessage.fromBuffer(List<int> data) {
|
||||
var i = 0;
|
||||
|
||||
|
||||
// required uint32 n = 1;
|
||||
if (data[0] != fieldId(1, fieldTypeUint32)) {
|
||||
throw Exception();
|
||||
|
||||
@@ -13,7 +13,6 @@ int fieldId(int number, int type) {
|
||||
}
|
||||
|
||||
class VarintDecode {
|
||||
|
||||
const VarintDecode(this.n, this.length);
|
||||
final int n;
|
||||
final int length;
|
||||
|
||||
@@ -18,9 +18,9 @@ class AlwaysTrustingTrustManager extends TrustManager {
|
||||
@override
|
||||
Future<void> setEnabled(String jid, int deviceId, bool enabled) async {}
|
||||
|
||||
@override
|
||||
@override
|
||||
Future<void> removeTrustDecisionsForJid(String jid) async {}
|
||||
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> toJson() async => <String, dynamic>{};
|
||||
}
|
||||
|
||||
@@ -10,23 +10,30 @@ import 'package:synchronized/synchronized.dart';
|
||||
enum BTBVTrustState {
|
||||
notTrusted, // = 1
|
||||
blindTrust, // = 2
|
||||
verified, // = 3
|
||||
verified, // = 3
|
||||
}
|
||||
|
||||
int _trustToInt(BTBVTrustState state) {
|
||||
switch (state) {
|
||||
case BTBVTrustState.notTrusted: return 1;
|
||||
case BTBVTrustState.blindTrust: return 2;
|
||||
case BTBVTrustState.verified: return 3;
|
||||
case BTBVTrustState.notTrusted:
|
||||
return 1;
|
||||
case BTBVTrustState.blindTrust:
|
||||
return 2;
|
||||
case BTBVTrustState.verified:
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
BTBVTrustState _trustFromInt(int i) {
|
||||
switch (i) {
|
||||
case 1: return BTBVTrustState.notTrusted;
|
||||
case 2: return BTBVTrustState.blindTrust;
|
||||
case 3: return BTBVTrustState.verified;
|
||||
default: return BTBVTrustState.notTrusted;
|
||||
case 1:
|
||||
return BTBVTrustState.notTrusted;
|
||||
case 2:
|
||||
return BTBVTrustState.blindTrust;
|
||||
case 3:
|
||||
return BTBVTrustState.verified;
|
||||
default:
|
||||
return BTBVTrustState.notTrusted;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,10 +44,10 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
Map<RatchetMapKey, BTBVTrustState>? trustCache,
|
||||
Map<RatchetMapKey, bool>? enablementCache,
|
||||
Map<String, List<int>>? devices,
|
||||
}) : trustCache = trustCache ?? {},
|
||||
enablementCache = enablementCache ?? {},
|
||||
devices = devices ?? {},
|
||||
_lock = Lock();
|
||||
}) : trustCache = trustCache ?? {},
|
||||
enablementCache = enablementCache ?? {},
|
||||
devices = devices ?? {},
|
||||
_lock = Lock();
|
||||
|
||||
/// The cache for mapping a RatchetMapKey to its trust state
|
||||
@visibleForTesting
|
||||
@@ -51,7 +58,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
@visibleForTesting
|
||||
@protected
|
||||
final Map<RatchetMapKey, bool> enablementCache;
|
||||
|
||||
|
||||
/// Mapping of Jids to their device identifiers
|
||||
@visibleForTesting
|
||||
@protected
|
||||
@@ -70,7 +77,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
return trustCache[RatchetMapKey(jid, id)]! == BTBVTrustState.verified;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Future<bool> isTrusted(String jid, int deviceId) async {
|
||||
var returnValue = false;
|
||||
@@ -116,12 +123,12 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
} else {
|
||||
devices[jid] = List<int>.from([deviceId]);
|
||||
}
|
||||
|
||||
|
||||
// Commit the state
|
||||
await commitState();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/// Returns a mapping from the device identifiers of [jid] to their trust state. If
|
||||
/// there are no devices known for [jid], then an empty map is returned.
|
||||
Future<Map<int, BTBVTrustState>> getDevicesTrust(String jid) async {
|
||||
@@ -129,7 +136,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
final map = <int, BTBVTrustState>{};
|
||||
|
||||
if (!devices.containsKey(jid)) return map;
|
||||
|
||||
|
||||
for (final deviceId in devices[jid]!) {
|
||||
map[deviceId] = trustCache[RatchetMapKey(jid, deviceId)]!;
|
||||
}
|
||||
@@ -139,7 +146,8 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
}
|
||||
|
||||
/// Sets the trust of [jid]'s device with identifier [deviceId] to [state].
|
||||
Future<void> setDeviceTrust(String jid, int deviceId, BTBVTrustState state) async {
|
||||
Future<void> setDeviceTrust(
|
||||
String jid, int deviceId, BTBVTrustState state,) async {
|
||||
await _lock.synchronized(() async {
|
||||
trustCache[RatchetMapKey(jid, deviceId)] = state;
|
||||
|
||||
@@ -172,10 +180,14 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
Future<Map<String, dynamic>> toJson() async {
|
||||
return {
|
||||
'devices': devices,
|
||||
'trust': trustCache.map((key, value) => MapEntry(
|
||||
key.toJsonKey(), _trustToInt(value),
|
||||
),),
|
||||
'enable': enablementCache.map((key, value) => MapEntry(key.toJsonKey(), value)),
|
||||
'trust': trustCache.map(
|
||||
(key, value) => MapEntry(
|
||||
key.toJsonKey(),
|
||||
_trustToInt(value),
|
||||
),
|
||||
),
|
||||
'enable':
|
||||
enablementCache.map((key, value) => MapEntry(key.toJsonKey(), value)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -192,8 +204,10 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
|
||||
/// From a serialized version of a BTBV trust manager, extract the trust cache.
|
||||
/// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on.
|
||||
static Map<RatchetMapKey, BTBVTrustState> trustCacheFromJson(Map<String, dynamic> json) {
|
||||
return (json['trust']! as Map<String, dynamic>).map<RatchetMapKey, BTBVTrustState>(
|
||||
static Map<RatchetMapKey, BTBVTrustState> trustCacheFromJson(
|
||||
Map<String, dynamic> json,) {
|
||||
return (json['trust']! as Map<String, dynamic>)
|
||||
.map<RatchetMapKey, BTBVTrustState>(
|
||||
(key, value) => MapEntry(
|
||||
RatchetMapKey.fromJsonKey(key),
|
||||
_trustFromInt(value as int),
|
||||
@@ -203,7 +217,8 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
|
||||
/// From a serialized version of a BTBV trust manager, extract the enable cache.
|
||||
/// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on.
|
||||
static Map<RatchetMapKey, bool> enableCacheFromJson(Map<String, dynamic> json) {
|
||||
static Map<RatchetMapKey, bool> enableCacheFromJson(
|
||||
Map<String, dynamic> json,) {
|
||||
return (json['enable']! as Map<String, dynamic>).map<RatchetMapKey, bool>(
|
||||
(key, value) => MapEntry(
|
||||
RatchetMapKey.fromJsonKey(key),
|
||||
@@ -212,21 +227,22 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
@override
|
||||
Future<void> removeTrustDecisionsForJid(String jid) async {
|
||||
await _lock.synchronized(() async {
|
||||
devices.remove(jid);
|
||||
await commitState();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/// Called when the state of the trust manager has been changed. Allows the user to
|
||||
/// commit the trust state to persistent storage.
|
||||
@visibleForOverriding
|
||||
Future<void> commitState();
|
||||
|
||||
@visibleForTesting
|
||||
BTBVTrustState getDeviceTrust(String jid, int deviceId) => trustCache[RatchetMapKey(jid, deviceId)]!;
|
||||
BTBVTrustState getDeviceTrust(String jid, int deviceId) =>
|
||||
trustCache[RatchetMapKey(jid, deviceId)]!;
|
||||
}
|
||||
|
||||
/// A BTBV TrustManager that does not commit its state to persistent storage. Well suited
|
||||
|
||||
@@ -18,7 +18,7 @@ class NeverTrustingTrustManager extends TrustManager {
|
||||
@override
|
||||
Future<void> setEnabled(String jid, int deviceId, bool enabled) async {}
|
||||
|
||||
@override
|
||||
@override
|
||||
Future<void> removeTrustDecisionsForJid(String jid) async {}
|
||||
|
||||
@override
|
||||
|
||||
@@ -12,7 +12,6 @@ const omemoX3DHInfoString = 'OMEMO X3DH';
|
||||
|
||||
/// Performed by Alice
|
||||
class X3DHAliceResult {
|
||||
|
||||
const X3DHAliceResult(this.ek, this.sk, this.opkId, this.ad);
|
||||
final OmemoKeyPair ek;
|
||||
final List<int> sk;
|
||||
@@ -22,7 +21,6 @@ class X3DHAliceResult {
|
||||
|
||||
/// Received by Bob
|
||||
class X3DHMessage {
|
||||
|
||||
const X3DHMessage(this.ik, this.ek, this.opkId);
|
||||
final OmemoPublicKey ik;
|
||||
final OmemoPublicKey ek;
|
||||
@@ -30,7 +28,6 @@ class X3DHMessage {
|
||||
}
|
||||
|
||||
class X3DHBobResult {
|
||||
|
||||
const X3DHBobResult(this.sk, this.ad);
|
||||
final List<int> sk;
|
||||
final List<int> ad;
|
||||
@@ -39,7 +36,8 @@ class X3DHBobResult {
|
||||
/// Sign [message] using the keypair [keyPair]. Note that [keyPair] must be
|
||||
/// a Ed25519 keypair.
|
||||
Future<List<int>> sig(OmemoKeyPair keyPair, List<int> message) async {
|
||||
assert(keyPair.type == KeyPairType.ed25519, 'Signature keypair must be Ed25519');
|
||||
assert(
|
||||
keyPair.type == KeyPairType.ed25519, 'Signature keypair must be Ed25519',);
|
||||
final signature = await Ed25519().sign(
|
||||
message,
|
||||
keyPair: await keyPair.asKeyPair(),
|
||||
@@ -70,7 +68,8 @@ Future<List<int>> kdf(List<int> km) async {
|
||||
|
||||
/// Alice builds a session with Bob using his bundle [bundle] and Alice's identity key
|
||||
/// pair [ik].
|
||||
Future<X3DHAliceResult> x3dhFromBundle(OmemoBundle bundle, OmemoKeyPair ik) async {
|
||||
Future<X3DHAliceResult> x3dhFromBundle(
|
||||
OmemoBundle bundle, OmemoKeyPair ik,) async {
|
||||
// Check the signature first
|
||||
final signatureValue = await Ed25519().verify(
|
||||
await bundle.spk.getBytes(),
|
||||
@@ -91,9 +90,9 @@ Future<X3DHAliceResult> x3dhFromBundle(OmemoBundle bundle, OmemoKeyPair ik) asyn
|
||||
final opkIndex = random.nextInt(bundle.opksEncoded.length);
|
||||
final opkId = bundle.opksEncoded.keys.elementAt(opkIndex);
|
||||
final opk = bundle.getOpk(opkId);
|
||||
|
||||
|
||||
final dh1 = await omemoDH(ik, bundle.spk, 1);
|
||||
final dh2 = await omemoDH(ek, bundle.ik, 2);
|
||||
final dh2 = await omemoDH(ek, bundle.ik, 2);
|
||||
final dh3 = await omemoDH(ek, bundle.spk, 0);
|
||||
final dh4 = await omemoDH(ek, opk, 0);
|
||||
|
||||
@@ -108,9 +107,10 @@ Future<X3DHAliceResult> x3dhFromBundle(OmemoBundle bundle, OmemoKeyPair ik) asyn
|
||||
|
||||
/// Bob builds the X3DH shared secret from the inital message [msg], the SPK [spk], the
|
||||
/// OPK [opk] that was selected by Alice and our IK [ik]. Returns the shared secret.
|
||||
Future<X3DHBobResult> x3dhFromInitialMessage(X3DHMessage msg, OmemoKeyPair spk, OmemoKeyPair opk, OmemoKeyPair ik) async {
|
||||
Future<X3DHBobResult> x3dhFromInitialMessage(X3DHMessage msg, OmemoKeyPair spk,
|
||||
OmemoKeyPair opk, OmemoKeyPair ik,) async {
|
||||
final dh1 = await omemoDH(spk, msg.ik, 2);
|
||||
final dh2 = await omemoDH(ik, msg.ek, 1);
|
||||
final dh2 = await omemoDH(ik, msg.ek, 1);
|
||||
final dh3 = await omemoDH(spk, msg.ek, 0);
|
||||
final dh4 = await omemoDH(opk, msg.ek, 0);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user