ubuntu

ubuntu中js如何实现数据加密

小樊
41
2025-08-25 21:42:34
栏目: 编程语言

在Ubuntu系统中,你可以使用多种JavaScript库来实现数据加密。以下是一些流行的库和示例代码:

1. CryptoJS

CryptoJS是一个纯JavaScript编写的加密标准库,支持多种加密算法,如AES、SHA1、SHA256等。

首先,安装CryptoJS:

npm install crypto-js

然后,在你的JavaScript代码中使用它:

const CryptoJS = require("crypto-js");

// 加密
const plaintext = "Hello, World!";
const passphrase = "mySecretPassphrase";
const ciphertext = CryptoJS.AES.encrypt(plaintext, passphrase).toString();

console.log("Ciphertext:", ciphertext);

// 解密
const bytes = CryptoJS.AES.decrypt(ciphertext, passphrase);
const decryptedData = bytes.toString(CryptoJS.enc.Utf8);

console.log("Decrypted Data:", decryptedData);

2. Node.js内置的crypto模块

Node.js提供了一个内置的crypto模块,可以用于各种加密操作。

首先,确保你已经安装了Node.js。然后,在你的JavaScript代码中使用它:

const crypto = require('crypto');

// 加密
const algorithm = 'aes-256-ctr';
const secretKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

const encrypt = (text) => {
  const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
  const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
  return {
    iv: iv.toString('hex'),
    content: encrypted.toString('hex')
  };
};

const decrypt = (hash) => {
  const decipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.from(hash.iv, 'hex'));
  const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
  return decrpyted.toString();
};

const text = "Hello, World!";
const encrypted = encrypt(text);
console.log("Encrypted:", encrypted);

const decrypted = decrypt(encrypted);
console.log("Decrypted:", decrypted);

3. Web Crypto API

如果你在浏览器环境中工作,可以使用Web Crypto API来进行加密操作。

async function encryptData(data, password) {
  const encoder = new TextEncoder();
  const dataBuffer = encoder.encode(data);
  const salt = crypto.getRandomValues(new Uint8Array(16));
  const keyMaterial = await window.crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveKey']
  );
  const derivedKey = await window.crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 100000,
      hash: 'SHA-256'
    },
    keyMaterial,
    { name: 'AES-CBC', length: 256 },
    false,
    ['encrypt']
  );
  const iv = crypto.getRandomValues(new Uint8Array(16));
  const encryptedData = await window.crypto.subtle.encrypt(
    {
      name: 'AES-CBC',
      iv: iv
    },
    derivedKey,
    dataBuffer
  );
  return {
    salt: Array.from(salt),
    iv: Array.from(iv),
    encryptedData: Array.from(new Uint8Array(encryptedData))
  };
}

async function decryptData(encryptedData, password) {
  const encoder = new TextEncoder();
  const salt = new Uint8Array(encryptedData.salt);
  const iv = new Uint8Array(encryptedData.iv);
  const encryptedDataBuffer = new Uint8Array(encryptedData.encryptedData);
  const keyMaterial = await window.crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveKey']
  );
  const derivedKey = await window.crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 100000,
      hash: 'SHA-256'
    },
    keyMaterial,
    { name: 'AES-CBC', length: 256 },
    false,
    ['decrypt']
  );
  const decryptedData = await window.crypto.subtle.decrypt(
    {
      name: 'AES-CBC',
      iv: iv
    },
    derivedKey,
    encryptedDataBuffer
  );
  return new TextDecoder().decode(decryptedData);
}

const data = "Hello, World!";
encryptData(data, "mySecretPassphrase").then(encrypted => {
  console.log("Encrypted:", encrypted);
  return decryptData(encrypted, "mySecretPassphrase");
}).then(decrypted => {
  console.log("Decrypted:", decrypted);
}).catch(err => {
  console.error("Error:", err);
});

这些示例展示了如何在Ubuntu系统中使用JavaScript进行数据加密和解密。你可以根据自己的需求选择合适的库和方法。

0
看了该问题的人还看了