forked from bcoin-org/bcrypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdsaies.js
72 lines (57 loc) · 1.76 KB
/
dsaies.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
/*!
* dsaies.js - dsaies for javascript
* Copyright (c) 2018-2019, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcrypto
*
* Resources:
* https://en.wikipedia.org/wiki/Integrated_Encryption_Scheme
* https://nacl.cr.yp.to/secretbox.html
*/
'use strict';
const assert = require('./internal/assert');
const dsa = require('./dsa');
const random = require('./random');
const box = require('./secretbox');
const {padLeft} = require('./encoding/util');
/*
* DSAIES
*/
function encrypt(kdf, msg, pub, priv = null) {
assert(kdf != null);
assert(Buffer.isBuffer(msg));
assert(Buffer.isBuffer(pub));
assert(priv == null || Buffer.isBuffer(priv));
if (priv == null) {
const params = dsa.paramsCreate(pub);
priv = dsa.privateKeyCreate(params);
}
const klen = (dsa.publicKeyBits(pub) + 7) >>> 3;
const {y} = dsa.privateKeyExport(priv);
const secret = dsa.derive(pub, priv);
const key = box.derive(secret, kdf);
const nonce = random.randomBytes(24);
const ourY = padLeft(y, klen);
const sealed = box.seal(msg, key, nonce);
return Buffer.concat([ourY, nonce, sealed]);
}
function decrypt(kdf, msg, priv) {
assert(kdf != null);
assert(Buffer.isBuffer(msg));
assert(Buffer.isBuffer(priv));
const klen = (dsa.privateKeyBits(priv) + 7) >>> 3;
if (msg.length < klen + 24)
throw new Error('Invalid ciphertext.');
const {p, q, g} = dsa.privateKeyExport(priv);
const y = msg.slice(0, klen);
const theirPub = dsa.publicKeyImport({ p, q, g, y });
const nonce = msg.slice(klen, klen + 24);
const sealed = msg.slice(klen + 24);
const secret = dsa.derive(theirPub, priv);
const key = box.derive(secret, kdf);
return box.open(sealed, key, nonce);
}
/*
* Expose
*/
exports.encrypt = encrypt;
exports.decrypt = decrypt;