feat: Allow serialising Device to Json
This commit is contained in:
@@ -12,6 +12,56 @@ class Device {
|
||||
|
||||
const Device(this.id, this.ik, this.spk, this.spkId, this.spkSignature, this.opks);
|
||||
|
||||
/// Deserialize the Device
|
||||
factory Device.fromJson(Map<String, dynamic> data) {
|
||||
// NOTE: We use the way OpenSSH names their keys, meaning that ik is the Identity
|
||||
// Keypair's private key, while ik_pub refers to the Identity Keypair's public
|
||||
// key.
|
||||
/*
|
||||
{
|
||||
'id': 123,
|
||||
'ik': 'base/64/encoded',
|
||||
'ik_pub': 'base/64/encoded',
|
||||
'spk': 'base/64/encoded',
|
||||
'spk_pub': 'base/64/encoded',
|
||||
'spk_id': 123,
|
||||
'spk_sig': 'base/64/encoded',
|
||||
'opks': [
|
||||
{
|
||||
'id': 0,
|
||||
'public': 'base/64/encoded',
|
||||
'private': 'base/64/encoded'
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
*/
|
||||
final opks = <int, OmemoKeyPair>{};
|
||||
for (final opk in data['opks']! as List<Map<String, dynamic>>) {
|
||||
opks[opk['id']! as int] = OmemoKeyPair.fromBytes(
|
||||
base64.decode(opk['public']! as String),
|
||||
base64.decode(opk['private']! as String),
|
||||
KeyPairType.x25519,
|
||||
);
|
||||
}
|
||||
|
||||
return Device(
|
||||
data['id']! as int,
|
||||
OmemoKeyPair.fromBytes(
|
||||
base64.decode(data['ik_pub']! as String),
|
||||
base64.decode(data['ik']! as String),
|
||||
KeyPairType.ed25519,
|
||||
),
|
||||
OmemoKeyPair.fromBytes(
|
||||
base64.decode(data['spk_pub']! as String),
|
||||
base64.decode(data['spk']! as String),
|
||||
KeyPairType.x25519,
|
||||
),
|
||||
data['spk_id']! as int,
|
||||
base64.decode(data['spk_sig']! as String),
|
||||
opks,
|
||||
);
|
||||
}
|
||||
|
||||
/// Generate a completely new device, i.e. cryptographic identity.
|
||||
static Future<Device> generateNewDevice({ int opkAmount = 100 }) async {
|
||||
final id = generateRandom32BitNumber();
|
||||
@@ -92,4 +142,28 @@ class Device {
|
||||
encodedOpks,
|
||||
);
|
||||
}
|
||||
|
||||
/// Serialise the device information.
|
||||
Future<Map<String, dynamic>> toJson() async {
|
||||
/// Serialise the OPKs
|
||||
final serialisedOpks = List<Map<String, dynamic>>.empty(growable: true);
|
||||
for (final entry in opks.entries) {
|
||||
serialisedOpks.add({
|
||||
'id': entry.key,
|
||||
'public': base64.encode(await entry.value.pk.getBytes()),
|
||||
'private': base64.encode(await entry.value.sk.getBytes()),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
'id': id,
|
||||
'ik': base64.encode(await ik.sk.getBytes()),
|
||||
'ik_pub': base64.encode(await ik.pk.getBytes()),
|
||||
'spk': base64.encode(await spk.sk.getBytes()),
|
||||
'spk_pub': base64.encode(await spk.pk.getBytes()),
|
||||
'spk_id': spkId,
|
||||
'spk_sig': base64.encode(spkSignature),
|
||||
'opks': serialisedOpks,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user