使用加密模块的流功能获取文件的哈希值(即:没有 hash.update 和 hash.digest) [英] Obtaining the hash of a file using the stream capabilities of crypto module (ie: without hash.update and hash.digest)

查看:7
本文介绍了使用加密模块的流功能获取文件的哈希值(即:没有 hash.update 和 hash.digest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The crypto module of node.js (at the time of this writing at least) is not still deemed stable and so the API may change. In fact, the methods that everyone in the internet use to get the hash (md5, sha1, ...) of a file are considered legacy (from the documentation of Hash class) (note: emphasis mine):

类:哈希

用于创建数据哈希摘要的类.

The class for creating hash digests of data.

它是一个既可读又可写的流.写入的数据是用于计算哈希.一旦流的可写端是结束后,使用 read() 方法获取计算出的哈希摘要.这还支持旧的更新和摘要方法.

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.

由 crypto.createHash 返回.

Returned by crypto.createHash.

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

Despite hash.update and hash.digest being considered legacy, the example shown just above the quoted snippet is using them.

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

What's the correct way of obtaining hashes without using those legacy methods?

推荐答案

来自问题中引用的片段:

From the quoted snippet in the question:

【Hash 类】是一个可读可写的流.写入的数据是用于计算哈希.一旦流的可写端是结束,使用 read() 方法获取计算出的哈希摘要.

[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.

所以你需要对一些文本进行哈希处理:

So what you need to hash some text is:

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 并将其通过管道传输到哈希值中:

If you want to get the hash of a file, the best way is create a ReadStream from the file and pipe it into the hash:

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);

这篇关于使用加密模块的流功能获取文件的哈希值(即:没有 hash.update 和 hash.digest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆