Javascript crypto.subtle.generateKey仍然提供相同的密钥?

时间:2017-08-26 06:38:30

标签: javascript cryptography

我有以下javascript。它应该生成一个ECDSA公钥 - 私钥对,并将BASE64编码的公钥作为字符串打印到控制台。我希望它能在每次重新加载时生成一个新密钥。但它总是打印相同的,我不明白为什么。它是否始终生成相同的密钥?该怎么做才能得到一个新钥匙?

JSfiddle:https://jsfiddle.net/35bk4maw/

window.crypto.subtle.generateKey(
   {
      name: "ECDSA",
      namedCurve: "P-256", //can be "P-256", "P-384", or "P-521"
   },
   true, //whether the key is extractable (i.e. can be used in exportKey)
   ["sign", "verify"] //can be any combination of "sign" and "verify"
)
.then(function(key)
{
   window.crypto.subtle.exportKey(
       "spki", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
       key.publicKey //can be a publicKey or privateKey, as long as extractable was true
    ).then(function(keydata)
    {
        // this always prints something like "A21ixmVqdCBccnOheQJ1cmNlcl0="
        // I would expect it to print different string on each reload!
        console.log(btoa(keydata));
    })
     .catch(function(err){ console.error(err); });
}).catch(function(err){ console.error(err); });

1 个答案:

答案 0 :(得分:0)

最后我发现了什么是错的,所以我会回答我自己的问题。 问题是当调用btoa(keydata)时,它不理解ArrayBuffer参数,因此它计算转换为字符串的keydata的BASE64。任何转换为​​字符串的ArrayBuffer总是“[ArrayBuffer Object]”。因此,此字符串的base64编码结果始终为W29iamVjdCBBcnJheUJ1ZmZlcl0 =

因此,为了让我以某种可读的形式打印ArrayBuffer内容,我需要使用不同的方式来编码它,这个答案帮我打印公钥的十六进制: Javascript ArrayBuffer to Hex