给定一个 P-256 椭圆曲线 Diffie-Hellman 私钥(它只是一个随机的 256 位整数):是否可以使用 window.crypto.subtle.importKey() 方法将此私钥导入 CryptoKey 对象Web Crypto API – 没有公钥组件?
我知道如果公钥组件(从私钥组件派生)也可用,则可以导入私钥。例如,下面的代码运行成功:
window.crypto.subtle.importKey(
"jwk", //can be "jwk" (public or private), "raw" (public only), "spki" (public only), or "pkcs8" (private only)
{
"crv":"P-256",
"d":"eM8u2176zFk9bwDP_jbJqnm-TlSo6GX702D9I_1AqBU",
"ext":true,
"key_ops":["deriveKey","deriveBits"],
"kty":"EC",
"x":"5Uw_SuaGZTFAuQuDArnLEmmyp4TpHx3AlBxL4EUEzbQ",
"y":"RO5t581VBuAKTQZVPSB__ebV6y9GCzrl8lBV2-p9BlM"
},
{ //these are the algorithm options
name: "ECDH",
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)
["deriveKey"] //"deriveKey" and/or "deriveBits" for private keys only (just put an empty list if importing a public key)
)
.then(function(key) {
console.log(key);
})
.catch(function(err){
console.error(err);
});
但是,如果只有私钥组件可用,而没有公钥组件,如下面的代码所示,Web Crypto API 会引发 DOMException,并显示消息“提供给操作的数据不符合要求”。
window.crypto.subtle.importKey(
"jwk", //can be "jwk" (public or private), "raw" (public only), "spki" (public only), or "pkcs8" (private only)
{
"crv":"P-256",
"d":"eM8u2176zFk9bwDP_jbJqnm-TlSo6GX702D9I_1AqBU",
"ext":true,
"key_ops":["deriveKey","deriveBits"],
"kty":"EC"
},
{ //these are the algorithm options
name: "ECDH",
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)
["deriveKey"] //"deriveKey" and/or "deriveBits" for private keys only (just put an empty list if importing a public key)
)
.then(function(key) {
console.log(key);
})
.catch(function(err){
console.error(err);
});
我也尝试过使用 pkcs8 格式作为密钥,而不是 JWK,但也没有运气。
Web Crypto API 的文档显示可以导入 JWK 格式的 ECDH 私钥 - 因此,似乎在没有公钥组件的情况下也可以这样做(Web Crypto API 应该能够如果需要,从内部的私钥组件计算公钥组件,就像使用 .generateKey() 方法一样)。但是,importKey() 方法似乎仅在包含公钥组件时才有效。
我在这里错过了什么吗?如果没有,是否有人知道解决方案或解决方法,在导入之前单独计算公钥组件,并将它们与私钥组件一起包含在 importKey() 方法中(这似乎过于繁琐且不必要)?