Add decryption methods

This commit is contained in:
morrigan 2019-11-04 15:19:40 +01:00
parent e4b5c068db
commit c542b53a4b

View File

@ -39,7 +39,7 @@ type NoiseSession = {
const minNonce = 0;
class XXHandshake {
export class XXHandshake {
private createEmptyKey() : bytes32 {
return Buffer.alloc(32);
}
@ -68,9 +68,15 @@ class XXHandshake {
return n + 1;
}
private encrypt(k: bytes32, n: uint32, ad: bytes, plaintext: bytes) : bytes {
private convertNonce(n: uint32) : bytes {
const nonce = Buffer.alloc(12);
nonce.writeUInt32LE(n, 4);
return nonce;
}
private encrypt(k: bytes32, n: uint32, ad: bytes, plaintext: bytes) : bytes {
const nonce = this.convertNonce(n);
const ctx = new AEAD();
ctx.init(k, nonce);
ctx.aad(ad);
@ -79,6 +85,17 @@ class XXHandshake {
return ctx.final();
}
private decrypt(k: bytes32, n: uint32, ad: bytes, ciphertext: bytes) : bytes {
const nonce = this.convertNonce(n);
const ctx = new AEAD();
ctx.init(k, nonce);
ctx.aad(ad);
ctx.decrypt(ciphertext);
return ctx.final();
}
// Cipher state related
private initializeKey(k: bytes32) : CipherState {
const n = minNonce;
@ -95,6 +112,13 @@ class XXHandshake {
return e;
}
private decryptWithAd(cs: CipherState, ad: bytes, ciphertext: bytes) : bytes {
const plaintext = this.decrypt(cs.k, cs.n, ad, ciphertext);
this.setNonce(cs, this.incrementNonce(cs.n));
return plaintext;
}
// Symmetric state related
private async initializeSymmetric(protocolName: string) : Promise<SymmetricState> {