UNPKG

1.97 kBJavaScriptView Raw
1var assert = require('assert')
2 , nacl = require('tweetnacl')
3 , a = require('../utils/a')
4 , bs58 = require('bs58')
5
6var pubkeyRegex = /([a-zA-Z0-9]{87,88})\s*(?:"([^"]*)")?\s*(?:<([^>]*)>)?/
7
8function parsePubkey (input, recipients) {
9 var buf, name, email
10 try {
11 // passing a pubkey buffer
12 if (Buffer.isBuffer(input)) {
13 buf = input
14 }
15 // passing a pubkey string
16 else if (typeof input === 'string') {
17 var match = input.match(pubkeyRegex)
18 assert(match)
19 buf = bs58.decode(match[1])
20 assert(Array.isArray(buf))
21 buf = Buffer(buf)
22 name = match[2]
23 email = match[3] ? match[3].toLowerCase() : null
24 }
25 assert.equal(buf.length, 64)
26 }
27 catch (e) {
28 throw new Error('invalid pubkey')
29 }
30 var pubkey = bs58.encode(buf)
31 if (recipients) {
32 // detect an imported pubkey
33 var recipient = recipients[pubkey]
34 if (recipient && !name && !email) {
35 name = recipient.name
36 email = recipient.email
37 }
38 }
39 return {
40 verifyPk: buf.slice(0, 32),
41 encryptPk: buf.slice(32),
42 pubkey: pubkey,
43 name: name,
44 email: email,
45 verify: function (sig, detachedBuf) {
46 if (detachedBuf) {
47 //console.error('detached', JSON.stringify(detachedBuf.toString('utf8')))
48 return nacl.sign.detached.verify(a(detachedBuf), a(sig), a(this.verifyPk)) ? detachedBuf : false
49 }
50 var result = nacl.sign.open(a(sig), a(this.verifyPk))
51 if (!result) return false
52 return Buffer(result)
53 },
54 toString: function (nice) {
55 var parts = nice ? [] : [
56 this.pubkey
57 ]
58 if (this.name) parts.push('"' + this.name.replace(/"/g, '') + '"')
59 if (this.email) parts.push('<' + this.email.replace(/>/g, '') + '>')
60 if (nice && !this.name && !this.email) parts.push(pubkeys)
61 return parts.join(' ')
62 },
63 toBuffer: function () {
64 return buf
65 }
66 }
67}
68
69module.exports = {
70 parse: parsePubkey,
71 regex: pubkeyRegex
72}
\No newline at end of file