### CipherState constructor example Source: https://github.com/holepunchto/noise-handshake Create a Cipher instance with a key. Shows hasKey is true and nonce starts at 0. ```javascript const Cipher = require('noise-handshake/cipher') const key = Buffer.alloc(Cipher.KEYBYTES, 7) const cipher = new Cipher(key) console.log(cipher.hasKey) // true console.log(cipher.nonce) // 0 ``` -------------------------------- ### Example: initialiseKey usage Source: https://github.com/holepunchto/noise-handshake Example showing initialiseKey usage. Before keying, encrypt acts as passthrough and nonce stays 0. After initialiseKey with a 32-byte key, hasKey becomes true and nonce resets to 0. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(null) cipher.encrypt(Buffer.from('x')) // passthrough, nonce stays 0 cipher.initialiseKey(Buffer.alloc(32, 9)) // now keyed; nonce reset to 0 console.log(cipher.hasKey) // true console.log(cipher.nonce) // 0 ``` -------------------------------- ### Example: setNonce usage Source: https://github.com/holepunchto/noise-handshake Example showing setNonce usage. Sets the nonce to 10 and logs it. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(Buffer.alloc(32, 1)) cipher.setNonce(10) console.log(cipher.nonce) // 10 ``` -------------------------------- ### Basic construction example Source: https://github.com/holepunchto/noise-handshake Creates initiator and responder NoiseState instances for the IK pattern. The initiator uses a pre-shared static key, while the responder generates its own. ```javascript const Noise = require('noise-handshake') const initiator = new Noise('IK', true) // responder's static key is pre-shared → no args needed const responder = new Noise('IK', false) // responder generates its own static keypair ``` -------------------------------- ### Example - deriving keys Source: https://github.com/holepunchto/noise-handshake Derives two 64-byte keys using hkdf and shows how Noise uses the first 32 bytes as cipher keys. ```javascript const hkdf = require('noise-handshake/hkdf') const [k1, k2] = hkdf(Buffer.alloc(64, 1), Buffer.alloc(32, 2), 'session') console.log(k1.length, k2.length) // 64 64 // Noise uses only the first 32 bytes of each chunk as cipher keys: const cipherKey = k1.subarray(0, 32) console.log(cipherKey.length) // 32 ``` -------------------------------- ### Keyless CipherState passthrough example Source: https://github.com/holepunchto/noise-handshake Create a Cipher instance with null key. encrypt returns the input unchanged. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(null) // no key yet const out = cipher.encrypt(Buffer.from('not yet encrypted')) console.log(out.toString()) // 'not yet encrypted' — returned unchanged ``` -------------------------------- ### Example: mixHash usage Source: https://github.com/holepunchto/noise-handshake Creates a SymmetricState instance and mixes a prologue buffer into the digest. After the call, the digest holds BLAKE2b(0x00...00 || 'prologue'). ```javascript const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() state.mixHash(Buffer.from('prologue')) // digest now holds BLAKE2b(0x00...00 || 'prologue') ``` -------------------------------- ### Nonce/authentication failure example Source: https://github.com/holepunchto/noise-handshake Shows that decrypting with a different key fails authentication. The example uses two Cipher instances with different keys; decryption with the wrong key throws the error 'could not verify data'. ```javascript const Cipher = require('noise-handshake/cipher') const from = new Cipher(Buffer.alloc(32, 1)) const to = new Cipher(Buffer.alloc(32, 2)) // different key const ciphertext = from.encrypt(Buffer.from('hello'), Buffer.from('ad')) // Decrypting under a different key fails authentication: try { to.decrypt(ciphertext, Buffer.from('ad')) } catch (err) { console.log(err.message) // 'could not verify data' } ``` -------------------------------- ### SymmetricState instantiation example Source: https://github.com/holepunchto/noise-handshake Creates a new SymmetricState instance and logs its default properties: DH_ALG is '25519', digest length is 64, and hasKey is false until a mixKey* call. ```javascript const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() console.log(state.DH_ALG) // '25519' (from the default X25519 curve) console.log(state.digest.length) // 64 console.log(state.hasKey) // false — no cipher key until a mixKey* call ``` -------------------------------- ### Example - 3-chunk derivation (as used by mixKeyAndHash) Source: https://github.com/holepunchto/noise-handshake Derives three 64-byte keys using hkdf with a length of 3 * HASHLEN. ```javascript const hkdf = require('noise-handshake/hkdf') const [chainingKey, tempHash, tempKey] = hkdf( Buffer.alloc(64, 5), Buffer.alloc(32, 6), '', 3 * hkdf.HASHLEN ) console.log(chainingKey.length, tempHash.length, tempKey.length) // 64 64 64 ``` -------------------------------- ### Example — IK handshake initialisation Source: https://github.com/holepunchto/noise-handshake Shows how to initialise an IK handshake. The initiator must already know the responder's static public key, so it passes responder.s.publicKey as remoteStatic; the responder needs no remote static for IK. ```javascript const Noise = require('noise-handshake') const initiator = new Noise('IK', true) const responder = new Noise('IK', false) const prologue = Buffer.from('proto-v1') // The initiator must already know the responder's static public key. initiator.initialise(prologue, responder.s.publicKey) responder.initialise(prologue) // responder needs no remote static for IK ``` -------------------------------- ### Basic encryption example Source: https://github.com/holepunchto/noise-handshake Creates a Cipher instance with a 32-byte key and encrypts a plaintext buffer. The resulting ciphertext length is plaintext length plus 16 bytes for the MAC tag, and the nonce counter increments by one after encryption. ```javascript const Cipher = require('noise-handshake/cipher') const send = new Cipher(Buffer.alloc(32, 1)) const enc = send.encrypt(Buffer.from('secret message')) console.log(enc.length) // 14 + 16 (MAC) console.log(send.nonce) // 1 ``` -------------------------------- ### generateKeyPair usage example Source: https://github.com/holepunchto/noise-handshake Example showing how to generate a keypair and derive a public key from a known secret. Outputs 32 for both secretKey and publicKey lengths. ```javascript const dh = require('noise-handshake/dh') const keyPair = dh.generateKeyPair() console.log(keyPair.secretKey.length) // 32 console.log(keyPair.publicKey.length) // 32 // Derive a public key from a known secret: const derived = dh.generateKeyPair(Buffer.alloc(32, 1)) console.log(derived.publicKey.length) // 32 ``` -------------------------------- ### generateSeedKeyPair usage example Source: https://github.com/holepunchto/noise-handshake Example showing deterministic keypair generation from the same seed. Outputs true, confirming both keypairs have identical public keys. ```javascript const dh = require('noise-handshake/dh') const a = dh.generateSeedKeyPair(Buffer.alloc(32, 4)) const b = dh.generateSeedKeyPair(Buffer.alloc(32, 4)) console.log(a.publicKey.equals(b.publicKey)) // true — deterministic ``` -------------------------------- ### SymmetricState split example Source: https://github.com/holepunchto/noise-handshake Seeds a chaining key with mixKeyNormal, then calls split() to derive two transport keys. Demonstrates that the keys are 32 bytes each and not equal. ```javascript const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() state.mixKeyNormal(Buffer.alloc(32, 3)) // seed a chaining key const [k1, k2] = state.split() console.log(k1.length, k2.length) // 32 32 console.log(k1.equals(k2)) // false ``` -------------------------------- ### Example: driving DH-key mixing manually Source: https://github.com/holepunchto/noise-handshake Creates a SymmetricState, generates local and remote key pairs, and mixes the remote public key with the local keypair. After the call, chainingKey is non-null and hasKey is true. ```javascript const SymmetricState = require('noise-handshake/symmetric-state') const { generateKeyPair } = require('noise-handshake/dh') const state = new SymmetricState() const local = generateKeyPair() const remote = generateKeyPair() state.mixKey(remote.publicKey, local) // mixes curve25519(remote.pub, local.sec) console.log(state.chainingKey !== null) // true — HKDF has run console.log(state.hasKey) // true — cipher rekeyed ``` -------------------------------- ### Example — driving a two-message handshake Source: https://github.com/holepunchto/noise-handshake Shows a complete IK handshake: the initiator sends a message, the responder receives it and replies, and the initiator receives the reply. After completion, initiator.complete is true and initiator.tx equals responder.rx (session keys match). ```javascript const Noise = require('noise-handshake') const initiator = new Noise('IK', true) const responder = new Noise('IK', false) initiator.initialise(Buffer.alloc(0), responder.s.publicKey) responder.initialise(Buffer.alloc(0)) // -> e, es, s, ss const message = initiator.send(Buffer.from('hello from initiator')) responder.recv(message) // <- e, ee, se const reply = responder.send(Buffer.from('hello from responder')) initiator.recv(reply) console.log(initiator.complete) // true console.log(initiator.tx.equals(responder.rx)) // session keys match (see README convention) ``` -------------------------------- ### SymmetricState mixHash and getHandshakeHash example Source: https://github.com/holepunchto/noise-handshake Creates a SymmetricState, mixes handshake data into the hash, and retrieves the 64-byte handshake hash. Shows that getHandshakeHash allocates a buffer by default or fills a provided destination buffer in place. ```javascript const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() state.mixHash(Buffer.from('handshake data')) const hash = state.getHandshakeHash() // allocates a 64-byte buffer console.log(hash.length) // 64 const dest = Buffer.alloc(64) const returned = state.getHandshakeHash(dest) console.log(returned === dest) // true — filled in place ``` -------------------------------- ### dh usage example Source: https://github.com/holepunchto/noise-handshake Example showing shared secret agreement between two keypairs. Outputs true, confirming both parties compute the same shared secret. ```javascript const dh = require('noise-handshake/dh') const alice = dh.generateKeyPair() const bob = dh.generateKeyPair() const s1 = dh.dh(bob.publicKey, alice) const s2 = dh.dh(alice.publicKey, bob) console.log(s1.equals(s2)) // true — shared secret agreement ``` -------------------------------- ### Catch authentication failure in CipherState.decrypt Source: https://github.com/holepunchto/noise-handshake Use try/catch to handle authentication failures from CipherState.decrypt. The example shows tampering with ciphertext and matching the error message 'could not verify data' to detect authenticated-encryption failures. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(Buffer.alloc(32, 1)) const ciphertext = cipher.encrypt(Buffer.from('x')) ciphertext[0] ^= 0xff try { cipher.decrypt(ciphertext) } catch (err) { if (/could not verify data/.test(err.message)) { // authenticated-encryption failure — reject/retry the connection console.log('authentication failed') } } ``` -------------------------------- ### Direct HMAC computation example Source: https://github.com/holepunchto/noise-handshake Computes HMAC over two message parts with a 32-byte key. The output is 64 bytes and is not all zeros. ```javascript const hmac = require('noise-handshake/hmac') const hkdf = require('noise-handshake/hkdf') const out = Buffer.alloc(hmac.BYTES) hmac(out, [Buffer.from('message part 1'), Buffer.from('message part 2')], Buffer.alloc(32, 9)) console.log(out.length) // 64 console.log(out.equals(Buffer.alloc(64))) // false — digest computed ``` -------------------------------- ### Example — error handling for a missing pre-shared key Source: https://github.com/holepunchto/noise-handshake Demonstrates the error thrown when remoteStatic is omitted for a pattern that preshares the responder's static key (XK). The catch block logs the error message 'Remote pubkey required'. ```javascript const Noise = require('noise-handshake') const initiator = new Noise('XK', true) // XK preshares the responder's static key try { initiator.initialise(Buffer.alloc(0)) // remoteStatic omitted! } catch (err) { console.log(err.message) // 'Remote pubkey required' } ``` -------------------------------- ### Catch assertion failure for missing remote static key in NoiseState.initialise Source: https://github.com/holepunchto/noise-handshake Use try/catch to handle assertion failures from nanoassert. The example shows an AssertionError with message 'Remote pubkey required' when initialise is called without the responder's static public key for IK/XK patterns. ```javascript const Noise = require('noise-handshake') const initiator = new Noise('XK', true) try { initiator.initialise(Buffer.alloc(0)) // remoteStatic missing } catch (err) { console.log(err.name, '|', err.message) // AssertionError | Remote pubkey required } ``` -------------------------------- ### Round-trip and tamper detection example Source: https://github.com/holepunchto/noise-handshake Demonstrates a full encrypt/decrypt round trip and tamper detection. Modifying one byte of the ciphertext causes decryption to fail with the error message 'could not verify data'. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(Buffer.alloc(32, 5)) const ciphertext = cipher.encrypt(Buffer.from('round trip')) const decrypted = cipher.decrypt(ciphertext) console.log(decrypted.toString()) // 'round trip' // Tamper with one byte of the ciphertext: ciphertext[0] ^= 0xff try { cipher.decrypt(ciphertext) } catch (err) { console.log(err.message) // 'could not verify data' } ``` -------------------------------- ### Encryption with associated data example Source: https://github.com/holepunchto/noise-handshake Shows encryption with associated data (AD). Decryption requires identical AD; using a different AD causes an authentication failure with the error message 'could not verify data'. ```javascript const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(Buffer.alloc(32, 1)) const ad = Buffer.from('frame header') const ciphertext = cipher.encrypt(Buffer.from('payload'), ad) // Decryption requires identical AD: const other = new Cipher(Buffer.alloc(32, 1)) console.log(other.decrypt(ciphertext, ad).toString()) // 'payload' // Wrong AD → authentication failure: try { other.initialiseKey(Buffer.alloc(32, 1)) other.decrypt(ciphertext, Buffer.from('other header')) } catch (err) { console.log(err.message) // 'could not verify data' } ``` -------------------------------- ### complete property initial and final values Source: https://github.com/holepunchto/noise-handshake Shows the `complete` property values at construction and after `final()` in noise.js. Starts `false` and becomes `true` when the last handshake message is sent or received. ```javascript this.complete = false // noise.js:101 (constructor) ``` ```javascript this.complete = true // noise.js:136 (final()) ``` -------------------------------- ### NoiseState.initialise(prologue, remoteStatic) Source: https://github.com/holepunchto/noise-handshake Initializes the handshake state with a prologue and optional remote static key. Throws assertion errors for missing required keys or corrupt pattern data. ```APIDOC ## NoiseState.initialise(prologue, remoteStatic) ### Description Initializes the handshake state with a prologue and optional remote static key. Throws assertion errors for missing required keys or corrupt pattern data. ### Method initialise ### Parameters - **prologue** (Buffer) - Required - Prologue data. - **remoteStatic** (Buffer) - Optional - Remote static public key (required for IK/XK initiator). ### Response #### Success Response No explicit success response documented. #### Error Responses - **Remote pubkey required** - IK/XK initiator calls without the responder's static public key. - **Unexpected pattern** - Corrupt pattern data with an unknown preshare token. ``` -------------------------------- ### CipherState constructor Source: https://github.com/holepunchto/noise-handshake Creates a CipherState instance with the specified key. The key is a 32-byte Buffer or null; null yields a keyless (passthrough) state until initialiseKey(key) is called. ```javascript new Cipher(key) ``` -------------------------------- ### NoiseState constructor Source: https://github.com/holepunchto/noise-handshake Creates a NoiseState instance with the specified pattern, initiator role, static keypair, and options. The pattern must be one of NN, NNpsk0, XX, XXpsk0, IK, or XK; unknown names throw a native TypeError at construction. ```javascript new Noise(pattern, initiator, staticKeypair, opts) ``` -------------------------------- ### NoiseState with psk option Source: https://github.com/holepunchto/noise-handshake Creates a NoiseState instance for the NNpsk0 pattern with a pre-shared key. The psk must be a 32-byte Buffer; non-32-byte values produce a handshake that fails authentication. If peers use different psk values, recv() throws 'could not verify data'. ```javascript const Noise = require('noise-handshake') const psk = Buffer.from('324eee92611cd877841c4de9fd5253e9dba6033329a837ee5f01beb005dffb2f', 'hex') const peer = new Noise('NNpsk0', true, null, { psk }) ``` -------------------------------- ### Construction with static keypair and options Source: https://github.com/holepunchto/noise-handshake Creates a NoiseState with a pre-generated static keypair and a pre-shared key for psk0 patterns. Shows how to access the static public key and check the psk handshake flag. ```javascript const Noise = require('noise-handshake') const { generateKeyPair } = require('noise-handshake/dh') const myStatic = generateKeyPair() // { secretKey, publicKey } const psk = Buffer.alloc(32, 0x42) // pre-shared key for psk0 patterns const peer = new Noise('NNpsk0', true, myStatic, { psk }) console.log(peer.s.publicKey) // the static public key that will be signed into the handshake console.log(peer.isPskHandshake) // true ``` -------------------------------- ### Import SymmetricState Source: https://github.com/holepunchto/noise-handshake Import the SymmetricState class from the noise-handshake package using the subpath 'noise-handshake/symmetric-state'. ```javascript const SymmetricState = require('noise-handshake/symmetric-state') ``` -------------------------------- ### SymmetricState constructor Source: https://github.com/holepunchto/noise-handshake Creates a SymmetricState instance with the specified options. The opts.curve option has the same semantics as NoiseState's opts.curve and is passed through by NoiseState via super(opts). ```javascript new SymmetricState(opts) ``` -------------------------------- ### constructor(key) Source: https://github.com/holepunchto/noise-handshake Creates a new CipherState instance for ChaCha20-Poly1305 authenticated encryption. The key is optional; when null, the state is keyless and encrypt/decrypt become identity passthroughs. ```APIDOC ## constructor(key) ### Description Creates a new CipherState instance for ChaCha20-Poly1305 authenticated encryption. The key is optional; when null, the state is keyless and encrypt/decrypt become identity passthroughs. ### Parameters - `key` (Buffer, 32 bytes; `KEYBYTES`) - Optional - The 32-byte ChaCha20-Poly1305 key. When null, the state is keyless. ### Instance Properties - `this.key` - The cipher key, or null. - `this.nonce` - Numeric counter, starts at 0, incremented after each operation. - `this.CIPHER_ALG` - Constant string 'ChaChaPoly'. ### Example ```js const Cipher = require('noise-handshake/cipher') const key = Buffer.alloc(Cipher.KEYBYTES, 7) const cipher = new Cipher(key) console.log(cipher.hasKey) // true console.log(cipher.nonce) // 0 ``` ### Example — keyless (passthrough) state ```js const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(null) // no key yet const out = cipher.encrypt(Buffer.from('not yet encrypted')) console.log(out.toString()) // 'not yet encrypted' — returned unchanged ``` ``` -------------------------------- ### Instantiate ciphers over agreed session keys Source: https://github.com/holepunchto/noise-handshake README pattern for creating send and receive ciphers after handshake completion. Uses `initiator.tx` for sending and `responder.rx` for receiving, then encrypts and decrypts a message. ```javascript // Instantiate ciphers over the agreed session keys (README pattern): const Cipher = require('noise-handshake/cipher') const send = new Cipher(initiator.tx) const receive = new Cipher(responder.rx) const enc = send.encrypt(Buffer.from('hello, world')) console.log(receive.decrypt(enc).toString()) // hello, world ``` -------------------------------- ### split() Source: https://github.com/holepunchto/noise-handshake Runs HKDF on the current chaining key with zero-length input key material and returns the two 32-byte transport keys: [k1, k2] from hkdf(chainingKey, Buffer.alloc(0)) mapped to subarray(0, 32). Used by NoiseState.final() to derive tx/rx. ```APIDOC ## split() ### Description Runs HKDF on the current chaining key with zero-length input key material and returns the two 32-byte transport keys: `[k1, k2]` from `hkdf(chainingKey, Buffer.alloc(0))` mapped to `subarray(0, 32)`. Used by `NoiseState.final()` to derive `tx`/`rx` (`tx = initiator ? k1 : k2`, `rx = initiator ? k2 : k1` — `noise.js:132-141`). ### Returns - `[k1, k2]` — array of two 32-byte `Buffer`s. ### Request Example ```js const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() state.mixKeyNormal(Buffer.alloc(32, 3)) // seed a chaining key const [k1, k2] = state.split() console.log(k1.length, k2.length) // 32 32 console.log(k1.equals(k2)) // false ``` ``` -------------------------------- ### initialiseKey(key) Source: https://github.com/holepunchto/noise-handshake Sets the cipher key and resets the nonce counter to 0. This method must be called before encryption or decryption to activate the cipher. ```APIDOC ## initialiseKey(key) ### Description Sets the cipher key and resets the nonce counter to `0`. ### Parameters - `key` (Buffer, 32 bytes) - Required - The new key. ### Returns `undefined` ### Example ```js const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(null) cipher.encrypt(Buffer.from('x')) // passthrough, nonce stays 0 cipher.initialiseKey(Buffer.alloc(32, 9)) // now keyed; nonce reset to 0 console.log(cipher.hasKey) // true console.log(cipher.nonce) // 0 ``` ``` -------------------------------- ### split() method signature Source: https://github.com/holepunchto/noise-handshake Signature of the split() method. Runs HKDF on the current chaining key with zero-length input key material and returns two 32-byte transport keys. ```javascript split() // symmetric-state.js:64 ``` -------------------------------- ### constructor(pattern, initiator, staticKeypair, opts) Source: https://github.com/holepunchto/noise-handshake Creates a handshake state for a given Noise protocol pattern. Either side of a connection instantiates its own NoiseState; the two instances then exchange messages through send()/recv(). ```APIDOC ## constructor(pattern, initiator, staticKeypair, opts) ### Description Creates a handshake state for a given Noise protocol pattern. Either side of a connection instantiates its own NoiseState; the two instances then exchange messages through send()/recv(). ### Parameters - `pattern` (string) - Required - The Noise handshake pattern to run (one of 'NN', 'NNpsk0', 'XX', 'XXpsk0', 'IK', 'XK'). - `initiator` (boolean) - Required - `true` for the initiator role, `false` for the responder role. - `staticKeypair` (KeyPair | null) - Optional - A pre-existing static keypair (`{ secretKey, publicKey }`). Defaults to `null` (a fresh keypair is generated via `this.curve.generateKeyPair()`). - `opts` (NoiseStateOptions) - Optional - Optional configuration; supports `curve` (custom curve module) and `psk` (32-byte pre-shared key). Defaults to `{}`. ### Example ```js const Noise = require('noise-handshake') const initiator = new Noise('IK', true) // responder's static key is pre-shared → no args needed const responder = new Noise('IK', false) // responder generates its own static keypair ``` ### Example ```js const Noise = require('noise-handshake') const { generateKeyPair } = require('noise-handshake/dh') const myStatic = generateKeyPair() // { secretKey, publicKey } const psk = Buffer.alloc(32, 0x42) // pre-shared key for psk0 patterns const peer = new Noise('NNpsk0', true, myStatic, { psk }) console.log(peer.s.publicKey) // the static public key that will be signed into the handshake console.log(peer.isPskHandshake) // true ``` ``` -------------------------------- ### Import hkdf module Source: https://github.com/holepunchto/noise-handshake Import the hkdf module from the noise-handshake package. ```javascript const hkdf = require('noise-handshake/hkdf') ``` -------------------------------- ### peer.initialise(prologue, remoteStatic) Source: https://github.com/holepunchto/noise-handshake/blob/main/README.md Initializes the handshake state with a prologue and any preshared keys. This must be called before sending or receiving messages. ```APIDOC ## peer.initialise(prologue, remoteStatic) ### Description Initializes the handshake state with a prologue and any preshared keys. This must be called before sending or receiving messages. ### Parameters - **prologue** (Buffer) - Required - The prologue data. - **remoteStatic** (Buffer) - Optional - The remote peer's static public key, if required by the pattern. ``` -------------------------------- ### Import CipherState from noise-handshake/cipher Source: https://github.com/holepunchto/noise-handshake Import the CipherState class from the 'noise-handshake/cipher' subpath. ```javascript const Cipher = require('noise-handshake/cipher') ``` -------------------------------- ### CipherState.encrypt / decrypt Source: https://github.com/holepunchto/noise-handshake Encrypts and decrypts data with authenticated encryption. Throws errors for size violations and authentication failures. ```APIDOC ## CipherState.encrypt / decrypt ### Description Encrypts and decrypts data with authenticated encryption. Throws errors for size violations and authentication failures. ### Method encrypt / decrypt ### Parameters - **plaintext** (Buffer) - Required (for encrypt) - Data to encrypt. - **ciphertext** (Buffer) - Required (for decrypt) - Data to decrypt. ### Response #### Success Response No explicit success response documented. #### Error Responses - **ciphertext length of N exceeds maximum Noise message length of 65535** - Plaintext producing > 65535-byte ciphertext. - **ciphertext length of N is shorter than the MAC** - Decrypt input shorter than 16 bytes. - **could not verify data** - Wrong key, nonce, AD, or tampered ciphertext. ``` -------------------------------- ### Class hierarchy diagram Source: https://github.com/holepunchto/noise-handshake Shows the inheritance chain: CipherState -> SymmetricState -> NoiseState. ```text CipherState (cipher.js) └── SymmetricState (symmetric-state.js) — adds digest/chaining-key/HKDF mixing └── NoiseState (noise.js) — adds handshake patterns, message construction ``` -------------------------------- ### new Noise(pattern, initiator, staticKeypair, [opts]) Source: https://github.com/holepunchto/noise-handshake/blob/main/README.md Creates a new handshake state for a given Noise protocol pattern. The initiator parameter indicates the role (true for initiator, false for responder), and an optional static keypair can be provided. ```APIDOC ## new Noise(pattern, initiator, staticKeypair, [opts]) ### Description Creates a new handshake state for a given Noise protocol pattern. The initiator parameter indicates the role (true for initiator, false for responder), and an optional static keypair can be provided. ### Parameters - **pattern** (string) - Required - The Noise protocol pattern (e.g., 'IK'). - **initiator** (boolean) - Required - `true` if this peer is the initiator, `false` if responder. - **staticKeypair** (object) - Optional - A preexisting keypair to use for the static key. - **opts** (object) - Optional - Options object with the following properties: - **curve** (module) - Optional - Module for performing Noise over other curves. - **psk** (Buffer) - Optional - A 32-byte buffer containing a pre-shared key for patterns containing `psk0`. ### Returns A new handshake state object. ``` -------------------------------- ### final() Source: https://github.com/holepunchto/noise-handshake Splits the chaining key into the two transport keys, assigns tx/rx according to role, records the handshake hash, marks the handshake complete, and wipes the working state via _clear(). Takes no arguments and returns undefined. ```APIDOC ## final() ### Description Splits the chaining key into the two transport keys, assigns `tx`/`rx` according to role, records the handshake hash, marks the handshake `complete`, and wipes the working state via `_clear()`. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | — | — | — | — | Takes no arguments. | ### Returns `undefined`. ### Notes `final()` is called automatically by `send()` and `recv()` once the last pattern message has been processed (`if (!this.handshake.length) this.final()` — `noise.js:185` in `recv`, `noise.js:230` in `send`). It is only in the public (inherited) API position because the class is a plain JS class; there is no need to call it manually in normal usage. Calling it more than once would call `split()` again on a cleared chaining key (the post-`_clear` chaining key is `null`). ### Example — inspecting the completed handshake state ```js const Noise = require('noise-handshake') const initiator = new Noise('XX', true) const responder = new Noise('XX', false) initiator.initialise(Buffer.alloc(0)) responder.initialise(Buffer.alloc(0)) initiator.send() // final() not yet reached (3-message pattern) const m2 = responder.send() initiator.recv(m2) initiator.send() // last message → initiator.final() runs (send) ... console.log(initiator.complete) // true console.log(initiator.hash) // 64-byte BLAKE2b hash of the full transcript console.log(initiator.tx) // session key for sending to the peer console.log(initiator.rx) // session key for receiving from the peer ``` ``` -------------------------------- ### Encrypt and decrypt with CipherState Source: https://github.com/holepunchto/noise-handshake Create Cipher instances with session keys from a completed handshake and use encrypt/decrypt. The decrypt returns the original plaintext. ```javascript const send = new Cipher(initiator.tx) const receive = new Cipher(responder.rx) const enc = send.encrypt(Buffer.from('hello, world')) console.log(receive.decrypt(enc)) // hello, world ``` -------------------------------- ### CipherState constructor signature Source: https://github.com/holepunchto/noise-handshake Constructor for CipherState. Accepts a 32-byte key or null. When null, encrypt/decrypt are identity passthroughs. ```javascript constructor(key) // cipher.js:5 ``` -------------------------------- ### initialiseKey(key) method signature Source: https://github.com/holepunchto/noise-handshake Method signature for initialiseKey(key) in cipher.js:11. Sets the cipher key and resets the nonce counter to 0. ```javascript initialiseKey(key) // cipher.js:11 ``` -------------------------------- ### new SymmetricState(opts) Source: https://github.com/holepunchto/noise-handshake Creates a new SymmetricState instance, which extends CipherState with a handshake digest, chaining key, and HKDF-based key-mixing operations. The constructor initializes the curve module, digest buffer, chaining key, offset, and DH algorithm identifier. ```APIDOC ## new SymmetricState(opts) ### Description Creates a new SymmetricState instance, which extends CipherState with a handshake digest, chaining key, and HKDF-based key-mixing operations. The constructor initializes the curve module, digest buffer, chaining key, offset, and DH algorithm identifier. ### Constructor `constructor(opts = {})` ### Parameters #### Options - **opts** (object) - Optional - Options object. - **opts.curve** (CurveModule) - Optional - Curve module used for Diffie-Hellman and key generation. Defaults to the built-in X25519 curve module (`./dh`). ### Instance Properties - **curve** - The curve module (`opts.curve || curve` where `curve = require('./dh')`). - **digest** - 64-byte zero-filled buffer; the running transcript hash. - **chainingKey** - `null` until initialised by the handshake driver. - **offset** - `0`; increments are performed by the Noise protocol's `MixKeyAndHash` equivalent sequences. - **DH_ALG** - `this.curve.ALG` (default `'25519'`). ### Example ```js const SymmetricState = require('noise-handshake/symmetric-state') const state = new SymmetricState() console.log(state.DH_ALG) // '25519' (from the default X25519 curve) console.log(state.digest.length) // 64 console.log(state.hasKey) // false — no cipher key until a mixKey* call ``` ``` -------------------------------- ### Import hmac module Source: https://github.com/holepunchto/noise-handshake Import the hmac module from the noise-handshake package. ```javascript const hmac = require('noise-handshake/hmac') ``` -------------------------------- ### Noise handshake with IK pattern and encryption Source: https://github.com/holepunchto/noise-handshake/blob/main/README.md Initializes an IK handshake between initiator and responder, exchanges messages, and uses the resulting session keys to encrypt and decrypt a message. Requires the noise-handshake and noise-handshake/cipher modules. ```javascript const Noise = require('noise-handshake') const Cipher = require('noise-handshake/cipher') const initiator = new Noise('IK', true) const responder = new Noise('IK', false) const prologue = Buffer.alloc(0) // preshared key initiator.initialise(prologue, responder.s.publicKey) responder.initialise(prologue) // -> e, es, s, ss const message = initiator.send() responder.recv(message) // <- e, ee, se const reply = responder.send() initiator.recv(reply) console.log(initiator.complete) // true // convention is to use rx for // sending and tx for receiving // initiator.rx === responder.tx // responder.rx === initiator.tx // instantiate a cipher using shared secrets const send = new Cipher(initiator.tx) const receive = new Cipher(responder.rx) const msg = Buffer.from('hello, world') const enc = send.encrypt(msg) console.log(receive.decrypt(enc)) // hello, world ``` -------------------------------- ### encrypt(plaintext, ad) Source: https://github.com/holepunchto/noise-handshake Performs authenticated encryption of the provided plaintext under the current key and nonce, with optional associated data. If the state has no key, the plaintext is returned unchanged and the nonce is untouched. ```APIDOC ## encrypt(plaintext, ad) ### Description Authenticated encryption of `plaintext` under the current key and nonce, with optional associated data. If the state has no key (`hasKey === false`) the plaintext is returned unchanged and the nonce is untouched. ### Parameters - `plaintext` (Buffer or hex string) - Required - Data to encrypt. Non-buffer values are coerced from hex. - `ad` (Buffer or hex string) - Optional (default: zero-length buffer) - Additional authenticated data (bound to the ciphertext, not encrypted). ### Returns Buffer — ciphertext plus the 16-byte `MACBYTES` authentication tag (`plaintext.byteLength + 16` bytes). The internal nonce counter (`this.nonce`) is incremented by one after a successful encryption. ### Throws - `Error: ciphertext length of N exceeds maximum Noise message length of 65535` - The produced ciphertext is longer than 65535 bytes (checked after encryption; e.g. a 90 000-byte plaintext yields a 90 016-byte ciphertext). ### Request Example ```js const Cipher = require('noise-handshake/cipher') const send = new Cipher(Buffer.alloc(32, 1)) const enc = send.encrypt(Buffer.from('secret message')) console.log(enc.length) // 14 + 16 (MAC) console.log(send.nonce) // 1 ``` ### Request Example (with associated data) ```js const Cipher = require('noise-handshake/cipher') const cipher = new Cipher(Buffer.alloc(32, 1)) const ad = Buffer.from('frame header') const ciphertext = cipher.encrypt(Buffer.from('payload'), ad) // Decryption requires identical AD: const other = new Cipher(Buffer.alloc(32, 1)) console.log(other.decrypt(ciphertext, ad).toString()) // 'payload' // Wrong AD → authentication failure: try { other.initialiseKey(Buffer.alloc(32, 1)) other.decrypt(ciphertext, Buffer.from('other header')) } catch (err) { console.log(err.message) // 'could not verify data' } ``` ``` -------------------------------- ### send(payload) method signature Source: https://github.com/holepunchto/noise-handshake Builds and returns the next handshake message for the role's current position in the pattern. Each pattern token is serialised in order: TOK_E appends the ephemeral public key, TOK_S appends the static public key encrypted, and DH tokens mix the Diffie-Hellman output into the chaining key and cipher state. The payload is appended encrypted at the end. Returns a Buffer; when the final pattern message is sent, final() runs at the end of send(). Throws 'Error: Unexpected message' for unhandled pattern tokens. ```javascript send(payload = b4a.alloc(0)) // noise.js:189 ``` -------------------------------- ### mixKey(remoteKey, localKey) Source: https://github.com/holepunchto/noise-handshake Computes the Diffie-Hellman output between a remote public key and a local secret key, then performs MixKey on the DH output. Returns undefined. ```APIDOC ## mixKey(remoteKey, localKey) ### Description Computes the Diffie-Hellman output between a remote public key and a local secret key via `this.curve.dh(remoteKey, localKey)`, then performs `MixKey` on the DH output (HKDF → new chaining key + cipher rekey). ### Parameters - `remoteKey` (Buffer, `PKLEN` bytes) - Required - Remote public key. - `localKey` (KeyPair) - Required - Local keypair; only `secretKey` is used. ### Returns `undefined` ### Example — driving DH-key mixing manually ```js const SymmetricState = require('noise-handshake/symmetric-state') const { generateKeyPair } = require('noise-handshake/dh') const state = new SymmetricState() const local = generateKeyPair() const remote = generateKeyPair() state.mixKey(remote.publicKey, local) // mixes curve25519(remote.pub, local.sec) console.log(state.chainingKey !== null) // true — HKDF has run console.log(state.hasKey) // true — cipher rekeyed ``` ``` -------------------------------- ### Export hkdf and HASHLEN Source: https://github.com/holepunchto/noise-handshake Module exports the hkdf function and the HASHLEN constant. ```javascript module.exports = { hkdf, HASHLEN } ``` -------------------------------- ### hkdf(salt, inputKeyMaterial, info, length) Source: https://github.com/holepunchto/noise-handshake HMAC-based Extract-and-Expand Key Derivation Function (HKDF, RFC 5869) built on BLAKE2b-based HMAC. Extracts a pseudorandom key from input key material using a salt, then expands it into the requested number of hash-length chunks. ```APIDOC ## hkdf(salt, inputKeyMaterial, info, length) ### Description HMAC-based Extract-and-Expand Key Derivation Function (HKDF, RFC 5869) built on BLAKE2b-based HMAC. Extracts a pseudorandom key from input key material using a salt, then expands it into the requested number of hash-length chunks. ### Method Function call ### Endpoint `hkdf(salt, inputKeyMaterial, info = '', length = 2 * HASHLEN)` ### Parameters #### Function Parameters - **salt** (Buffer) - Required - HKDF salt; key for the extract step. In `SymmetricState` this is the current chaining key. - **inputKeyMaterial** (Buffer) - Required - The key material to extract from (e.g. a DH output, pre-shared key, or zero-length buffer in `split()`). - **info** (string | Buffer) - Optional (default: `''`) - Context string mixed into each expansion chunk. - **length** (number) - Optional (default: `128` (`2 * HASHLEN`)) - Total output length in bytes; must be a multiple of `HASHLEN` (64) for chunking to align. ### Response #### Success Response - **Returns** (Array) - `length / HASHLEN` buffers, each `HASHLEN` (64) bytes, created as subarrays of a single `allocUnsafeSlow(length)` slab. Default call returns 2 buffers. ### Request Example ```js const hkdf = require('noise-handshake/hkdf') const [k1, k2] = hkdf(Buffer.alloc(64, 1), Buffer.alloc(32, 2), 'session') console.log(k1.length, k2.length) // 64 64 // Noise uses only the first 32 bytes of each chunk as cipher keys: const cipherKey = k1.subarray(0, 32) console.log(cipherKey.length) // 32 ``` ### Request Example ```js const hkdf = require('noise-handshake/hkdf') const [chainingKey, tempHash, tempKey] = hkdf( Buffer.alloc(64, 5), Buffer.alloc(32, 6), '', 3 * hkdf.HASHLEN ) console.log(chainingKey.length, tempHash.length, tempKey.length) // 64 64 64 ``` ``` -------------------------------- ### Static constants for Cipher Source: https://github.com/holepunchto/noise-handshake Defines the static getters for MACBYTES, NONCEBYTES, and KEYBYTES. These constants are used for authentication tag length, nonce length, and key length respectively. ```javascript static get MACBYTES() { return 16 } // cipher.js:60 static get NONCEBYTES() { return 8 } // cipher.js:64 static get KEYBYTES() { return 32 } // cipher.js:68 ``` -------------------------------- ### Static alg getter Source: https://github.com/holepunchto/noise-handshake Returns CipherState.alg concatenated with '_BLAKE2b'. Note: CipherState does not define a static alg getter, so this returns 'undefined_BLAKE2b'. ```javascript static get alg() { return CipherState.alg + '_BLAKE2b' } // symmetric-state.js:82 ``` -------------------------------- ### mixKeyAndHash(key) Source: https://github.com/holepunchto/noise-handshake Noise's MixKeyAndHash: derives a 3-part HKDF from the chaining key and key, updates the chaining key with the first 64 bytes, mixes the second 64 bytes into the digest, and rekeys the cipher with tempK. Returns undefined. ```APIDOC ## mixKeyAndHash(key) ### Description Noise's `MixKeyAndHash`: derives a 3-part HKDF (`3 * HASHLEN` output) from the chaining key and `key`, updates the chaining key with the first 64 bytes, mixes the second 64 bytes into the digest, and rekeys the cipher with `tempK` (first 32 bytes). ### Parameters - `key` (Buffer) - Required - Key material (e.g. a pre-shared key). ### Returns `undefined` ``` -------------------------------- ### _clear() Source: https://github.com/holepunchto/noise-handshake Zeroes the key and resets nonce to null. Called internally when a handshake completes. ```APIDOC ## _clear() ### Description Zeroes the key with `sodium_memzero` and sets `key` and `nonce` to `null`. ### Returns `undefined` ``` -------------------------------- ### Send payload over an already-running XX handshake Source: https://github.com/holepunchto/noise-handshake Shows how to send and receive payloads during an XX handshake using send() and recv(). The initiator and responder exchange messages, with payloads attached to the second and third messages. The responder receives the client payload and logs it. ```javascript const Noise = require('noise-handshake') const initiator = new Noise('XX', true) const responder = new Noise('XX', false) initiator.initialise(Buffer.alloc(0)) responder.initialise(Buffer.alloc(0)) const m1 = initiator.send() // -> e responder.recv(m1) const m2 = responder.send(Buffer.from('server payload')) // <- e, ee, s, es initiator.recv(m2) const m3 = initiator.send(Buffer.from('client payload')) // -> s, se const got = responder.recv(m3) console.log(got.toString()) // 'client payload' ``` -------------------------------- ### Constructor signature Source: https://github.com/holepunchto/noise-handshake Signature for the NoiseState constructor. Creates a handshake state for a given pattern. ```javascript constructor(pattern, initiator, staticKeypair, opts = {}) // noise.js:77 ``` -------------------------------- ### Require noise-handshake package Source: https://github.com/holepunchto/noise-handshake Imports the top-level NoiseState class from the noise-handshake package. ```javascript const Noise = require('noise-handshake') ```