使用 jose 创建 JWK 和 JWS,但出现错误 "unsupported algorithm"

creating JWK and JWS using jose, however getting error "unsupported algorithm"

我必须使用 ES256 算法加密负载。还必须按照下面的代码所述在 JWK 中使用 kid。我正在使用 jose 库来创建签名。下面是代码:

var jose = require("node-jose");

async function a1(){
    try {
    const keystore = [
  {
    kty: 'EC',
    kid: '6d858102402dbbeb0f9bb711e3d13a1229684792db4940db0d0e71c08ca602e1',
    use: 'sig',
    alg:'ES256'
  }
]
const ks = await jose.JWK.asKeyStore(keystore);
const rawKey = ks.get(keystore[0].kid)
const key =  await jose.JWK.asKey(rawKey);

const payload =JSON.stringify({"sub": "1234567890",  "name": "Eric D.",  "role": "admin","iat": 1516239022});
    
const token =await jose.JWS.createSign({alg: "ES256", format: 'compact'}, key).update(payload, "utf8").final();

    }catch (err) {
    console.log(err);
  }
    
}
a1();

但我收到错误消息:

unsupported algorithm.

请告诉我为什么会出现这个问题。

alg参数({alg: 'ES256'})正确但提供的JWK不完整,缺少some parameters.

您必须提供曲线(crv)、x和y坐标(xy)和ECC私钥(d)。

  const keystore = [
  {
    kty: 'EC',
    kid: '6d858102402dbbeb0f9bb711e3d13a1229684792db4940db0d0e71c08ca602e1',
    use: 'sig',
    alg:'ES256',
    crv: "P-256",
    x  : "SVqB4JcUD6lsfvqMr-OKUNUphdNn64Eay60978ZlL74",
    y  : "lf0u0pMj4lGAzZix5u4Cm5CMQIgMNpkwy163wtKYVKI",
    d  : "0g5vAEKzugrXaRbgKG0Tj2qJ5lMP4Bezds1_sTybkfk"    
  }]

上例中 x、y 和 d 的值取自 this article, but usally you have to generate your own key, which is also described in the linked article or by using an online key generator

结果将是一个签名令牌:

eyJhbGciOiJFUzI1NiIsImtpZCI6IjZkODU4MTAyNDAyZGJiZWIwZjliYjcxMWUzZDEzYTEyMjk2ODQ3OTJkYjQ5NDBkYjBkMGU3MWMwOGNhNjAyZTEifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkVyaWMgRC4iLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE1MTYyMzkwMjJ9.gmVcj7rcENUDesVOSKRzvcMbxT_3zf2Sz771pdy3E1t4P-aKFxV1Vkcry2gvoQ1k11xvE0RSs3jYa13qsjFAzg

注意:令牌是签名令牌,负载未加密。如果您 need/require 负载加密,请考虑创建加密令牌 (JWE)。