-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
115 lines (93 loc) · 2.5 KB
/
util.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const storage = require('ara-contracts/storage')
const ss = require('ara-secret-storage')
const { create } = require('./create')
const {
METADATA_SIGNATURES_INDEX,
SIGNATURES_WRITE_LENGTH,
HEADER_LENGTH,
} = require('./constants')
const {
getProxyAddress,
proxyExists
} = require('ara-contracts/registry')
const {
blake2b,
keyPair,
randomBytes: cryptoRandomBytes
} = require('ara-crypto')
async function isUpdateAvailable(opts) {
if (!opts || 'object' !== typeof opts) {
throw new TypeError('Expecting opts object')
} else if (!opts.did || 'string' !== typeof opts.did) {
throw new TypeError('Expecting DID to be non-empty string')
}
const {
keyringOpts = {},
did
} = opts
let buf
try {
const { afs } = await create({ did, keyringOpts })
const localVersion = afs.partitions.home.version
const updateVersion = localVersion + 1
await afs.close()
// offset to read from bc to see if update is available
const offset = HEADER_LENGTH + (updateVersion * SIGNATURES_WRITE_LENGTH)
if (!(await proxyExists(did))) {
return false
}
const address = await getProxyAddress(did)
buf = await storage.read({
fileIndex: METADATA_SIGNATURES_INDEX,
address,
offset
})
} catch (err) {
throw err
}
return null !== buf
}
function generateKeypair(password) {
const passHash = blake2b(Buffer.from(password))
const { publicKey, secretKey } = keyPair(passHash)
return { publicKey, secretKey }
}
function encrypt(value, opts) {
return ss.encrypt(value, opts)
}
function decrypt(value, opts) {
const keystore = JSON.parse(value.keystore)
return ss.decrypt(keystore, opts)
}
function randomBytes(size) {
return cryptoRandomBytes(size)
}
function encryptJSON(json, password) {
const { secretKey } = generateKeypair(password)
const encryptionKey = Buffer.allocUnsafe(16).fill(secretKey.slice(0, 16))
const encryptedJSON = encrypt(JSON.stringify(json), {
key: encryptionKey,
iv: randomBytes(16)
})
secretKey.fill(0)
encryptionKey.fill(0)
return encryptedJSON
}
function decryptJSON(keystore, password) {
const { secretKey } = generateKeypair(password)
const encryptionKey = Buffer.allocUnsafe(16).fill(secretKey.slice(0, 16))
const decryptedJSON = decrypt({ keystore }, { key: encryptionKey })
secretKey.fill(0)
encryptionKey.fill(0)
return decryptedJSON
}
module.exports = {
isUpdateAvailable,
generateKeypair,
proxyExists,
encryptJSON,
decryptJSON,
randomBytes,
encrypt,
decrypt,
}