在节点js中将文本转换为哈希

convert a text to hash in node js

我想使用节点 js 将文本转换为数字的哈希 ID。已经有一个 java 程序可以转换,但要使用节点 js 完成相同类型的实现。

Java代码

    public static long generateId(String text) {

    byte[] buffer = null;
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
        md.reset();
        buffer = text.getBytes(Charsets.UTF_8);

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    md.update(buffer);
    byte[] digest = md.digest();
    String hexStr = "";
    for (int i = 0; i < digest.length; i++) {
        hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
    }
    long hashid = 0;
    for (int i = 0; i < hexStr.length(); i++)
        hashid += Math.abs((long) Math.pow(27, 10 - i) * ('a' - (1 + hexStr.charAt(i))));

    return hashid;
}   

我能够转换成 nodejs upto digest 之后我无法继续。

function generateHashCode()
{
var text = '9/01/2017'+'xx'+'405'+''+'SDD'+'MDD'+'9';
var crypto = require('crypto');
console.log(crypto.createHash('SHA1').update(text).digest("hex"));
var hexDigest = crypto.createHash('SHA1').update(text).digest("hex");
var hexStr;
}

请帮我解决这个问题

function generateHashCode(text)
{
    // assuming text is UTF-8 encoded

    var crypto = require('crypto');
    var hexDigest = crypto.createHash('SHA1').update(text).digest(); // this should be .digest() not .digest('hex')

    var hexStr = "";
    for (var i = 0; i < hexDigest.length; i++) {
        hexStr += (((hexDigest[i] - 0x100) & 0xff) + 0x100).toString(16).substr(1); // fixed some math issues here
    }

    var hashid = 0;
    var a = 'a'.charCodeAt(0); // or just var a = 97;
    for (var i = 0; i < hexStr.length; i++)
        hashid += Math.abs(Math.pow(27, 10 - i) * (a - (1 + hexStr.charCodeAt(i))));

    return hashid;
}

console.log(generateHashCode("batman"));