sodium-javascript/crypto_kdf.js

41 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2020-06-24 12:08:55 +00:00
/* eslint-disable camelcase */
const assert = require('nanoassert')
const randombytes_buf = require('./randombytes').randombytes_buf
const blake2b = require('blake2b')
2017-06-07 20:38:40 +00:00
module.exports.crypto_kdf_PRIMITIVE = 'blake2b'
module.exports.crypto_kdf_BYTES_MIN = 16
module.exports.crypto_kdf_BYTES_MAX = 64
module.exports.crypto_kdf_CONTEXTBYTES = 8
module.exports.crypto_kdf_KEYBYTES = 32
2017-06-07 20:38:40 +00:00
2020-06-24 12:08:55 +00:00
function STORE64_LE (dest, int) {
2017-06-07 20:38:40 +00:00
var mul = 1
var i = 0
dest[0] = int & 0xFF
while (++i < 8 && (mul *= 0x100)) {
dest[i] = (int / mul) & 0xFF
}
}
module.exports.crypto_kdf_derive_from_key = function crypto_kdf_derive_from_key (subkey, subkey_id, ctx, key) {
2017-06-11 18:23:06 +00:00
assert(subkey.length >= module.exports.crypto_kdf_BYTES_MIN, 'subkey must be at least crypto_kdf_BYTES_MIN')
assert(subkey_id >= 0 && subkey_id <= 0x1fffffffffffff, 'subkey_id must be safe integer')
assert(ctx.length >= module.exports.crypto_kdf_CONTEXTBYTES, 'context must be at least crypto_kdf_CONTEXTBYTES')
2017-06-07 20:38:40 +00:00
var ctx_padded = new Uint8Array(blake2b.PERSONALBYTES)
var salt = new Uint8Array(blake2b.SALTBYTES)
ctx_padded.set(ctx, 0, module.exports.crypto_kdf_CONTEXTBYTES)
STORE64_LE(salt, subkey_id)
2017-06-11 18:23:06 +00:00
var outlen = Math.min(subkey.length, module.exports.crypto_kdf_BYTES_MAX)
blake2b(outlen, key.subarray(0, module.exports.crypto_kdf_KEYBYTES), salt, ctx_padded, true)
2017-06-11 18:23:06 +00:00
.final(subkey)
2017-06-07 20:38:40 +00:00
}
module.exports.crypto_kdf_keygen = function crypto_kdf_keygen (out) {
2017-06-11 18:23:06 +00:00
assert(out.length >= module.exports.crypto_kdf_KEYBYTES, 'out.length must be crypto_kdf_KEYBYTES')
2017-06-11 08:44:02 +00:00
randombytes_buf(out.subarray(0, module.exports.crypto_kdf_KEYBYTES))
2017-06-07 20:38:40 +00:00
}