Skip to content

Commit

Permalink
refactor({box,unbox}.js): ensure nonce and key are truncated to corre…
Browse files Browse the repository at this point in the history
…ct size
  • Loading branch information
jwerle committed Apr 2, 2021
1 parent 5892d44 commit 5108c27
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
5 changes: 5 additions & 0 deletions box.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const split = require('split-buffer')

/* eslint-disable camelcase */
const {
crypto_secretbox_NONCEBYTES,
crypto_secretbox_KEYBYTES,
crypto_secretbox_MACBYTES,

Expand Down Expand Up @@ -55,6 +56,10 @@ function box(buffer, opts) {
throw new TypeError('crypto.box: Expecting secret key.')
}

// truncate key and nonce
nonce = nonce.slice(0, crypto_secretbox_NONCEBYTES)
key = key.slice(0, crypto_secretbox_KEYBYTES)

// ephemeral nonces used for header and body buffer boxing
const nonces = [ copy(nonce), increment(copy(nonce)) ]

Expand Down
10 changes: 6 additions & 4 deletions unbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ const through = require('through2')

/* eslint-disable camelcase */
const {
crypto_secretbox_NONCEBYTES,
crypto_secretbox_KEYBYTES,
crypto_secretbox_MACBYTES,
crypto_secretbox_NONCEBYTES,

crypto_secretbox_open_easy,
} = require('./sodium')
Expand Down Expand Up @@ -47,15 +47,17 @@ function unbox(buffer, opts) {
if (false === isBuffer(key)) {
throw new TypeError('crypto.unbox: Expecting secret key.')
}


nonce = nonce.slice(0, crypto_secretbox_NONCEBYTES)
key = key.slice(0, crypto_secretbox_KEYBYTES)

const nonces = [ copy(nonce), increment(copy(nonce)) ]
const header = Buffer.allocUnsafe(2 + crypto_secretbox_MACBYTES)

crypto_secretbox_open_easy(
header,
buffer.slice(0, 2 + (2 * crypto_secretbox_MACBYTES)),
nonces[0].slice(0, crypto_secretbox_NONCEBYTES),
nonces[0],
key
)

Expand All @@ -77,7 +79,7 @@ function unbox(buffer, opts) {
crypto_secretbox_open_easy(
unboxed,
combined,
nonces[1].slice(0, crypto_secretbox_NONCEBYTES),
nonces[1],
key
)

Expand Down

0 comments on commit 5108c27

Please sign in to comment.