-
Notifications
You must be signed in to change notification settings - Fork 20
/
utils.js
78 lines (66 loc) · 2.19 KB
/
utils.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
"use strict";
let crypto = require('crypto');
const { mnemonicToSeedSync } = require('bip39');
const { pki, random } = require('node-forge');
// CRYPTO settings
const HASH_ALG = 'sha256';
const SIG_ALG = 'RSA-SHA256';
exports.hash = function hash(s, encoding) {
encoding = encoding || 'hex';
return crypto.createHash(HASH_ALG).update(s).digest(encoding);
};
/**
* Generates keypair from mnemonic and password
*
* @param {String} mnemonic - associated with the blockchain instance
* @param {String} password - unique to each user
* @returns
*/
//https://stackoverflow.com/questions/72047474/how-to-generate-safe-rsa-keys-deterministically-using-a-seed
exports.generateKeypairFromMnemonic = function( mnemonic, password ) {
const seed = mnemonicToSeedSync(mnemonic, password).toString('hex');
const prng = random.createInstance();
prng.seedFileSync = () => seed;
const { privateKey, publicKey } = pki.rsa.generateKeyPair({ bits: 512, prng, workers: 2 });
return {
public: pki.publicKeyToPem(publicKey),
private: pki.privateKeyToPem(privateKey),
};
};
exports.generateKeypair = function() {
const kp = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
return {
public: kp.publicKey,
private: kp.privateKey,
};
};
exports.sign = function(privKey, msg) {
let signer = crypto.createSign(SIG_ALG);
// Convert an object to its JSON representation
let str = (msg === Object(msg)) ? JSON.stringify(msg) : ""+msg;
return signer.update(str).sign(privKey, 'hex');
};
exports.verifySignature = function(pubKey, msg, sig) {
let verifier = crypto.createVerify(SIG_ALG);
// Convert an object to its JSON representation
let str = (msg === Object(msg)) ? JSON.stringify(msg) : ""+msg;
return verifier.update(str).verify(pubKey, sig, 'hex');
};
exports.calcAddress = function(key) {
let addr = exports.hash(""+key, 'base64');
//console.log(`Generating address ${addr} from ${key}`);
return addr;
};
exports.addressMatchesKey = function(addr, pubKey) {
return addr === exports.calcAddress(pubKey);
};