-
Notifications
You must be signed in to change notification settings - Fork 1
/
key-pair.js
58 lines (51 loc) · 1.53 KB
/
key-pair.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict'
const isBuffer = require('is-buffer')
const alloc = require('buffer-alloc-unsafe')
const {
crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES,
crypto_sign_SEEDBYTES,
crypto_sign_seed_keypair,
crypto_sign_keypair,
} = require('sodium-universal')
/**
* Generate a public and secret key pair from an optional
* seed buffer. This function calls crypto_sign_seed_keypair and
* crypto_sign_keypair internally.
* @public
* @param {(Buffer)} [seed]
* @return {Object}
* @throws TypeError
*/
function keyPair(seed) {
if (null === seed) {
throw new TypeError("keyPair: Seed cannot be null.")
} else if (null != seed) {
if (false == isBuffer(seed)) {
throw new TypeError("keyPair: Expecting seed to be a buffer.")
} else if (0 == seed.length) {
throw new TypeError("keyPair: Cannot use empty buffer as seed.")
} else if (seed.length < crypto_sign_SEEDBYTES) {
throw new TypeError(
`keyPair: Seed buffer length too small. `+
`Expecting size ${crypto_sign_SEEDBYTES}.`
)
} else if (seed.length > crypto_sign_SEEDBYTES) {
throw new TypeError(
`keyPair: Seed buffer length too large. `+
`Expecting size ${crypto_sign_SEEDBYTES}.`
)
}
}
const publicKey = alloc(crypto_sign_PUBLICKEYBYTES)
const secretKey = alloc(crypto_sign_SECRETKEYBYTES)
if (seed) {
crypto_sign_seed_keypair(publicKey, secretKey, seed)
} else {
crypto_sign_keypair(publicKey, secretKey)
}
return { publicKey, secretKey }
}
module.exports = {
keyPair
}