Node.js crypto Module
Node.js's crypto The module is a built-in module that provides cryptographic functionality, including wrappers for OpenSSL's hashing, HMAC, encryption, decryption, signing, and verification features. It allows developers to perform various cryptographic operations in Node.js applications.
Core Features
Hashing Algorithm
A hash algorithm is a one-way function that converts an input of arbitrary length into a fixed-length output.crypto The module supports multiple hash algorithms, such as SHA-256, MD5, and others.
Example
const
crypto
=
require
(
'crypto'
)
;
// Create a SHA-256 hash
const
hash
=
crypto.
createHash
(
'sha256'
)
;
hash.
update
(
'Hello World'
)
;
console.
log
(
hash.
digest
(
'hex'
)
)
;
// Output: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146
HMAC (Keyed-Hash Message Authentication Code)
HMAC is a message authentication mechanism that uses a cryptographic hash function combined with a secret key.
Example
const
crypto
=
require
(
'crypto'
)
;
const
secret
=
'mysecret'
;
const
hmac
=
crypto.
createHmac
(
'sha256'
,
secret
)
;
hmac.
update
(
'Hello World'
)
;
console.
log
(
hmac.
digest
(
'hex'
)
)
;
// Output: 9b8e8b0e3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a
Encryption and decryption
Symmetric encryption
Symmetric encryption uses the same key for both encryption and decryption.crypto The module supports algorithms such as AES and DES.
Example
const
crypto
=
require
(
'crypto'
)
;
// Encrypt
const
algorithm
=
'aes-256-cbc'
;
const
key
=
crypto.
randomBytes
(
32
)
;
const
iv
=
crypto.
randomBytes
(
16
)
;
const
cipher
=
crypto.
createCipheriv
(
algorithm
,
key
,
iv
)
;
let encrypted
=
cipher.
update
(
'Hello World'
,
'utf8'
,
'hex'
)
;
encrypted
+=
cipher.
final
(
'hex'
)
;
console.
log
(
encrypted
)
;
// Decrypt
const
decipher
=
crypto.
createDecipheriv
(
algorithm
,
key
,
iv
)
;
let decrypted
=
decipher.
update
(
encrypted
,
'hex'
,
'utf8'
)
;
decrypted
+=
decipher.
final
(
'utf8'
)
;
console.
log
(
decrypted
)
;
Asymmetric encryption
Asymmetric encryption uses a public/private key pair, with the public key used for encryption and the private key for decryption.
Example
const
crypto
=
require
(
'crypto'
)
;
// Generate a key pair
const
{
publicKey
,
privateKey
}
=
crypto.
generateKeyPairSync
(
'rsa'
,
{
modulusLength
:
2048
,
}
)
;
// Encrypt
const
encryptedData
=
crypto.
publicEncrypt
(
publicKey
,
Buffer.
from
(
'Hello World'
)
)
;
console.
log
(
encryptedData.
toString
(
'base64'
)
)
;
// Decrypt
const
decryptedData
=
crypto.
privateDecrypt
(
privateKey
,
encryptedData
)
;
console.
log
(
decryptedData.
toString
(
)
)
;
Digital signatures and verification
Digital signatures are used to verify the integrity and origin of data.
Example
const
crypto
=
require
(
'crypto'
)
;
// Generate a key pair
const
{
privateKey
,
publicKey
}
=
crypto.
generateKeyPairSync
(
'rsa'
,
{
modulusLength
:
2048
,
}
)
;
// Create a signature
const
sign
=
crypto.
createSign
(
'SHA256'
)
;
sign.
update
(
'some data to sign'
)
;
const
signature
=
sign.
sign
(
privateKey
,
'hex'
)
;
console.
log
(
signature
)
;
// Verify a signature
const
verify
=
crypto.
createVerify
(
'SHA256'
)
;
verify.
update
(
'some data to sign'
)
;
console.
log
(
verify.
verify
(
publicKey
,
signature
,
'hex'
)
)
;
// Output: true
Random number generation
crypto The module provides methods for generating cryptographically secure random numbers.
Example
const
crypto
=
require
(
'crypto'
)
;
// Generate a 16-byte random number
const
randomBytes
=
crypto.
randomBytes
(
16
)
;
console.
log
(
randomBytes.
toString
(
'hex'
)
)
;
// Generate a random integer
const
randomInt
=
crypto.
randomInt
(
1
,
100
)
;
console.
log
(
randomInt
)
;
Security considerations
- Key management: never hardcode keys in code; use environment variables or a key management system.
- Algorithm selection: avoid using algorithms known to be insecure, such as MD5 and SHA1.
- Initialization vector (IV): for symmetric encryption, a different IV should be used for each encryption.
- Cryptographic parameters: use a sufficiently long key length (such as AES-256 instead of AES-128).
Practical Application Scenarios
- Password storage: use a hash algorithm to store user passwords
- Data transmission encryption: protect data during network transmission
- API Signature Verification: Ensuring the integrity of API requests
- JWT Tokens: Generating and verifying JSON Web Tokens
- File Integrity Checking: Verifying the hash values of downloaded files
Summary
Node.js's crypto The module provides powerful cryptographic functionality and is an important tool for building secure applications. By making reasonable use of hashing, encryption, signing, and other features, developers can effectively protect data security. When using it, be sure to follow security best practices and choose appropriate algorithms and parameters.
For more complex security requirements, you can consider using specialized cryptographic libraries such as bcrypt、argon2 etc., which are optimized for specific purposes.
Node.js Built-in Modules