我的代码:
/*
Fetch the contents of the "message" textbox, and encode it
in a form we can use for the sign operation.
*/
function getMessageEncoding() {
const messageBox = 'hello world!';
let message = messageBox.value;
let enc = new TextEncoder();
return enc.encode(message);
}
async function main() {
let encoded = getMessageEncoding();
window.crypto.subtle.sign(
{
name: "ECDSA",
hash: { name: "SHA-384" },
},
{"alg":"ES256","crv":"P-256","d":"KRiXxoIFHmBQJdoCsqB8Bc9_f2Z-QCdRgoydMKdoL04","ext":true,"key_ops":["sign"],"kty":"EC","x":"FKwqyGd4i2NAl8RUXCCBRCAIbcpeGyfyXwgA_AWHb8Y","y":"njxhw5O6zGVkBlcPDKYj0E-6VO1giHTUkJWBhgKNqd8"},
encoded,
).then(signature => {
console.log(signature);
alert('test');
});
alert(signature);
}
main();
(私钥是虚拟私钥,不是生产私钥)
当我运行它时,它没有执行任何操作。我希望它将签名放入 JS 控制台?
这是 JS Fiddle 上的:
https://jsfiddle.net/pwuersfL/1/
有什么想法吗?
importKey()
的关键导入。 importKey()
将 JWK 转换为 CryptoKey
,可以通过 sign()
进行处理。
在以下代码中添加了缺少的导入(加上验证):
function getMessageEncoding() {
//const messageBox = 'hello world!';
//let message = messageBox.value;
let message = 'hello world!'; // for testing
let enc = new TextEncoder();
return enc.encode(message);
}
async function main() {
// sign
let encoded = getMessageEncoding();
let jwk = {"alg":"ES256","crv":"P-256","d":"KRiXxoIFHmBQJdoCsqB8Bc9_f2Z-QCdRgoydMKdoL04","ext":true,"key_ops":["sign"],"kty":"EC","x":"FKwqyGd4i2NAl8RUXCCBRCAIbcpeGyfyXwgA_AWHb8Y","y":"njxhw5O6zGVkBlcPDKYj0E-6VO1giHTUkJWBhgKNqd8"};
let key = await window.crypto.subtle.importKey("jwk", jwk, {name: "ECDSA", namedCurve: "P-256"},true,["sign"]); // Fix: import the key
let signature = await window.crypto.subtle.sign(
{
name: "ECDSA",
hash: { name: "SHA-384" },
},
key,
encoded,
);
console.log(ab2hex(signature));
// verify
jwk = {"alg":"ES256","crv":"P-256","ext":true,"key_ops":["verify"],"kty":"EC","x":"FKwqyGd4i2NAl8RUXCCBRCAIbcpeGyfyXwgA_AWHb8Y","y":"njxhw5O6zGVkBlcPDKYj0E-6VO1giHTUkJWBhgKNqd8"};
key = await window.crypto.subtle.importKey("jwk", jwk, {name: "ECDSA", namedCurve: "P-256"},true,["verify"]);
let verified = await window.crypto.subtle.verify(
{
name: "ECDSA",
hash: { name: "SHA-384" },
},
key,
signature,
encoded,
);
console.log(verified);
}
// helper: hex encoding
function ab2hex(ab) {
return Array.prototype.map.call(new Uint8Array(ab), x => ('00' + x.toString(16)).slice(-2)).join('');
}
main();