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

时间:2017-02-04 02:18:03

标签: javascript java node.js hashcode

我想使用节点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转换为digest。

&#13;
&#13;
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;
}
&#13;
&#13;
&#13;

请帮助我

1 个答案:

答案 0 :(得分:0)

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