Sign 类
- 继承自: <stream.Writable>
Sign
类是用于生成签名的实用工具。
它可以通过以下两种方式之一使用:
- 作为可写流,写入要签名的数据,使用
sign.sign()
方法生成并返回签名,或者 - 使用
sign.update()
和sign.sign()
方法生成签名。
crypto.createSign()
方法用于创建 Sign
实例。
参数是要使用的哈希函数的字符串名称。
Sign
对象不能直接使用 new
关键字创建。
示例:使用 Sign
和 Verify
对象作为流:
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1'
});
const sign = crypto.createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = crypto.createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// 打印: true
示例:使用 sign.update()
和 verify.update()
方法:
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = crypto.createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);
const verify = crypto.createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// 打印: true
- Extends: <stream.Writable>
The Sign
class is a utility for generating signatures. It can be used in one
of two ways:
- As a writable stream, where data to be signed is written and the
sign.sign()
method is used to generate and return the signature, or - Using the
sign.update()
andsign.sign()
methods to produce the signature.
The crypto.createSign()
method is used to create Sign
instances. The
argument is the string name of the hash function to use. Sign
objects are not
to be created directly using the new
keyword.
Example: Using Sign
and Verify
objects as streams:
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1'
});
const sign = crypto.createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = crypto.createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
Example: Using the sign.update()
and verify.update()
methods:
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = crypto.createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);
const verify = crypto.createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true