crypto.generateKeyPairSync(type, options)
type<string> 要生成的非对称密钥类型。请参阅支持的 非对称密钥类型。options<Object>modulusLength<number> 密钥位大小(RSA,DSA)。publicExponent<number> 公共指数 (RSA)。默认值:0x10001。hashAlgorithm<string> 消息摘要的名称 (RSA-PSS)。mgf1HashAlgorithm<string> 用于 MGF1(RSA-PSS)的消息摘要算法名称。saltLength<number> 最小盐长度(字节)(RSA-PSS)。divisorLength<number>q的位数(DSA)。namedCurve<string> 使用的曲线名称(椭圆曲线)。prime<Buffer> 质数参数(DH)。primeLength<number> 以比特为单位的素数长度(DH)。generator<number> 自定义生成器 (DH)。默认值:2。groupName<string> Diffie-Hellman 组名 (DH)。参见crypto.getDiffieHellman()。paramEncoding<string> 必须是'named'或'explicit'(EC)。 默认值:'named'。publicKeyEncoding<Object> 参见keyObject.export()。privateKeyEncoding<Object> 参见keyObject.export()。
- 返回:<Object>
publicKey<string> | <Buffer> | <KeyObject>privateKey<string> | <Buffer> | <KeyObject>
生成给定 type 的新的非对称密钥对。目前支持 RSA、RSA-PSS、DSA、EC、Ed25519、Ed448、X25519、X448、DH 和 ML-DSA1。
【Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, DH, and ML-DSA1 are currently supported.】
如果指定了 publicKeyEncoding 或 privateKeyEncoding,此函数的行为就好像在其结果上调用了 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',并且应保持密码的保密性。
【When encoding public keys, it is recommended to use 'spki'. When encoding
private keys, it is recommended to use 'pkcs8' with a strong passphrase,
and to keep the passphrase confidential.】
const {
generateKeyPairSync,
} = await import('node:crypto');
const {
publicKey,
privateKey,
} = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
});const {
generateKeyPairSync,
} = require('node:crypto');
const {
publicKey,
privateKey,
} = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
});返回值 { publicKey, privateKey } 表示生成的密钥对。当选择 PEM 编码时,相应的密钥将是一个字符串,否则它将是一个包含以 DER 编码的数据的缓冲区。
【The return value { publicKey, privateKey } represents the generated key pair.
When PEM encoding was selected, the respective key will be a string, otherwise
it will be a buffer containing the data encoded as DER.】