Cryptography
The crypto module is mostly useful as a tool for implementing cryptographic protocols such as TLS and https.
Nodejs offers great support for cryptography.
The crypto module is a wrapper above the OpenSSL cryptographic functions. (HMAC, Cyphers, ...)
require("crypto")
.createHash("md5")
.update("This is some crypt string in node!")
.digest("hex");
Thecrypto
module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.
How to determine if crypto support is unavailable
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
Thecrypto
module provides theCertificate
class for working with SPKAC data.
Instances of theCertificate
class can be created using thenew
keyword or by callingcrypto.Certificate()
as a function:
Example on hot to decrypt/encrypt text using the crypto module
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world")
console.log(decrypt(hw));
An example on how to decrypt/encrypt buffers:
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';
function encrypt(buffer){
var cipher = crypto.createCipher(algorithm,password)
var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
return crypted;
}
function decrypt(buffer){
var decipher = crypto.createDecipher(algorithm,password)
var dec = Buffer.concat([decipher.update(buffer) , decipher.final()]);
return dec;
}
var hw = encrypt(new Buffer("hello world", "utf8"))
// outputs hello world
console.log(decrypt(hw).toString('utf8'));