mirror of
https://github.com/fluencelabs/js-libp2p-noise
synced 2025-04-26 06:52:31 +00:00
Add decryption methods
This commit is contained in:
parent
e4b5c068db
commit
c542b53a4b
28
src/xx.ts
28
src/xx.ts
@ -39,7 +39,7 @@ type NoiseSession = {
|
|||||||
|
|
||||||
const minNonce = 0;
|
const minNonce = 0;
|
||||||
|
|
||||||
class XXHandshake {
|
export class XXHandshake {
|
||||||
private createEmptyKey() : bytes32 {
|
private createEmptyKey() : bytes32 {
|
||||||
return Buffer.alloc(32);
|
return Buffer.alloc(32);
|
||||||
}
|
}
|
||||||
@ -68,9 +68,15 @@ class XXHandshake {
|
|||||||
return n + 1;
|
return n + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private encrypt(k: bytes32, n: uint32, ad: bytes, plaintext: bytes) : bytes {
|
private convertNonce(n: uint32) : bytes {
|
||||||
const nonce = Buffer.alloc(12);
|
const nonce = Buffer.alloc(12);
|
||||||
nonce.writeUInt32LE(n, 4);
|
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();
|
const ctx = new AEAD();
|
||||||
ctx.init(k, nonce);
|
ctx.init(k, nonce);
|
||||||
ctx.aad(ad);
|
ctx.aad(ad);
|
||||||
@ -79,6 +85,17 @@ class XXHandshake {
|
|||||||
return ctx.final();
|
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
|
// Cipher state related
|
||||||
private initializeKey(k: bytes32) : CipherState {
|
private initializeKey(k: bytes32) : CipherState {
|
||||||
const n = minNonce;
|
const n = minNonce;
|
||||||
@ -95,6 +112,13 @@ class XXHandshake {
|
|||||||
return e;
|
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
|
// Symmetric state related
|
||||||
|
|
||||||
private async initializeSymmetric(protocolName: string) : Promise<SymmetricState> {
|
private async initializeSymmetric(protocolName: string) : Promise<SymmetricState> {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user