Created
August 13, 2018 15:46
-
-
Save JCloudYu/f039969f0c7d785a145a0761cc144d11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require( 'crypto' ); | |
module.exports = { | |
UUIDv4(){ | |
let random_num = crypto.randomBytes(16); | |
random_num[6] = (random_num[6] & 0x0f) | 0x40; | |
random_num[8] = (random_num[8] & 0x3f) | 0x80; | |
return [ | |
random_num.slice(0, 4).toString('hex'), | |
random_num.slice(4, 6).toString('hex'), | |
random_num.slice(6, 8).toString('hex'), | |
random_num.slice(8, 10).toString('hex'), | |
random_num.slice(10, 16).toString('hex') | |
].join('-').toUpperCase(); | |
}, | |
_UUIDv35( version, value, namespace ) { | |
let val = Buffer.from(value); | |
let ns = Buffer.from(namespace); | |
let bytes = crypto.createHash(version === 3 ? 'md5' : 'sha1').update(Buffer.concat([ns, val])).digest(); | |
bytes[6] = (bytes[6] & 0x0f) | 0x50; | |
bytes[8] = (bytes[8] & 0x3f) | 0x80; | |
return [ | |
bytes.slice( 0, 4).toString('hex'), | |
bytes.slice( 4, 6).toString('hex'), | |
bytes.slice( 6, 8).toString('hex'), | |
bytes.slice( 8, 10).toString('hex'), | |
bytes.slice(10, 16).toString('hex') | |
].join('-').toUpperCase(); | |
}, | |
UUIDv3(...args){ return this._UUIDv35(3, ...args); }, | |
UUIDv5(...args){ return this._UUIDv35(5, ...args); }, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment