Íca*_*ota 2 node.js async-await typescript
好的,所以我尝试使用加密生成公钥和私钥(https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback)
问题是,generateKeyPair 的参数之一是回调函数,我无法让我的代码等待回调运行。它最终会运行,但那时我已经尝试使用这些数据。我们的想法是做这样的事情:
const _getKeyPair = (pwd: string): Object => {
const { generateKeyPair }: any = require('crypto');
const keyPair = { publicKey: '', privateKey: '' };
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: pwd
}
}, (err: Error, publicKey: string, privateKey: string) => {
if (err) {
throw err;
}
keyPair.publicKey = publicKey;
keyPair.privateKey = privateKey;
});
return keyPair;
};
Run Code Online (Sandbox Code Playgroud)
并致电:
const keyPair = _getKeyPair('myPassword');
Run Code Online (Sandbox Code Playgroud)
crypto有两种方法来生成密钥对,一种是异步方法generateKeyPair,一种是同步方法generateKeyPairSync,您可以使用这两种方法而不必担心回调(如果您需要的话)。另一种方法是用 Promise 和 use 包装该方法await。就像是:
const _getKeyPair = async (pwd) => {
const { generateKeyPair } = require('crypto');
return new Promise((resolve, reject) => {
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: pwd
}
}, (err, publicKey, privateKey) => {
if (err) return reject(err);
resolve({publicKey, privateKey});
});
});
};
async function main() {
const keyPair = await _getKeyPair('myPassword');
}
main();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1266 次 |
| 最近记录: |