Sign 类


Sign 类是一个实用工具,用于生成签名。 它可以通过以下两种方式之一使用:

crypto.createSign() 方法用于创建 Sign 实例。 参数是要使用的哈希函数的字符串名称。 不能使用 new 关键字直接地创建 Sign 对象。

示例,使用 SignVerify 对象作为流:

const crypto = require('crypto');

const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
  namedCurve: 'sect239k1'
});

const sign = crypto.createSign('SHA256');
sign.write('要生成签名的数据');
sign.end();
const signature = sign.sign(privateKey, 'hex');

const verify = crypto.createVerify('SHA256');
verify.write('要生成签名的数据');
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('要生成签名的数据');
sign.end();
const signature = sign.sign(privateKey);

const verify = crypto.createVerify('SHA256');
verify.update('要生成签名的数据');
verify.end();
console.log(verify.verify(publicKey, signature));
// 打印: true

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() and sign.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