Node.js KeyObject.from() 方法
keyObject.form()方法是crypto 模块中keyObject 类的内置应用程序编程接口,用于转换KeyObject 中的CryptoKey 实例。它是 KeyObject 类的静态方法。
句法:
keyObject.form( key )
参数:此方法仅采用下面描述的一个参数。
- key:此参数保存 CryptoKey 值。
返回值:此方法将实例返回给 KeyObject。
例子:
文件名:index.js
Javascript
// Node.js program to demonstrate the
// keyObject.form() method
// Importing the crypto module
const { webcrypto: { subtle }, KeyObject }
= require('crypto');
// Generating the crypto key that is
// not a keyObject instance
(async function () {
const key = await subtle.generateKey({
name: 'HMAC',
hash: 'SHA-256',
length: 256
}, true, ['sign', 'verify']);
try {
// Calling keyObject.form() method to
// get the instance to keyObject
const keyObject = KeyObject.from(key);
console.log("Successfully converted a "
+ "cryptoKey to instance of keyObject");
}
catch (error) {
console.log("Error has been occured");
}
})();
使用以下命令运行index.js文件:
node index.js
输出:
Successfully converted a cryptoKey to instance of keyObject.
参考:https://nodejs.org/api/crypto.html#crypto_class_keyobject