【问题标题】:JavaScript - how to encrypt string with only password in 2020? [duplicate]JavaScript - 如何在 2020 年仅使用密码加密字符串? [复制]
【发布时间】:2020-09-17 23:19:41
【问题描述】:

我想用人类可读的密码加密/解密一个字符串。仅知道密码,加密数据应该是可解密的。 2020年推荐的工具是什么?

  1. 内置SubtleCrypto接口中的对称加密需要生成密钥(基于我找到的示例),并且它们还需要额外的数据来解密(计数器或iv值)。
  2. 相关SO question 6 岁

    const data = "Hello World";
    const key = "SuperSecret";
    
    const encrypted = encrypt(data, key);
    console.log(encrypted);  // gibberish
    
    const decrypted = decrypt(encrypted, key);
    console.log(decrypted);  // Hello World
    

【问题讨论】:

  • 链接页面上有一个aes-cbc示例
  • 可能最成熟且经过仔细分析的算法是 argon2 系列。不幸的是,它还没有被广泛实施。最广泛可用的相当不错的算法是pbkdf2
  • 您已经找到的问题可能很老,但有一些最近的答案,并且从那以后没有太多创新。请解释为什么您认为这些答案不能解决您的问题。顺便说一句,寻求建议是题外话。

标签: javascript encryption


【解决方案1】:

这里是一个例子,实现简单的加密/解密

// derive string key
async function deriveKey(password) {
  const algo = {
    name: 'PBKDF2',
    hash: 'SHA-256',
    salt: new TextEncoder().encode('a-unique-salt'),
    iterations: 1000
  }
  return crypto.subtle.deriveKey(
    algo,
    await crypto.subtle.importKey(
      'raw',
      new TextEncoder().encode(password),
      {
        name: algo.name
      },
      false,
      ['deriveKey']
    ),
    {
      name: 'AES-GCM',
      length: 256
    },
    false,
    ['encrypt', 'decrypt']
  )
}

// Encrypt function
async function encrypt(text, password) {
  const algo = {
    name: 'AES-GCM',
    length: 256,
    iv: crypto.getRandomValues(new Uint8Array(12))
  }
  return {
    cipherText: await crypto.subtle.encrypt(
      algo,
      await deriveKey(password),
      new TextEncoder().encode(text)
    ),
    iv: algo.iv
  }
}

// Decrypt function
async function decrypt(encrypted, password) {
  const algo = {
    name: 'AES-GCM',
    length: 256,
    iv: encrypted.iv
  }
  return new TextDecoder().decode(
    await crypto.subtle.decrypt(
      algo,
      await deriveKey(password),
      encrypted.cipherText
    )
  )
}

// example
;(async () => {
  // encrypt
  const encrypted = await encrypt('Secret text', 'password')

  // the cipher text
  console.log(
    String.fromCharCode.apply(null, new Uint8Array(encrypted.cipherText))
  )

  // decrypt it
  const decrypted = await decrypt(encrypted, 'password')
  console.log(decrypted) // Secret text
})()

【讨论】:

  • 您的 derivedKey 实现忽略了 algoName 和 length 参数。
  • 看不到,请解释或更新/编辑
猜你喜欢
  • 2020-07-02
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 2014-08-07
  • 2018-10-31
  • 2010-12-11
  • 1970-01-01
  • 2010-11-22
相关资源
最近更新 更多