Browse Source

handle string or buffer input for securing encryption key

Kieran Gibb 2 years ago
parent
commit
f1d9ae2c13
No known key found for this signature in database
2 changed files with 10 additions and 2 deletions
  1. 2
    1
      index.js
  2. 8
    1
      test/index.test.js

+ 2
- 1
index.js View File

@@ -20,7 +20,8 @@ class Crypto {
20 20
 
21 21
   encryptionKey (encryptionKey) {
22 22
     var key = sodium.sodium_malloc(sodium.crypto_secretbox_KEYBYTES)
23
-    if (encryptionKey) key.write(encryptionKey)
23
+    if (encryptionKey && Buffer.isBuffer(encryptionKey)) key.copy(encryptionKey)
24
+    else if (encryptionKey && typeof encryptionKey === 'string') key.write(encryptionKey)
24 25
     else sodium.randombytes_buf(key)
25 26
     return key
26 27
   }

+ 8
- 1
test/index.test.js View File

@@ -30,13 +30,20 @@ describe('key generation', (context) => {
30 30
     next()
31 31
   })
32 32
 
33
-  context('encryptionKey(key)', (assert, next) => {
33
+  context('encryptionKey(string)', (assert, next) => {
34 34
     const key = crypto.encryptionKey(crypto.randomBytes(32).toString('hex'))
35 35
     assert.ok(key, 'Key successfully generated')
36 36
     assert.ok(key instanceof Buffer, 'key is a secure buffer')
37 37
     next()
38 38
   })
39 39
 
40
+  context('encryptionKey(buffer)', (assert, next) => {
41
+    const key = crypto.encryptionKey(crypto.randomBytes(32))
42
+    assert.ok(key, 'Key successfully generated')
43
+    assert.ok(key instanceof Buffer, 'key is a secure buffer')
44
+    next()
45
+  })
46
+
40 47
   context('accessKey()', (assert, next) => {
41 48
     const accessKey = crypto.accessKey()
42 49
     assert.ok(accessKey, 'Key successfully generated')