«

JS的加密函数

时间:2023-11-30 14:01     作者:wen     分类: F2E


JavaScript自身提供了一些简单的加密函数,其中最常见的是哈希函数。在浏览器环境中,你可以使用 window.crypto.subtle API 进行更高级的加密操作,包括对称加密、非对称加密等。以下是一些常见的加密函数和API的示例:

  1. MD5哈希(JavaScript原生实现):
    JavaScript本身并没有提供MD5哈希函数,但你可以使用以下函数进行简单的实现:
function md5(str) {
  const encoder = new TextEncoder();
  const data = encoder.encode(str);
  const hashBuffer = crypto.subtle.digest('MD5', data);
  return hashBuffer.then(buffer => {
    const hashArray = Array.from(new Uint8Array(buffer));
    return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
  });
}

// 使用示例
const originalString = 'Hello, World!';
md5(originalString).then(hash => console.log('MD5 Hash:', hash));
  1. SHA-256哈希(JavaScript原生实现):
function sha256(str) {
  const encoder = new TextEncoder();
  const data = encoder.encode(str);
  const hashBuffer = crypto.subtle.digest('SHA-256', data);
  return hashBuffer.then(buffer => {
    const hashArray = Array.from(new Uint8Array(buffer));
    return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
  });
}

// 使用示例
const originalString = 'Hello, World!';
sha256(originalString).then(hash => console.log('SHA-256 Hash:', hash));
  1. AES对称加密(使用window.crypto.subtle API):
async function encryptAES(text, key) {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);

  const cryptoKey = await crypto.subtle.importKey('raw', encoder.encode(key), 'AES-GCM', true, ['encrypt']);
  const encryptedData = await crypto.subtle.encrypt({ name: 'AES-GCM' }, cryptoKey, data);

  const encryptedArray = Array.from(new Uint8Array(encryptedData));
  return btoa(String.fromCharCode.apply(null, encryptedArray));
}

// 使用示例
const originalString = 'Hello, World!';
const key = 'MySecretKey123';
encryptAES(originalString, key).then(encrypted => console.log('Encrypted String:', encrypted));

这里的代码使用了 window.crypto.subtle API,该API提供了对底层加密操作的访问。请注意,这是一个异步API,因此需要使用 async/await 或 .then() 进行处理。在实际应用中,请确保对密钥进行安全的管理和存储,并使用适当的加密算法。

标签: javascript