proteus-hd
Version:
Signal Protocol (with header encryption) implementation for JavaScript. Based on Proteus.js.
116 lines (98 loc) • 2.88 kB
JavaScript
/*
* Wire
* Copyright (C) 2016 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
;
const CBOR = require('wire-webapp-cbor');
const ClassUtil = require('../util/ClassUtil');
const DontCallConstructor = require('../errors/DontCallConstructor');
const TypeUtil = require('../util/TypeUtil');
const DerivedSecrets = require('../derived/DerivedSecrets');
const MacKey = require('../derived/MacKey');
const MessageKeys = require('./MessageKeys');
/** @module session */
/**
* @class ChainKey
* @throws {DontCallConstructor}
*/
class ChainKey {
constructor() {
throw new DontCallConstructor(this);
}
/**
* @param {!derived.MacKey} key - Mac Key generated by derived secrets
* @param {!number} counter
* @returns {ChainKey}
*/
static from_mac_key(key, counter) {
TypeUtil.assert_is_instance(MacKey, key);
TypeUtil.assert_is_integer(counter);
const ck = ClassUtil.new_instance(ChainKey);
ck.key = key;
ck.idx = counter;
return ck;
}
/** @returns {ChainKey} */
next() {
const ck = ClassUtil.new_instance(ChainKey);
ck.key = MacKey.new(this.key.sign('1'));
ck.idx = this.idx + 1;
return ck;
}
/** @returns {session.MessageKeys} */
message_keys() {
const base = this.key.sign('0');
const derived_secrets = DerivedSecrets.kdf_without_salt(base, 'hash_ratchet');
return MessageKeys.new(derived_secrets.cipher_key, derived_secrets.mac_key, this.idx);
}
/**
* @param {!CBOR.Encoder} e
* @returns {CBOR.Encoder}
*/
encode(e) {
e.object(2);
e.u8(0);
this.key.encode(e);
e.u8(1);
return e.u32(this.idx);
}
/**
* @param {!CBOR.Decoder} d
* @returns {ChainKey}
*/
static decode(d) {
TypeUtil.assert_is_instance(CBOR.Decoder, d);
const self = ClassUtil.new_instance(ChainKey);
const nprops = d.object();
for (let i = 0; i <= nprops - 1; i++) {
switch (d.u8()) {
case 0:
self.key = MacKey.decode(d);
break;
case 1:
self.idx = d.u32();
break;
default:
d.skip();
}
}
TypeUtil.assert_is_instance(MacKey, self.key);
TypeUtil.assert_is_integer(self.idx);
return self;
}
}
module.exports = ChainKey;