Write and test IK stages

This commit is contained in:
Belma Gutlic
2020-01-15 11:32:40 +01:00
parent 6ee5c70af9
commit eeaaa8cc84
3 changed files with 93 additions and 1 deletions

View File

@ -5,6 +5,8 @@ import {bytes, bytes32} from "./@types/basic";
import {KeyPair, PeerId} from "./@types/libp2p";
import {IHandshake} from "./@types/handshake-interface";
import {Buffer} from "buffer";
import {decode0, decode1, encode0, encode1} from "./encoder";
import {verifySignedPayload} from "./utils";
export class IKHandshake implements IHandshake {
public isInitiator: boolean;
@ -38,6 +40,38 @@ export class IKHandshake implements IHandshake {
this.session = this.ik.initSession(this.isInitiator, this.prologue, this.staticKeypair, remoteStaticKey);
}
public async stage0(): Promise<void> {
if (this.isInitiator) {
const messageBuffer = this.ik.sendMessage(this.session, this.payload);
this.connection.writeLP(encode0(messageBuffer));
} else {
const receivedMessageBuffer = decode0(await this.connection.readLP());
const plaintext = this.ik.recvMessage(this.session, receivedMessageBuffer);
try {
await verifySignedPayload(receivedMessageBuffer.ns, plaintext, this.remotePeer.id);
} catch (e) {
throw new Error(`Error occurred while verifying signed payload: ${e.message}`);
}
}
}
public async stage1(): Promise<void> {
if (this.isInitiator) {
const receivedMessageBuffer = decode1(await this.connection.readLP());
const plaintext = this.ik.recvMessage(this.session, receivedMessageBuffer);
try {
await verifySignedPayload(receivedMessageBuffer.ns, plaintext, this.remotePeer.id);
} catch (e) {
throw new Error(`Error occurred while verifying signed payload: ${e.message}`);
}
} else {
const messageBuffer = this.ik.sendMessage(this.session, this.payload);
this.connection.writeLP(encode1(messageBuffer));
}
}
public decrypt(ciphertext: Buffer, session: NoiseSession): Buffer {
const cs = this.getCS(session, false);
return this.ik.decryptWithAd(cs, Buffer.alloc(0), ciphertext);

View File

@ -179,7 +179,9 @@ export class Noise implements INoiseConnection {
handshake: IKHandshake,
payload: bytes,
): Promise<IKHandshake> {
// TODO
await handshake.stage0();
await handshake.stage1();
return handshake;
}