forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest-crypto-dh-generate-keys.js
More file actions
63 lines (54 loc) · 1.93 KB
/
test-crypto-dh-generate-keys.js
File metadata and controls
63 lines (54 loc) · 1.93 KB
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
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const crypto = require('crypto');
{
const size = common.hasFipsCrypto || common.hasOpenSSL3 ? 1024 : 256;
function unlessInvalidState(f) {
try {
return f();
} catch (err) {
if (err.code !== 'ERR_CRYPTO_INVALID_STATE') {
throw err;
}
}
}
function testGenerateKeysChangesKeys(setup, expected) {
const dh = crypto.createDiffieHellman(size);
setup(dh);
const firstPublicKey = unlessInvalidState(() => dh.getPublicKey());
const firstPrivateKey = unlessInvalidState(() => dh.getPrivateKey());
dh.generateKeys();
const secondPublicKey = dh.getPublicKey();
const secondPrivateKey = dh.getPrivateKey();
function changed(shouldChange, first, second) {
if (shouldChange) {
assert.notDeepStrictEqual(first, second);
} else {
assert.deepStrictEqual(first, second);
}
}
changed(expected.includes('public'), firstPublicKey, secondPublicKey);
changed(expected.includes('private'), firstPrivateKey, secondPrivateKey);
}
// Both the private and the public key are missing: generateKeys() generates both.
testGenerateKeysChangesKeys(() => {
// No setup.
}, ['public', 'private']);
// Neither key is missing: generateKeys() does nothing.
testGenerateKeysChangesKeys((dh) => {
dh.generateKeys();
}, []);
// Only the public key is missing: generateKeys() generates only the public key.
testGenerateKeysChangesKeys((dh) => {
dh.setPrivateKey(Buffer.from('01020304', 'hex'));
}, ['public']);
// The public key is outdated: generateKeys() generates only the public key.
testGenerateKeysChangesKeys((dh) => {
const oldPublicKey = dh.generateKeys();
dh.setPrivateKey(Buffer.from('01020304', 'hex'));
assert.deepStrictEqual(dh.getPublicKey(), oldPublicKey);
}, ['public']);
}