【问题标题】:Typescript is throwing an error with crypto generateKeyPair 'rsa'Typescript 使用加密 generateKeyPair 'rsa' 引发错误
【发布时间】:2021-07-12 22:44:53
【问题描述】:

我有一个函数,我正在尝试生成公钥和私钥 PEM 密钥字符串,我将使用私钥生成签名的 JWT 令牌并将公钥存储在数据库中。

NodeJS 版本在多个生产应用程序中运行,但将其添加到其中一个 typescript 项目时,我们遇到了一个神秘错误。

// javascript version
const newCrypto = () => {
  return new Promise((resolve, reject) => {
    try {
      crypto.generateKeyPair('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
          type: 'spki',
          format: 'pem'
        },
        privateKeyEncoding: {
          type: 'pkcs8',
          format: 'pem'
        }
      }, (err, publicKey, privateKey) => {
        if (err) throw err
        resolve({ publicKey, privateKey })
      })
    } catch (err) {
      reject(err)
    }
  })
}
// typescript version
const newCrypto = async (): Promise<any> => {
  crypto.generateKeyPair('rsa', {
    modulusLength: 1024,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  }, (err: Error, publicKey: string, privateKey: string) => {
    if (err) throw err
    return { publicKey, privateKey }
  })
}

这是我从 Typescript 得到的以下错误。花了一些时间谷歌搜索后,我在网上没有发现任何关于这个问题的信息。有人有什么想法吗?

No overload matches this call.
  The last overload gave the following error.
    Argument of type '"rsa"' is not assignable to parameter of type '"x448"'.

8   crypto.generateKeyPair('rsa', {

【问题讨论】:

    标签: node.js typescript cryptojs


    【解决方案1】:

    查看 crypto.d.ts 文件后,我发现回调函数可能会返回 null 来代替错误。

    下面是类型定义:

    function generateKeyPair(
            type: 'rsa',
            options: RSAKeyPairOptions<'pem', 'pem'>,
            callback: (err: Error | null, publicKey: string, privateKey: string) => void,
        ): void;
    

    解决方案:

    const newCrypto = async (): Promise<any> => {
      crypto.generateKeyPair('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
          type: 'spki',
          format: 'pem'
        },
        privateKeyEncoding: {
          type: 'pkcs8',
          format: 'pem'
        }
      }, (err: Error | null, publicKey: string, privateKey: string) => {
        if (err) throw err
        return { publicKey, privateKey }
      })
    }
    

    通过添加空回调错误类型,错误得到解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2011-02-24
      相关资源
      最近更新 更多