@ -7,15 +7,17 @@ wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.
Use `require('crypto')` to access this module.
const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
```js
const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
```
## Class: Certificate
@ -31,10 +33,12 @@ data. The most common usage is handling output generated by the HTML5
Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:
const crypto = require('crypto');
```js
const crypto = require('crypto');
const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
```
### certificate.exportChallenge(spkac)
@ -43,11 +47,13 @@ The `spkac` data structure includes a public key and a challenge. The
form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
or a [`Buffer`][].
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints the challenge as a UTF8 string
```js
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints the challenge as a UTF8 string
```
### Certificate.exportPublicKey(spkac)
@ -56,21 +62,25 @@ The `spkac` data structure includes a public key and a challenge. The
form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
or a [`Buffer`][].
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints the public key as < Buffer . . . >
```js
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints the public key as < Buffer . . . >
```
### Certificate.verifySpkac(spkac)
Returns `true` if the given `spkac` data structure is valid, `false` otherwise.
The `spkac` argument must be a Node.js [`Buffer`][].
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(new Buffer(spkac)));
// Prints true or false
```js
const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(new Buffer(spkac)));
// Prints true or false
```
## Class: Cipher
@ -88,38 +98,44 @@ using the `new` keyword.
Example: Using `Cipher` objects as streams:
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
```js
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
cipher.on('readable', () => {
var data = cipher.read();
if (data)
console.log(data.toString('hex'));
// Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
});
cipher.on('readable', () => {
var data = cipher.read();
if (data)
console.log(data.toString('hex'));
// Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
});
cipher.write('clear text data');
cipher.end();
cipher.write('clear text data');
cipher.end();
```
Example: Using `Cipher` and piped streams:
const crypto = require('crypto');
const fs = require('fs');
const cipher = crypto.createCipher('aes192', 'a password');
```js
const crypto = require('crypto');
const fs = require('fs');
const cipher = crypto.createCipher('aes192', 'a password');
const input = fs.createReadStream('test.js');
const output = fs.createWriteStream('test.enc');
const input = fs.createReadStream('test.js');
const output = fs.createWriteStream('test.enc');
input.pipe(cipher).pipe(output);
input.pipe(cipher).pipe(output);
```
Example: Using the `cipher.update()` and `cipher.final()` methods:
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
```js
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
cipher.update('clear text data');
console.log(cipher.final('hex'));
// Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
cipher.update('clear text data');
console.log(cipher.final('hex'));
// Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
```
### cipher.final([output_encoding])
@ -192,38 +208,44 @@ directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
```js
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
decipher.on('readable', () => {
var data = decipher.read();
if (data)
console.log(data.toString());
// Prints: clear text data
});
decipher.on('readable', () => {
var data = decipher.read();
if (data)
console.log(data.toString());
// Prints: clear text data
});
decipher.write('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
decipher.end();
decipher.write('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
decipher.end();
```
Example: Using `Decipher` and piped streams:
const crypto = require('crypto');
const fs = require('fs');
const decipher = crypto.createDecipher('aes192', 'a password');
```
const crypto = require('crypto');
const fs = require('fs');
const decipher = crypto.createDecipher('aes192', 'a password');
const input = fs.createReadStream('test.enc');
const output = fs.createWriteStream('test.js');
const input = fs.createReadStream('test.enc');
const output = fs.createWriteStream('test.js');
input.pipe(decipher).pipe(output);
input.pipe(decipher).pipe(output);
```
Example: Using the `decipher.update()` and `decipher.final()` methods:
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
```js
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
decipher.update('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
console.log(decipher.final('utf8'));
// Prints: clear text data
decipher.update('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
console.log(decipher.final('utf8'));
// Prints: clear text data
```
### decipher.final([output_encoding])
@ -286,23 +308,25 @@ exchanges.
Instances of the `DiffieHellman` class can be created using the
`crypto.createDiffieHellman()` function.
const crypto = require('crypto');
const assert = require('assert');
```js
const crypto = require('crypto');
const assert = require('assert');
// Generate Alice's keys...
const alice = crypto.createDiffieHellman(11);
const alice_key = alice.generateKeys();
// Generate Alice's keys...
const alice = crypto.createDiffieHellman(11);
const alice_key = alice.generateKeys();
// Generate Bob's keys...
const bob = crypto.createDiffieHellman(11);
const bob_key = bob.generateKeys();
// Generate Bob's keys...
const bob = crypto.createDiffieHellman(11);
const bob_key = bob.generateKeys();
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
assert(alice_secret, bob_secret);
// OK
assert(alice_secret, bob_secret);
// OK
```
### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])
@ -383,23 +407,25 @@ key exchanges.
Instances of the `ECDH` class can be created using the
`crypto.createECDH()` function.
const crypto = require('crypto');
const assert = require('assert');
```js
const crypto = require('crypto');
const assert = require('assert');
// Generate Alice's keys...
const alice = crypto.createECDH('secp521r1');
const alice_key = alice.generateKeys();
// Generate Alice's keys...
const alice = crypto.createECDH('secp521r1');
const alice_key = alice.generateKeys();
// Generate Bob's keys...
const bob = crypto.createECDH('secp521r1');
const bob_key = bob.generateKeys();
// Generate Bob's keys...
const bob = crypto.createECDH('secp521r1');
const bob_key = bob.generateKeys();
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
assert(alice_secret, bob_secret);
// OK
assert(alice_secret, bob_secret);
// OK
```
### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])
@ -471,25 +497,27 @@ public point/key associated with the private key being set.
Example (obtaining a shared secret):
const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');
```js
const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');
// Note: This is a shortcut way to specify one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
crypto.createHash('sha256').update('alice', 'utf8').digest()
);
// Note: This is a shortcut way to specify one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
crypto.createHash('sha256').update('alice', 'utf8').digest()
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair bob.generateKeys();
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair bob.generateKeys();
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// alice_secret and bob_secret should be the same shared secret value
console.log(alice_secret === bob_secret);
// alice_secret and bob_secret should be the same shared secret value
console.log(alice_secret === bob_secret);
```
## Class: Hash
@ -506,38 +534,44 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hash` objects as streams:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
```js
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.on('readable', () => {
var data = hash.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
});
hash.on('readable', () => {
var data = hash.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
});
hash.write('some data to hash');
hash.end();
hash.write('some data to hash');
hash.end();
```
Example: Using `Hash` and piped streams:
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
```js
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);
const input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);
```
Example: Using the `hash.update()` and `hash.digest()` methods:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
```js
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
```
### hash.digest([encoding])
@ -574,38 +608,44 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hmac` objects as streams:
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
```js
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
hmac.on('readable', () => {
var data = hmac.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
});
hmac.on('readable', () => {
var data = hmac.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
});
hmac.write('some data to hash');
hmac.end();
hmac.write('some data to hash');
hmac.end();
```
Example: Using `Hmac` and piped streams:
const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');
```js
const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');
const input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);
const input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);
```
Example: Using the `hmac.update()` and `hmac.digest()` methods:
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
```js
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
```
### hmac.digest([encoding])
@ -636,26 +676,30 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Sign` objects as streams:
const crypto = require('crypto');
const sign = crypto.createSign('rsa-sha256');
```js
const crypto = require('crypto');
const sign = crypto.createSign('rsa-sha256');
sign.write('some data to sign');
sign.end();
sign.write('some data to sign');
sign.end();
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
```
Example: Using the `sign.update()` and `sign.sign()` methods:
const crypto = require('crypto');
const sign = crypto.createSign('rsa-sha256');
```js
const crypto = require('crypto');
const sign = crypto.createSign('rsa-sha256');
sign.update('some data to sign');
sign.update('some data to sign');
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
```
### sign.sign(private_key[, output_format])
@ -696,28 +740,32 @@ of two ways:
Example: Using `Verify` objects as streams:
const crypto = require('crypto');
const verify = crypto.createVerify('rsa-sha256');
```js
const crypto = require('crypto');
const verify = crypto.createVerify('rsa-sha256');
verify.write('some data to sign');
verify.end();
verify.write('some data to sign');
verify.end();
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(sign.verify(public_key, signature));
// Prints true or false
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(sign.verify(public_key, signature));
// Prints true or false
```
Example: Using the `verify.update()` and `verify.verify()` methods:
const crypto = require('crypto');
const verify = crypto.createVerify('rsa-sha256');
```js
const crypto = require('crypto');
const verify = crypto.createVerify('rsa-sha256');
verify.update('some data to sign');
verify.update('some data to sign');
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
// Prints true or false
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
// Prints true or false
```
### verifier.update(data)
@ -890,21 +938,23 @@ display the available digest algorithms.
Example: generating the sha256 sum of a file
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
```js
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
```
### crypto.createHmac(algorithm, key)
@ -919,21 +969,23 @@ The `key` is the HMAC key used to generate the cryptographic HMAC hash.
Example: generating the sha256 HMAC of a file
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
```js
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');
const hmac = crypto.createHmac('sha256', 'a secret');
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hmac.update(data);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hmac.update(data);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
```
### crypto.createSign(algorithm)
@ -953,8 +1005,10 @@ Returns an array with the names of the supported cipher algorithms.
Example:
const ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
```js
const ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
```
### crypto.getCurves()
@ -962,8 +1016,10 @@ Returns an array with the names of the supported elliptic curves.
Example:
const curves = crypto.getCurves();
console.log(curves); // ['secp256k1', 'secp384r1', ...]
```js
const curves = crypto.getCurves();
console.log(curves); // ['secp256k1', 'secp384r1', ...]
```
### crypto.getDiffieHellman(group_name)
@ -980,18 +1036,20 @@ and communication time.
Example (obtaining a shared secret):
const crypto = require('crypto');
const alice = crypto.getDiffieHellman('modp14');
const bob = crypto.getDiffieHellman('modp14');
```js
const crypto = require('crypto');
const alice = crypto.getDiffieHellman('modp14');
const bob = crypto.getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();
alice.generateKeys();
bob.generateKeys();
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);
/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);
```
### crypto.getHashes()
@ -999,8 +1057,10 @@ Returns an array with the names of the supported hash algorithms.
Example:
const hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
```js
const hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
```
### crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)
@ -1024,11 +1084,13 @@ salts are random and their lengths are greater than 16 bytes. See
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'
});
```js
const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
if (err) throw err;
console.log(key.toString('hex')); // 'c5e478d...1469e50'
});
```
An array of supported digest functions can be retrieved using
[`crypto.getHashes()`][].
@ -1054,9 +1116,11 @@ salts are random and their lengths are greater than 16 bytes. See
Example:
const crypto = require('crypto');
const key = crypto.pbkdf2sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key.toString('hex')); // 'c5e478d...1469e50'
```js
const crypto = require('crypto');
const key = crypto.pbkdf2sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key.toString('hex')); // 'c5e478d...1469e50'
```
An array of supported digest functions can be retrieved using
[`crypto.getHashes()`][].
@ -1149,22 +1213,26 @@ and the `callback` function is invoked with two arguments: `err` and `buf`.
If an error occurs, `err` will be an Error object; otherwise it is null. The
`buf` argument is a [`Buffer`][] containing the generated bytes.
// Asynchronous
const crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(
`${buf.length}` bytes of random data: ${buf.toString('hex')});
});
```js
// Asynchronous
const crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(
`${buf.length}` bytes of random data: ${buf.toString('hex')});
});
```
If the `callback` function is not provided, the random bytes are generated
synchronously and returned as a [`Buffer`][]. An error will be thrown if
there is a problem generating the bytes.
// Synchronous
const buf = crypto.randomBytes(256);
console.log(
`${buf.length}` bytes of random data: ${buf.toString('hex')});
```js
// Synchronous
const buf = crypto.randomBytes(256);
console.log(
`${buf.length}` bytes of random data: ${buf.toString('hex')});
```
The `crypto.randomBytes()` method will block until there is sufficient entropy.
This should normally never take longer than a few milliseconds. The only time