Phương thức crypto.createVerify() tạo và trả về một đối tượng verify sử dụng thuật toán được truyền vào tham số. Bạn có thể dùng crypto.getHashes() để lấy tên các thuật toán ký có sẵn. Bạn có thể tạo instance Verify bằng tên thuật toán chữ ký như 'RSA-SHA256' trong một số trường hợp, thay vì thuật toán digest.
Cú pháp
crypto.createVerify(algorithm, [options])
Tham số
algorithm – Tên thuật toán dùng để tạo đối tượng verify.
options – Tham số tùy chọn để kiểm soát hành vi stream.
Ví dụ
Tạo file createVerify.js và sao chép mã. Chạy lệnh:
node createVerify.js
createVerify.js
// Chương trình Node.js minh họa dùng createVerify()
// Import module crypto
const crypto = require('crypto');
// Tạo đối tượng verify với thuật toán nhập vào
const verify = crypto.createVerify('SHA256');
// Trả về đối tượng verify
console.log(verify);
Kết quả
C:\home\node>> node createVerify.js
Verify {
_handle: {},
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: { next: null, entry: null, finish: [Function: bound onCorkedFinish] }
},
writable: true,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined
}
Ví dụ 2
Xem thêm ví dụ minh họa xác thực chữ ký.
// Chương trình Node.js minh họa dùng createVerify()
// Import module crypto
const crypto = require('crypto');
// Tạo đối tượng verify từ thuật toán SHA256
const verify = crypto.createVerify('SHA256');
// Ghi dữ liệu cần ký và xác thực
verify.write('TutorialPoint');
// Kết thúc ghi
verify.end();
// Khối khóa công khai
const l1 = "-----BEGIN PUBLIC KEY-----\n";
const l2 = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXIvPbzLjaPLd8jgiv1TL/X8PXpJNgDkGRj9U9Lcx1 yKURpQFVavcMkfWyO8r7JlZNMax0JKfLZUM1IePRjHlFw==";
const l3 = "\n-----END PUBLIC KEY-----";
// Ghép khóa công khai
const publicKey = l1 + l2 + l3;
// Chữ ký cần xác thực
const signature = "MEYCIQCPfWhpzxMqu3gZWflBm5V0aetgb2/S+SGyGcElaOjgdgIhALaD4lbxVwa8HUUBFOLz+CGvI ioDkf9oihSnXHCqh8yV";
// In true nếu chữ ký hợp lệ, false nếu không
console.log(verify.verify(publicKey, signature));
Kết quả
C:\home\node>> node createVerify.js false