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



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

爪哇代码

    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 以消化,我无法继续。

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

相关内容

  • 没有找到相关文章

最新更新