node.js內(nèi)置模塊之crypto?模塊及作用詳解
crypto 模塊的作用
在 Node.js 中,crypto 模塊提供了多種加密功能,包括哈希、對稱加密、非對稱加密和數(shù)字簽名等。通過 crypto 模塊,可以進行各種加密和解密操作,保護敏感數(shù)據(jù)的安全性。
crypto 模塊
1. 哈希算法(Hashing)
哈希函數(shù)(如 SHA、MD5 等)用于將輸入數(shù)據(jù)映射為一個固定長度的字符串(哈希值)。它是單向的,不可逆的,通常用于數(shù)據(jù)完整性驗證。
createHash(algorithm):創(chuàng)建一個哈希對象,algorithm指定使用的哈希算法(例如'sha256','md5')。update(data):向哈希對象添加數(shù)據(jù),可以調(diào)用多次。digest(encoding):返回哈希值,encoding可以是'hex'、'base64'或'binary'。
示例:生成 SHA-256 哈希值
const hash = crypto.createHash('sha256');
hash.update('Hello, world!');
const result = hash.digest('hex');
console.log(result); // 輸出 SHA-256 哈希值
2、加密與解密(Encryption and Decryption)
對稱加密
對稱加密使用相同的密鑰進行加密和解密。crypto 模塊支持多種對稱加密算法,如 AES(AES-128、AES-256)等。
createCipheriv(algorithm, key, iv):創(chuàng)建加密對象,algorithm是加密算法,key是密鑰,iv是初始化向量(IV)。update(data, inputEncoding, outputEncoding):將明文數(shù)據(jù)輸入并指定編碼,返回加密數(shù)據(jù)。final(outputEncoding):返回最后的加密數(shù)據(jù)。
示例:使用 AES-256-CBC 加密和解密
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 32 字節(jié)的密鑰
const iv = crypto.randomBytes(16); // 16 字節(jié)的初始化向量
// 加密
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello, world!', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('Encrypted:', encrypted);
// 解密
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('Decrypted:', decrypted);非對稱加密
非對稱加密使用一對密鑰——公鑰和私鑰。公鑰用于加密,私鑰用于解密。
generateKeyPairSync(type, options):同步生成公鑰和私鑰對,type指定密鑰類型(如'rsa'),options指定密鑰的參數(shù)。publicEncrypt(publicKey, data):使用公鑰對數(shù)據(jù)進行加密。privateDecrypt(privateKey, data):使用私鑰對數(shù)據(jù)進行解密。
示例:使用 RSA 非對稱加密
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048, // 公鑰的位數(shù)
});
// 使用公鑰加密
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from('Hello, world!'));
console.log('Encrypted:', encrypted.toString('hex'));
// 使用私鑰解密
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log('Decrypted:', decrypted.toString());3. HMAC(Hash-based Message Authentication Code)
HMAC 是一種基于哈希的消息認證碼,用于驗證消息的完整性和真實性。它結(jié)合了哈希函數(shù)和密鑰,能夠防止中間人攻擊。
createHmac(algorithm, key):創(chuàng)建 HMAC 對象,algorithm指定哈希算法(如'sha256'),key是密鑰。update(data):向 HMAC 對象輸入數(shù)據(jù)。digest(encoding):返回 HMAC 的結(jié)果,通常是'hex'或'base64'編碼。
示例:生成 HMAC
const secret = 'my-secret-key';
const hmac = crypto.createHmac('sha256', secret);
hmac.update('Hello, world!');
const result = hmac.digest('hex');
console.log('HMAC:', result);
4. 隨機數(shù)生成(Random Number Generation)
crypto 提供了生成安全隨機數(shù)的功能,用于生成隨機密碼、令牌等。
randomBytes(size):生成指定字節(jié)數(shù)的隨機數(shù)據(jù)。
示例:生成隨機字節(jié)
const randomBytes = crypto.randomBytes(16); // 生成16個隨機字節(jié)
console.log(randomBytes.toString('hex')); // 輸出十六進制字符串
5. 數(shù)字簽名(Digital Signature)
數(shù)字簽名用于驗證數(shù)據(jù)的完整性和身份認證,通常用于公鑰基礎(chǔ)設(shè)施(PKI)中。它使用私鑰對數(shù)據(jù)簽名,使用公鑰驗證簽名。
createSign(algorithm):創(chuàng)建一個簽名對象,algorithm指定哈希算法。createVerify(algorithm):創(chuàng)建一個驗證簽名對象,algorithm指定哈希算法。sign(privateKey, encoding):使用私鑰對數(shù)據(jù)進行簽名。verify(publicKey, signature, encoding):使用公鑰驗證簽名。
示例:生成簽名
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
// 生成簽名
const sign = crypto.createSign('SHA256');
sign.update('Hello, world!');
const signature = sign.sign(privateKey, 'hex');
console.log('Signature:', signature);
// 驗證簽名
const verify = crypto.createVerify('SHA256');
verify.update('Hello, world!');
const isVerified = verify.verify(publicKey, signature, 'hex');
console.log('Verified:', isVerified); // true 或 false6. 密鑰對生成(Key Pair Generation)
非對稱加密中,公鑰和私鑰的生成可以通過 crypto.generateKeyPairSync 方法。
generateKeyPairSync(type, options):生成公鑰和私鑰對,type指定加密算法類型(如'rsa'),options包含密鑰的相關(guān)參數(shù)。export(options):將密鑰導(dǎo)出為 PEM 格式。
示例:生成 RSA 密鑰對
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
console.log('Private Key:', privateKey.export({ type: 'pkcs1', format: 'pem' }));
console.log('Public Key:', publicKey.export({ type: 'pkcs1', format: 'pem' }));到此這篇關(guān)于node.js內(nèi)置模塊之crypto 模塊及作用詳解的文章就介紹到這了,更多相關(guān)node.js內(nèi)置模塊crypto內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodeJS服務(wù)器的創(chuàng)建和重新啟動的實現(xiàn)方法
今天小編就為大家分享一篇nodeJS服務(wù)器的創(chuàng)建和重新啟動的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
使用node.js半年來總結(jié)的 10 條經(jīng)驗
從3月初來到帝都某創(chuàng)業(yè)公司的服務(wù)器團隊實習(xí),到現(xiàn)在已接近半年的時間。PS: 已轉(zhuǎn)正,服務(wù)器端用的 Node。2014-08-08

