This repository has been archived by the owner on Feb 20, 2019. It is now read-only.
/
keypair_store.js
70 lines (63 loc) · 1.92 KB
/
keypair_store.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const
fs = require('fs'),
path = require('path'),
util = require('util');
const
PUBLIC_KEY_FILENAME = 'key.publickey';
var
pub_key_filename = util.format('var/%s', PUBLIC_KEY_FILENAME);
/**
* Checks to see if either server public or secret keys already exist.
* Takes a callback with one argument exists - a boolean.
* exists will be true if either file already exists.
*/
exports.files_exist = function (callback) {
path.exists(pub_key_filename, function (pub_exists) {
if (pub_exists) {
callback(pub_exists);
} else {
callback(false);
}
});
};
/**
* Given a jwcrypto public/private keypair, serializes them to the
* filesystem. Two optional callbacks can be provided for errors
* generated while writing public and secret files.
*/
exports.write_files = function (keypair, pub_cb, secr_cb) {
fs.writeFile(pub_key_filename, keypair.publicKey.serialize(), 'utf8', function (err) {
if (err) {
pub_cb(err);
}
});
fs.writeFile(priv_key_filename, keypair.secretKey.serialize(), 'utf8', function (err) {
if (err) {
secr_cb(err);
}
});
};
/**
* Reads JSON formatted jwcrypto public key from filesystem.
* Use write_files to create these files.
* Takes callback with arguments err, pubKey
*
* Method is synchronous as it's used from other modules during loading.
*/
exports.read_files_sync = function (callback) {
var pub_exists = path.existsSync(pub_key_filename);
if (! pub_exists) {
return callback("Missing public key, cannot read files");
}
try {
var pubKey = JSON.parse(fs.readFileSync(pub_key_filename, 'utf8'));
callback(null, pubKey);
} catch (e) {
// File IO or malformed JSON
console.trace(e);
callback(e.toString());
}
};