生成 JSON Web 密钥集 (JWKS) 时的空密钥

Empty keys when generating JSON Web Key Set (JWKS)

我正在尝试创建一个 JSON 网络密钥集以用于 node.js API 客户端。但是,当记录我的密钥时,它们似乎是空的。

const {JWKS} = require("jose");
const keyAlg = "RSA";
const keySize = 2048;
const keyUse = "sig";
const alg = "RS256";
const keystore = new JWKS.KeyStore();
keystore.generate(keyAlg, keySize, {
  alg,
  use: keyUse,
});

console.log("Public keys");
console.log("This can be used as the jwks in your API client configuration in the portal");
console.log(JSON.stringify(keystore.toJWKS(), null, 4));
console.log("Private keys");
console.log("This can be used as the keys value when configuring the api client");
console.log(JSON.stringify(keystore.toJWKS(true), null, 4));

keystore.generate 是一个异步函数。它 returns 一个不会立即执行的承诺。您可以使用 .then 或 async/await 来获取承诺的结果。

这是来自图书馆 github 的 example

keystore.generate("oct", 256). then(function(result) { // {result} is a jose.JWK.Key key = result; });

将此应用于您的代码:

const {JWKS} = require("jose");
const keyAlg = "RSA";
const keySize = 2048;
const keyUse = "sig";
const alg = "RS256";
const keystore = new JWKS.KeyStore();
keystore.generate(keyAlg, keySize, {
  alg,
  use: keyUse,
}).then(function(result) {
  
  console.log(result);
  console.log("Public keys");
  console.log("This can be used as the jwks in your API client configuration in the portal");
  console.log(JSON.stringify(keystore.toJWKS(), null, 4));
  console.log("Private keys");
  console.log("This can be used as the keys value when configuring the api client");
  console.log(JSON.stringify(keystore.toJWKS(true), null, 4));
});

如果您是 javascript 异步函数的新手,请查看有关该主题的最热门问答: How do I return the response from an asynchronous call?