crypto.generateKeyPair(type, options, callback)


生成给定 type 的新非对称密钥对。目前支持 RSA、RSA-PSS、DSA、EC、Ed25519、Ed448、X25519、X448 和 DH。

【Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC, Ed25519, Ed448, X25519, X448, and DH are currently supported.】

如果指定了 publicKeyEncodingprivateKeyEncoding,此函数的行为就好像在其结果上调用了 keyObject.export()。否则,密钥的相应部分将作为 KeyObject 返回。

【If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.】

建议将公钥编码为 'spki',私钥编码为 'pkcs8' 并加密以便长期存储:

【It is recommended to encode public keys as 'spki' and private keys as 'pkcs8' with encryption for long-term storage:】

const {
  generateKeyPair,
} = await import('node:crypto');

generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});const {
  generateKeyPair,
} = require('node:crypto');

generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});

完成后,callback 将被调用,err 的值为 undefinedpublicKey / privateKey 表示生成的密钥对。

【On completion, callback will be called with err set to undefined and publicKey / privateKey representing the generated key pair.】

如果以其 util.promisify()ed 版本调用此方法,它将返回一个包含 publicKeyprivateKey 属性的 ObjectPromise

【If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with publicKey and privateKey properties.】