js-libp2p-noise/src/handshake-ik.ts

71 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-01-03 17:28:13 +01:00
import {WrappedConnection} from "./noise";
2020-01-05 19:09:59 +01:00
import {IK} from "./handshakes/ik";
2020-01-03 14:53:14 +01:00
import {NoiseSession} from "./@types/handshake";
import {bytes, bytes32} from "./@types/basic";
import {KeyPair, PeerId} from "./@types/libp2p";
2020-01-07 13:34:45 +01:00
import {IHandshake} from "./@types/handshake-interface";
2020-01-03 17:28:13 +01:00
import {Buffer} from "buffer";
2020-01-03 14:53:14 +01:00
2020-01-07 13:34:45 +01:00
export class IKHandshake implements IHandshake {
2020-01-03 14:53:14 +01:00
public isInitiator: boolean;
public session: NoiseSession;
2020-01-11 20:20:57 +01:00
private payload: bytes;
2020-01-03 14:53:14 +01:00
private prologue: bytes32;
2020-01-07 13:34:45 +01:00
private staticKeypair: KeyPair;
2020-01-03 14:53:14 +01:00
private connection: WrappedConnection;
private remotePeer: PeerId;
2020-01-05 19:09:59 +01:00
private ik: IK;
2020-01-03 14:53:14 +01:00
constructor(
isInitiator: boolean,
2020-01-11 20:20:57 +01:00
payload: bytes,
2020-01-03 14:53:14 +01:00
prologue: bytes32,
2020-01-07 13:34:45 +01:00
staticKeypair: KeyPair,
2020-01-03 14:53:14 +01:00
connection: WrappedConnection,
remotePeer: PeerId,
2020-01-13 16:33:58 +01:00
remoteStaticKey: bytes,
2020-01-05 19:09:59 +01:00
handshake?: IK,
2020-01-03 14:53:14 +01:00
) {
this.isInitiator = isInitiator;
2020-01-11 20:20:57 +01:00
this.payload = payload;
2020-01-03 14:53:14 +01:00
this.prologue = prologue;
2020-01-07 13:34:45 +01:00
this.staticKeypair = staticKeypair;
2020-01-03 14:53:14 +01:00
this.connection = connection;
this.remotePeer = remotePeer;
2020-01-05 19:09:59 +01:00
this.ik = handshake || new IK();
2020-01-13 16:33:58 +01:00
this.session = this.ik.initSession(this.isInitiator, this.prologue, this.staticKeypair, remoteStaticKey);
2020-01-03 14:53:14 +01:00
}
2020-01-03 17:28:13 +01:00
public decrypt(ciphertext: Buffer, session: NoiseSession): Buffer {
const cs = this.getCS(session, false);
return this.ik.decryptWithAd(cs, Buffer.alloc(0), ciphertext);
}
public encrypt(plaintext: Buffer, session: NoiseSession): Buffer {
const cs = this.getCS(session);
return this.ik.encryptWithAd(cs, Buffer.alloc(0), plaintext);
}
2020-01-05 19:00:16 +01:00
public getRemoteEphemeralKeys(): KeyPair {
if (!this.session.hs.e) {
throw new Error("Ephemeral keys do not exist.");
}
2020-01-03 17:28:13 +01:00
return this.session.hs.e;
}
private getCS(session: NoiseSession, encryption = true) {
if (!session.cs1 || !session.cs2) {
throw new Error("Handshake not completed properly, cipher state does not exist.");
}
if (this.isInitiator) {
return encryption ? session.cs1 : session.cs2;
} else {
return encryption ? session.cs2 : session.cs1;
}
}
2020-01-03 14:53:14 +01:00
}