Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: fix and modernize code examples in crypto.md #10909

Closed
wants to merge 8 commits into from
103 changes: 53 additions & 50 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ It is possible for Node.js to be built without including support for the
error being thrown.

```js
var crypto;
let crypto;
try {
crypto = require('crypto');
} catch (err) {
Expand Down Expand Up @@ -132,9 +132,9 @@ Example: Using `Cipher` objects as streams:
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');

var encrypted = '';
let encrypted = '';
cipher.on('readable', () => {
var data = cipher.read();
const data = cipher.read();
if (data)
encrypted += data.toString('hex');
});
Expand Down Expand Up @@ -166,7 +166,7 @@ Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');

var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
Expand Down Expand Up @@ -269,9 +269,9 @@ Example: Using `Decipher` objects as streams:
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');

var decrypted = '';
let decrypted = '';
decipher.on('readable', () => {
var data = decipher.read();
const data = decipher.read();
if (data)
decrypted += data.toString('utf8');
});
Expand All @@ -280,7 +280,7 @@ decipher.on('end', () => {
// Prints: some clear text data
});

var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();
```
Expand All @@ -304,8 +304,8 @@ Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');

var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
Expand Down Expand Up @@ -402,18 +402,18 @@ const assert = require('assert');

// Generate Alice's keys...
const alice = crypto.createDiffieHellman(2048);
const alice_key = alice.generateKeys();
const aliceKey = alice.generateKeys();

// Generate Bob's keys...
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bob_key = bob.generateKeys();
const bobKey = bob.generateKeys();

// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);

// OK
assert.equal(alice_secret.toString('hex'), bob_secret.toString('hex'));
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
```

### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])
Expand Down Expand Up @@ -531,17 +531,17 @@ const assert = require('assert');

// Generate Alice's keys...
const alice = crypto.createECDH('secp521r1');
const alice_key = alice.generateKeys();
const aliceKey = alice.generateKeys();

// Generate Bob's keys...
const bob = crypto.createECDH('secp521r1');
const bob_key = bob.generateKeys();
const bobKey = bob.generateKeys();

// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);

assert(alice_secret, bob_secret);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
```

Expand Down Expand Up @@ -648,13 +648,14 @@ alice.setPrivateKey(
);

// Bob uses a newly generated cryptographically strong
// pseudorandom key pair bob.generateKeys();
// pseudorandom key pair
bob.generateKeys();

const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

// alice_secret and bob_secret should be the same shared secret value
console.log(alice_secret === bob_secret);
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
```

## Class: Hash
Expand All @@ -680,7 +681,7 @@ const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.on('readable', () => {
var data = hash.read();
const data = hash.read();
if (data)
console.log(data.toString('hex'));
// Prints:
Expand Down Expand Up @@ -763,7 +764,7 @@ const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');

hmac.on('readable', () => {
var data = hmac.read();
const data = hmac.read();
if (data)
console.log(data.toString('hex'));
// Prints:
Expand Down Expand Up @@ -847,8 +848,8 @@ const sign = crypto.createSign('RSA-SHA256');
sign.write('some data to sign');
sign.end();

const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
const privateKey = getPrivateKeySomehow();
console.log(sign.sign(privateKey, 'hex'));
// Prints: the calculated signature
```

Expand All @@ -860,8 +861,8 @@ const sign = crypto.createSign('RSA-SHA256');

sign.update('some data to sign');

const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
const privateKey = getPrivateKeySomehow();
console.log(sign.sign(privateKey, 'hex'));
// Prints: the calculated signature
```

Expand All @@ -878,13 +879,14 @@ const sign = crypto.createSign('sha256');

sign.update('some data to sign');

const private_key = '-----BEGIN EC PRIVATE KEY-----\n' +
'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' +
'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' +
'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
'-----END EC PRIVATE KEY-----\n';
const privateKey =
`-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49
AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2
pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==
-----END EC PRIVATE KEY-----`;

console.log(sign.sign(private_key).toString('hex'));
console.log(sign.sign(privateKey).toString('hex'));
```

### sign.sign(private_key[, output_format])
Expand Down Expand Up @@ -947,9 +949,9 @@ const verify = crypto.createVerify('RSA-SHA256');
verify.write('some data to sign');
verify.end();

const public_key = getPublicKeySomehow();
const publicKey = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
console.log(verify.verify(publicKey, signature));
// Prints: true or false
```

Expand All @@ -961,9 +963,9 @@ const verify = crypto.createVerify('RSA-SHA256');

verify.update('some data to sign');

const public_key = getPublicKeySomehow();
const publicKey = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
console.log(verify.verify(publicKey, signature));
// Prints: true or false
```

Expand Down Expand Up @@ -1192,7 +1194,7 @@ const hash = crypto.createHash('sha256');

const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
const data = input.read();
if (data)
hash.update(data);
else {
Expand Down Expand Up @@ -1226,7 +1228,7 @@ const hmac = crypto.createHmac('sha256', 'a secret');

const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
const data = input.read();
if (data)
hmac.update(data);
else {
Expand Down Expand Up @@ -1278,7 +1280,7 @@ Example:

```js
const curves = crypto.getCurves();
console.log(curves); // ['secp256k1', 'secp384r1', ...]
console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
```

### crypto.getDiffieHellman(group_name)
Expand Down Expand Up @@ -1307,11 +1309,11 @@ const bob = crypto.getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();

const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
```

### crypto.getHashes()
Expand All @@ -1326,7 +1328,7 @@ Example:

```js
const hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
```

### crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
Expand Down Expand Up @@ -1357,7 +1359,7 @@ Example:
const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
if (err) throw err;
console.log(key.toString('hex')); // 'c5e478d...1469e50'
console.log(key.toString('hex')); // '3745e48...aa39b34'
});
```

Expand Down Expand Up @@ -1390,7 +1392,7 @@ Example:
```js
const crypto = require('crypto');
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key.toString('hex')); // 'c5e478d...1469e50'
console.log(key.toString('hex')); // '3745e48...aa39b34'
```

An array of supported digest functions can be retrieved using
Expand Down Expand Up @@ -1938,6 +1940,7 @@ the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL.
[`crypto.createHash()`]: #crypto_crypto_createhash_algorithm
[`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key
[`crypto.createSign()`]: #crypto_crypto_createsign_algorithm
[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm
[`crypto.getCurves()`]: #crypto_crypto_getcurves
[`crypto.getHashes()`]: #crypto_crypto_gethashes
[`crypto.pbkdf2()`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
Expand Down