NodeJS md5 'bytestring' 喜欢 PHP md5(str, true)

NodeJS md5 'bytestring' like PHP md5(str, true)

我遇到了以下问题:我尝试将一些字符串 str 转换为 md5 bytestring hash。在 PHP 中我们可以使用 md5(str, true),但是在 JS (nodejs express) 中我找不到某种方法来接收相同的结果。我已经包含了 npm 模块 js-md5,但是这个模块的 arrayBuffer 方法 returns 另一个结果(不同于 PHP md5(str, true))。

有人能帮帮我吗

谢谢

使用 CryptoJS 模块: NPM link here

然后做类似的事情:

// Requires
var crypto = require('crypto');

// Constructor
function Crypto() {
    this.hash;
}

// Hash method
Crypto.prototype.encode = function(data) {
    this.hash = crypto.createHash('md5').update(data);
    var result = this.hash.digest('hex');
    return result;
};

// Comparison method (return true if === else false)
Crypto.prototype.equals = function(data, model) {
    var bool = false;
    var data = data.toUpperCase();
    var model = String(model).toUpperCase();
    if (data == model){
        bool = true;
    } else {
        bool = false;
    }
    return bool;
};

// Exports
module.exports = Crypto;

然后在您的代码中实例化此 "tool" 对象并使用方法。
简单易行,同样的事情可以用其他加密方法完成,如 AES、SHA256 等。
关于 raw_output 选项(二进制答案,填充 16 位),您可以使用简单的函数轻松地将返回的 var 转换为二进制格式,请参阅 this SO post 了解如何操作。 玩得开心。

简答:

const crypto = require('crypto');
const buffer = crypto.createHash('md5').update(str).digest();

长答案: 你需要使用 NodeJS 的默认 crypto 模块(这里不需要依赖),它包含效用函数和 类 .它能够使用同步或异步方法为您创建散列(例如 MD5 或 SHA-1 散列)。名为 crypto.createHash(algorithm) 的简短实用函数可用于创建具有最少编码的哈希。如 the docs 指定:

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list-message-digest-algorithms will display the available digest algorithms.

现在,这个 createHash 函数 returns 一个 Hash 对象,它可以与流一起使用(您可以向它提供文件、HTTP 请求等)或字符串,如你所问。如果要使用字符串,请使用 hash.update(string) 对其进行哈希处理。此方法 returns 哈希本身,因此您可以将其与 .digest(encoding) 链接以生成字符串(如果设置了 encoding)或 Buffer(如果未设置)。由于您要求字节,我相信 Buffer 就是您想要的(BufferUint8Array 个实例)。

var md5 = require('md5');
console.log(md5('text'))