ubuntu

Ubuntu Node.js如何实现数据加密与解密

小樊
52
2025-09-04 22:21:11
栏目: 编程语言

在Ubuntu系统中使用Node.js实现数据加密与解密,你可以使用内置的crypto模块。以下是一个简单的示例,展示了如何使用crypto模块进行AES-256-CBC加密和解密。

  1. 首先,确保你已经安装了Node.js。如果没有,请访问Node.js官网下载并安装。

  2. 创建一个新的JavaScript文件,例如encryptDecrypt.js

  3. encryptDecrypt.js文件中,编写以下代码:

const crypto = require('crypto');

// 加密函数
function encrypt(text, key) {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
  const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
  return {
    iv: iv.toString('hex'),
    content: encrypted.toString('hex')
  };
}

// 解密函数
function decrypt(hash, key) {
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), Buffer.from(hash.iv, 'hex'));
  const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
  return decrpyted.toString();
}

// 示例
const key = crypto.randomBytes(32); // 生成一个32字节的密钥
const text = 'Hello, World!';
const encrypted = encrypt(text, key);
const decrypted = decrypt(encrypted, key);

console.log('原始文本:', text);
console.log('加密后的文本:', encrypted);
console.log('解密后的文本:', decrypted);
  1. 在终端中运行encryptDecrypt.js文件:
node encryptDecrypt.js

你将看到原始文本、加密后的文本和解密后的文本。

请注意,这个示例使用了AES-256-CBC加密算法,你可以根据需要选择其他算法。同时,确保妥善保管好密钥,因为它是加密和解密的关键。

0
看了该问题的人还看了