【问题标题】:get hash from strings, like hashids从字符串中获取哈希值,例如 hashids
【发布时间】:2014-11-06 14:21:50
【问题描述】:

使用包hashids,我可以从数字中获取哈希值(带编码和解码)。

    var Hashids = require("hashids"),
        hashids = new Hashids("this is my salt", 8);
    
    var id = hashids.encode(1);

是否有类似的包来从字符串中获取哈希? (带编码和解码)

【问题讨论】:

    标签: node.js hash hashids


    【解决方案1】:
    var Hashids = require("hashids");
    var hashids = new Hashids("this is my salt");
    
    var hex = Buffer.from('Hello World', 'utf8').toString('hex');
    console.log (hex); // '48656c6c6f20576f726c64'
    
    var encoded = hashids.encodeHex(hex);
    console.log (encoded); // 'rZ4pPgYxegCarB3eXbg'
    
    var decodedHex = hashids.decodeHex('rZ4pPgYxegCarB3eXbg');
    console.log (decodedHex); // '48656c6c6f20576f726c64'
    
    var string = Buffer.from('48656c6c6f20576f726c64', 'hex').toString('utf8');
    console.log (string); // 'Hello World'
    

    【讨论】:

    • 缓冲区?我在哪里可以找到它?谢谢!
    • 客户端?浏览器...:)
    • @Eusthace Buffer 是 Node.js 核心 api 的一部分 - nodejs.org/api/… 您可以使用 npmjs.com/package/buffer 获得浏览器支持
    【解决方案2】:

    在没有节点的 Buffer.from 的情况下获取十六进制(与 hashids.decodeHex 一起使用)

    const toHex = (str: string): string => str.split("")
            .reduce((hex, c) => hex += c.charCodeAt(0).toString(16).padStart(2, "0"), "")
    const toUTF8 = (num: string): string =>
            num.match(/.{1,2}/g)
                .reduce((acc, char) => acc + String.fromCharCode(parseInt(char, 16)),"");
    

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2015-10-01
      • 2018-09-01
      • 2017-05-28
      • 1970-01-01
      • 2015-12-20
      • 2023-03-16
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多