node.js - 使用加密模块的流功能获取文件的哈希(即 : without hash. 更新和 hash.digest)

标签 node.js hash stream

crypto node.js 的模块(至少在撰写本文时)仍未被认为是稳定的,因此 API 可能会更改。事实上,互联网上每个人用来获取文件哈希(md5,sha1,...)的方法都被认为是遗留的(来自 Hash class 的文档)(注意:强调我的):

Class: Hash

The class for creating hash digests of data.

It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. The legacy update and digest methods are also supported.

Returned by crypto.createHash.

尽管 hash.updatehash.digest 被认为是旧版,但引用片段上方显示的示例正在使用它们。

在不使用这些旧方法的情况下获取哈希的正确方法是什么?

最佳答案

来自问题中引用的片段:

[the Hash class] It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest.

所以你需要散列一些文本是:

var crypto = require('crypto');

// change to 'md5' if you want an MD5 hash
var hash = crypto.createHash('sha1');

// change to 'binary' if you want a binary hash.
hash.setEncoding('hex');

// the text that you want to hash
hash.write('hello world');

// very important! You cannot read from the stream until you have called end()
hash.end();

// and now you get the resulting hash
var sha1sum = hash.read();

如果要获取文件的哈希,最好的方法是从文件中创建一个 ReadStream 并将其通过管道传输到哈希中:

var fs = require('fs');
var crypto = require('crypto');

// the file you want to get the hash    
var fd = fs.createReadStream('/some/file/name.txt');
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');

fd.on('end', function() {
    hash.end();
    console.log(hash.read()); // the desired sha1sum
});

// read all file and pipe it (write it) to the hash object
fd.pipe(hash);

关于node.js - 使用加密模块的流功能获取文件的哈希(即 : without hash. 更新和 hash.digest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658612/

相关文章:

c# - 具有 2 个不同读者的阅读流

javascript - expressjs中的路由错误

javascript - 使用 mongoose 查询嵌套文档

ruby - 如何根据哈希值合并两个哈希数组?

perl - 如何在 Perl 中访问存储在散列中的数组元素?

c# - 流式传输 IEnumerable

html - 在页面中嵌入 PDF 字节流的问题

javascript - 如何使用自定义日期格式的 find() 方法从集合中检索数据

javascript - 为什么console.log传递不同的参数会得到不同的结果?

security - 密码哈希 : Is this a way to avoid collisions?