Browse Source

allow keys to be passed to pack and unpack as strings

ameba23 3 years ago
parent
commit
68d75fb6ce
1 changed files with 14 additions and 3 deletions
  1. 14
    3
      index.js

+ 14
- 3
index.js View File

@@ -20,6 +20,8 @@ class Crypto {
20 20
   }
21 21
 
22 22
   pack (pubKey, symKey) {
23
+    pubKey = this.toBuf(pubKey, sodium.crypto_sign_PUBLICKEYBYTES)
24
+    symKey = this.toBuf(symKey, sodium.crypto_secretbox_KEYBYTES)
23 25
     const accessKey = sodium.sodium_malloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_secretbox_KEYBYTES)
24 26
     pubKey.copy(accessKey)
25 27
     symKey.copy(accessKey, sodium.crypto_secretbox_KEYBYTES)
@@ -27,13 +29,22 @@ class Crypto {
27 29
   }
28 30
 
29 31
   unpack (key) {
30
-    if (key.length < sodium.crypto_sign_PUBLICKEYBYTES) throw new Error('Invalid key length')
32
+    key = this.toBuf(key, [sodium.crypto_sign_PUBLICKEYBYTES, sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_secretbox_KEYBYTES])
31 33
     if (key.length === sodium.crypto_sign_PUBLICKEYBYTES) return { publicKey: key }
32 34
     const publicKey = key.slice(0, sodium.crypto_sign_PUBLICKEYBYTES)
33 35
     const symmetricKey = key.slice(sodium.crypto_secretbox_KEYBYTES)
34 36
     return { publicKey, symmetricKey }
35 37
   }
36 38
 
39
+  toBuf (stringOrBuffer, lengths) {
40
+    if (typeof lengths === 'number') lengths = [lengths]
41
+    if ((Buffer.isBuffer(stringOrBuffer)) && (lengths.indexOf(stringOrBuffer.length) > -1)) return stringOrBuffer
42
+    assert((typeof stringOrBuffer === 'string'), 'Key is incorrect type')
43
+    const res = Buffer.from(stringOrBuffer, 'hex')
44
+    assert((lengths.indexOf(res.length) > -1), 'Invalid key')
45
+    return res
46
+  }
47
+
37 48
   isAccessKey (key) {
38 49
     try { var keys = this.unpack(key) }
39 50
     catch (err) { return false }
@@ -46,9 +57,9 @@ class Crypto {
46 57
   }
47 58
 
48 59
   isBlindKey (key) {
49
-    try { var keys = this.unpack(key) }
60
+    var keys
61
+    try { keys = this.unpack(key) }
50 62
     catch (err) { return false }
51
-    var keys = this.unpack(key)
52 63
     return keys.publicKey !== undefined &&
53 64
       keys.publicKey !== null &&
54 65
       keys.publicKey.length === sodium.crypto_sign_PUBLICKEYBYTES &&