Skip to content

Instantly share code, notes, and snippets.

@crotel
Last active July 26, 2021 03:51
Show Gist options
  • Save crotel/230011cb2bfb67d719b3883d2c1e56e8 to your computer and use it in GitHub Desktop.
Save crotel/230011cb2bfb67d719b3883d2c1e56e8 to your computer and use it in GitHub Desktop.
Generate Hash-ID in six way: random, hex, md5, sha1, uuid, udid. addon: a timestamp join-with random num.
/* getHash v10 */
/*
* Notice: UDID original base at localhost mac-addr, otherwise using tunnl and uuidEncode with remote mac-addr.
*
* Unique ID (random): hex.encode, sha1.encode, md5.encode, uuid([leave blank]),
* Decodable string: hex.encode,
* One-way transformation (one Time): sha1.encode, md5.encode, uuid([give value]), udid.
*
* ascii for encode and decode zh-chs char with ascii code.
* browser code fix get date block.
* lastModify: Jul/26/2021
*/
// var init = ((n) => {return n})(); // add custom suger if you want. but should make some change.
const getHash = {
timestamp: () => {return [ new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3, hour12: false, timeZone: 'Asia/Shanghai', dayPeriod: 'short', }) .format(new Date()) .replaceAll(/[\/\,\:\.\s]/g, '') .trim(), (Math.random() * 16).toString().split('.')[1], ].join('')},
random : (l, c) => { var s = ''; l = l || 40; c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz'; while (l > 0) { s += c.charAt(Math.floor(Math.random() * c.length)); l-- }; return s },
udid: () => { let hmac = ((nics) => { var nic, index, addr, retn; for (nic in nics) { for (index in nics[nic]) { addr = nics[nic][index]; if (!addr.internal) { if (addr.address.match('ff:fe')) { addr.address .slice(6) .split(/:/) .map(function (v, i, a) { retn = a[0].substring(0, 2) + a[0].slice(2) + a[1].substring(0, 2) + a[2].slice(2) + a[3].substring(0, 2) + a[3].slice(2); return retn; }); } } } } return retn; })(require('os').networkInterfaces()); let sha = require('crypto') .createHash('sha1') .update(hmac) .digest('hex'), md = require('crypto').createHash('md5').update(sha).digest('hex'); return ( md.substring(0, 8) + '-' + md.substring(8, 12) + '-' + md.substring(12, 16) + '-' + md.substring(16, 20) + '-' + md.substring(20) ); },
uuid: (e) => { let sha = require('crypto') .createHash('sha1') .update((e = e === undefined ? [ new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3, hour12: false, timeZone: 'Asia/Shanghai', dayPeriod: 'short', }) .format(new Date()) .replaceAll(/[\/\,\:\.\s]/g, '') .trim(), (Math.random() * 16).toString().split('.')[1], ].join('') : e.toString())) .digest('hex'), md = require('crypto').createHash('md5').update(sha).digest('hex'); return ( md.substring(0, 8) + '-' + md.substring(8, 12) + '-4' + md.substring(13, 16) + '-' + md.substring(16, 20) + '-' + md.substring(20) ); },
hex:{
encode: (c, b) => { let suger = Buffer.from(b, 'utf8').toString('hex'); console.log(suger); let buff = Buffer.from(c.toString()).toString('hex'); return Buffer.from([buff, suger].join(''), 'utf8').toString('hex'); },
decode: (c, br) => { let r = Buffer.from(c, 'hex').toString('utf8'), rxp = br !== '' ? RegExp(br) : RegExp('error'), o = rxp.test(r) ? r.replace(br, '') : 'error'; return Buffer.from(o, 'hex').toString('utf8'); },
verify: (n, c) => { let dn = Buffer.from(n.toString(), 'utf8').toString('hex'); if (dn === c) { return true; } return false; }
},
md5: {
random: require('crypto').createHash('md5').update([ new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3, hour12: false, timeZone: 'Asia/Shanghai', dayPeriod: 'short', }) .format(new Date()) .replaceAll(/[\/\,\:\.\s]/g, '') .trim(), (Math.random() * 16).toString().split('.')[1], ].join('')).digest('hex'),
encode: (c) => { return require('crypto') .createHash('md5') .update(Buffer.from(c.toString(), 'utf8').toString('hex')) .digest('hex'); },
verify: (n, c) => { let dn = require('crypto') .createHash('md5') .update(Buffer.from(n.toString(), 'utf8').toString('hex')) .digest('hex'); if (dn === c) { return true; } return false; }
},
sha1: {
random: require('crypto') .createHash('sha1') .update([ new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3, hour12: false, timeZone: 'Asia/Shanghai', dayPeriod: 'short', }) .format(new Date()) .replaceAll(/[\/\,\:\.\s]/g, '') .trim(), (Math.random() * 16).toString().split('.')[1], ].join('')) .digest('hex'),
encode: (c) => { return require('crypto') .createHash('sha1') .update(Buffer.from(c.toString(), 'utf8').toString('hex')) .digest('hex'); },
verify: (n, c) => { let dn = require('crypto') .createHash('sha1') .update(Buffer.from(n.toString(), 'utf8').toString('hex')) .digest('hex'); if (dn === c) { return true; } return false; }
},
ascii:{
encode: (n) => { let buf = []; for (let i = n.length - 1; i >= 0; i--) { buf.unshift(['&#', n[i].charCodeAt(), ';'].join('')); } return buf.join(''); },
decode: (n) => { return n.replace(/&#(\d+);/g, function (match, dec) { return String.fromCharCode(dec); })}},
};
exports.timestamp = getHash.timestamp;
exports.random = getHash.random;
exports.ascii = getHash.ascii;
exports.hex = getHash.hex;
exports.sha1 = getHash.sha1;
exports.md5 = getHash.md5;
exports.uuid = getHash.uuid;
exports.udid = getHash.udid;
/* method sample */
/*
const {random,ascii,hex,sha1,md5,uuid,udid} = require('./getHash');
random() >> result 'FCCLqa6yNrgRLiWOPZN3p4KbkzOg1LtVoRU6JZvx' // random, with empty arg, math with default length 40
random(32) >> result 'JSd7LjhpFInqVKWPimhGMybhrop0muMH' // random, length 32, arg was type num.
hex.encode('apple') >> result '6170706c65' // unique, weak hex encode
hex.decode('6170706c65') >> result 'apple' // hex decode which using weak hex encode above
hex.verify('apple','6170706c65') >> result true // verify hex which using weak hex encode above and original string
sha1.random >> result '9759728908b7d440bbc78c11a17ca27a98d6eafa' // random, one-way transformation
sha1.encode('apple') >> result '0e7e3e4f35908aafbc2a8b648a328eca5a883e9c' // unique, one-way transformation
sha1.verify('apple','0e7e3e4f35908aafbc2a8b648a328eca5a883e9c') >> result true // verify sha1
md5.random >> result 'db31d9bccc6611f325320667a6b07e11' // random, one-way transformation
md5.encode('apple') >> result '69177a5df5c45b15738f7447dab78417' // unique, one-way transformation
md5.verify('apple','69177a5df5c45b15738f7447dab78417') >> result true // verify md5
uuid() >> result '281cb9fa-0db4-44af-96dc-f12ae796ab1b' // random uuid format base at time string, measure of milliseconds
uuid('apple') >> result '1ac6b15d-59ca-489c-c5f4-48131045f648' // unique, one-way transformation
uuid(1) >> result '7055eced-1553-8bfb-7c07-f8a5b28fc5d0' // unique, one-way transformation, even type number ( for example num 1 ) is acceptable.
udid() >> result '64ea488e-85b4-f740-fb9a-c0c9a55a28dc' // unique, one-way transformation
ascii.encode("你好世界") >> result '你好世界'
ascii.decode("你好世界") >> result '你好世界'
*/
/* browser compatibility time-based random uuid */
/*
var uuid = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { let n = (Math.floor(Date.now() / 16) + Math.random() * 16) % 16 | 0; return (c === 'x' ? n : (n & 0x3) | 0x8).toString(16)})}
uuid();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment