【问题标题】:How to set the out-length with the Web Crypto API SubtleCrypto.deriveKey() for PBKDF2如何使用 Web Crypto API SubtleCrypto.deriveKey() 为 PBKDF2 设置外长
【发布时间】:2018-11-22 00:54:56
【问题描述】:

根据doc一个简单的例子,用PBKDF2导出密码是

  return window.crypto.subtle.importKey(
    'raw', 
    encoder.encode(password), 
    {name: 'PBKDF2'}, 
    false, 
    ['deriveBits', 'deriveKey']
  ).then(function(key) {
    return window.crypto.subtle.deriveKey(
      { "name": 'PBKDF2',
        "salt": encoder.encode(salt),
        "iterations": iterations,
        "hash": 'SHA-256'
      },
      key,
      { "name": 'AES-CTR', "length": 128 }, //api requires this to be set
      true, //extractable
      [ "encrypt", "decrypt" ] //allowed functions
    )
  }).then(function (webKey) {
    return crypto.subtle.exportKey("raw", webKey);
  })

正如人们所看到的,API 允许您选择:

  • 密钥派生函数(及其底层哈希)
  • 迭代
  • 原始密钥材料(即密码)

但据我所知,没有选择外长的选项。 似乎密码套件参数{ "name": 'AES-CTR', "length": 128 }会影响输出长度,但您只能选择16和32字节。

例如 10,000 轮,salt: 'salt', password: 'key material' 为 128 会产生以下 16 个字节:

26629f0e2b7b14ed4b84daa8071c648c

{ "name": 'AES-CTR', "length": 256 } 你会得到

26629f0e2b7b14ed4b84daa8071c648c648d2cce067f93e2c5bde0c620030521

如何将输出长度设置为 16 或 32 字节?我必须自己截断它吗?

【问题讨论】:

    标签: javascript pbkdf2 webcrypto-api


    【解决方案1】:
    带有 AES 算法选项的

    deriveKey 函数会返回 AES 密钥。可能的 AES 密钥长度参数如下(bits):

    • 128
    • 192
    • 256

    因此,在使用 AES 密码时,您只能从它们中进行选择。在我看来,修改 deriveKey 函数生成的密钥是一个 的想法。首先,您将打破算法标准,并且将来您将遇到使用截断密钥的问题。

    但如果您只想使用 PBKDF2 并从密码中派生 bits,则可以使用 deriveBits 函数。这是一个例子:

    window.crypto.subtle.deriveBits(
            {
                name: "PBKDF2",
                salt: window.crypto.getRandomValues(new Uint8Array(16)),
                iterations: 50000,
                hash: {name: "SHA-256"}, // can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
            },
            key, //your key from generateKey or importKey
            512 //the number of bits you want to derive, values: 8, 16, 32, 64, 128, 512, 1024, 2048
        )
        .then(function(bits){
            //returns the derived bits as an ArrayBuffer
            console.log(new Uint8Array(bits));
        })
        .catch(function(err){
            console.error(err);
        });
    

    更多示例在这里 - https://github.com/diafygi/webcrypto-examples#pbkdf2---derivekey

    另外,我已经测试了派生位的可能值,它们是 2 的幂(从 8 到 2048)。

    希望对你有所帮助。请记住,如果您只想使用 AES 密码,最好使用默认值和 deriveKey 函数。

    【讨论】:

    • 啊,我明白了。这只是对 API 的误解。不幸的是,似乎没有developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/… 的文档,所以这很糟糕。我习惯了 derivedBits 样式(我只需要字节)。
    • 是的,你是对的,deriveBits 没有文档。也许,他们决定简化 API 并添加 deriveKey 而不是 deriveBits
    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 2016-02-19
    • 2022-10-18
    • 2019-04-11
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    相关资源
    最近更新 更多