Reputation: 24804
Using the package hashids, I can obtain hashes (with encode and decode) from numbers.
var Hashids = require("hashids"),
hashids = new Hashids("this is my salt", 8);
var id = hashids.encode(1);
Is there a similar package to obtain hashes from strings? (with encode and decode)
Upvotes: 21
Views: 9953
Reputation: 2828
here's a quick implementation for sqids.js (formerly hashids), using code from hashids.encodeHex method and includes the buffer toString hex workaround from @roman-rhrn-nesterov above:
function convertStringToNumbers(input) {
const hex = Buffer.from(input).toString('hex');
return Array.from({ length: Math.ceil(hex.length / 12) }, (_, i) => Number.parseInt(`1${hex.slice(i * 12, (i + 1) * 12)}`, 16));
}
const sqids = new Sqids()
const id = sqids.encode( convertStringToNumbers( 'any string' ) );
! This code does not provide a decode method, you have to adapt decodeHex() for that part.
Upvotes: 0
Reputation: 9
Getting hex without Node's Buffer.from ( to use with 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)),"");
Upvotes: 1
Reputation: 3673
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'
Upvotes: 37