溫馨提示×

ubuntu上js如何實現數據加密

小樊
40
2025-10-18 18:16:57
欄目: 編程語言

在Ubuntu上使用JavaScript進行數據加密,你可以選擇多種庫和方法。以下是一些流行的方法和庫:

  1. 使用Node.js的crypto模塊: Node.js內置了一個名為crypto的模塊,它提供了各種加密算法,如AES、RSA等。以下是一個使用AES-256-CBC算法進行加密和解密的例子:
const crypto = require('crypto');

// 加密函數
function encrypt(text, secretKey) {
  const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, Buffer.alloc(16, '0'));
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

// 解密函數
function decrypt(encryptedText, secretKey) {
  const decipher = crypto.createDecipheriv('aes-256-cbc', secretKey, Buffer.alloc(16, '0'));
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const secretKey = crypto.randomBytes(32); // 生成一個32字節的密鑰
const text = 'Hello, World!';

const encryptedText = encrypt(text, secretKey);
console.log('Encrypted:', encryptedText);

const decryptedText = decrypt(encryptedText, secretKey);
console.log('Decrypted:', decryptedText);
  1. 使用Web Crypto API: 如果你在瀏覽器環境中工作,可以使用Web Crypto API進行加密。這是一個原生的JavaScript API,不需要任何外部庫。以下是一個使用AES-GCM算法進行加密和解密的例子:
async function encrypt(text, password) {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);
  const salt = crypto.getRandomValues(new Uint8Array(16));
  const keyMaterial = await window.crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'AES-GCM' },
    false,
    ['encrypt']
  );
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encryptedData = await window.crypto.subtle.encrypt(
    { name: 'AES-GCM', iv },
    keyMaterial,
    data
  );
  return {
    encryptedData: Array.from(new Uint8Array(encryptedData)),
    salt: Array.from(salt),
    iv: Array.from(iv)
  };
}

async function decrypt(encryptedData, salt, iv, password) {
  const encoder = new TextEncoder();
  const keyMaterial = await window.crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'AES-GCM' },
    false,
    ['decrypt']
  );
  const decryptedData = await window.crypto.subtle.decrypt(
    { name: 'AES-GCM', iv },
    keyMaterial,
    new Uint8Array(encryptedData)
  );
  return new TextDecoder().decode(decryptedData);
}

const password = 'my-password';
const text = 'Hello, World!';

encrypt(text, password).then(({ encryptedData, salt, iv }) => {
  console.log('Encrypted:', encryptedData);
  console.log('Salt:', salt);
  console.log('IV:', iv);

  decrypt(encryptedData, salt, iv, password).then(decryptedText => {
    console.log('Decrypted:', decryptedText);
  });
});

請注意,這些代碼示例僅用于演示目的,實際應用中需要考慮更多的安全措施,比如密鑰管理和存儲、錯誤處理、算法選擇等。在生產環境中,確保遵循最佳安全實踐。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女