forked from ssbc/ssb-keys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecp256k1.js
56 lines (46 loc) · 1.36 KB
/
secp256k1.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
const secp256k1 = require('secp256k1')
const sodium = require('sodium-native')
const keccak = require('keccak')
function keccak256 (message) {
return keccak('keccak256').update(message).digest()
}
function randomBytes (len, seed) {
var rb = Buffer.alloc(len)
sodium.randombytes_buf(rb)
return rb
}
// This gives us methods of the same form as nacl
// for use with ssb-keys
exports.curves = ['secp256k1']
exports.generateKeys =
exports.generate = function (seed) {
let secretKey
if (seed) {
secretKey = Buffer.alloc(32)
// keeping this is under debate
sodium.randombytes_buf_deterministic(secretKey, seed)
while (!secp256k1.privateKeyVerify(secretKey)) {
secretKey = secp256k1.privateKeyTweakAdd(secretKey, seed)
}
} else {
do {
secretKey = randomBytes(32)
} while (!secp256k1.privateKeyVerify(secretKey))
}
// public key is given in short form
return {
curve: 'secp256k1',
private: secretKey,
public: secp256k1.publicKeyCreate(secretKey)
}
}
exports.sign = function (secretKey, message) {
const hash = keccak256(message)
// arguments are the other way around
return secp256k1.sign(hash, secretKey).signature
}
exports.verify = function (publicKey, signature, message) {
const hash = keccak256(message)
// arguments are the other way around
return secp256k1.verify(hash, signature, publicKey)
}