Created
July 20, 2014 08:27
-
-
Save hmalphettes/41c6cde062b4331cd0e5 to your computer and use it in GitHub Desktop.
Generate uuid-v5 in node
This file contains hidden or 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
var expect = require('chai').expect; | |
var UUID = require('./uuid-v5'); | |
describe('When generating a uuid v5', function() { | |
it('must generate the expected uuids from 3 examples on the web', function() { | |
var testUrl = UUID.v5(UUID.URL, 'www.example.org'); | |
var testDns = UUID.v5(UUID.DNS, 'www.example.org'); | |
var testDns2 = UUID.v5(UUID.DNS, 'php.net'); | |
// see the examples here: http://jsfiddle.net/rexmac/F3pwA/ | |
expect(testDns).to.equal('74738ff5-5367-5958-9aee-98fffdcd1876'); | |
expect(testUrl).to.equal('abe19220-c90c-5288-b33a-58772250d428'); | |
// see https://servicecore.info/tools/uuid-generator/ | |
expect(testDns2).to.equal('c4a760a8-dbcf-5254-a0d9-6a4474bd1b62'); | |
}); | |
}); |
This file contains hidden or 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
var crypto = require('crypto'); | |
function _hash(version, hash) { | |
return hash.substr(0,8) + '-' + | |
hash.substr(8,4) + '-' + | |
(version + hash.substr(13,3)) + '-' + | |
((parseInt(hash.substr(16, 2), 16) | 0x80) & 0xBF).toString(16) + hash.substr(18,2) + '-' + | |
hash.substr(20,12); | |
} | |
function uuidV5(namespace, name) { | |
var hexNm = namespace.replace(/[{}\-]/g, ''); | |
var bytesNm = new Buffer(hexNm, 'hex'); | |
var bytesName = new Buffer(name, 'utf8'); | |
var hash = crypto.createHash('sha1') | |
.update(bytesNm).update(bytesName) | |
.digest('hex'); | |
return _hash(5, hash); | |
} | |
module.exports = { | |
// well know uuid namespaces in rfc 1422 | |
DNS: '6ba7b810-9dad-11d1-80b4-00c04fd430c8', | |
URL: '6ba7b811-9dad-11d1-80b4-00c04fd430c8', | |
OID: '6ba7b812-9dad-11d1-80b4-00c04fd430c8', | |
X500: '6ba7b814-9dad-11d1-80b4-00c04fd430c8', | |
v5: uuidV5 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ported http://jsfiddle.net/rexmac/F3pwA/ that uses Crypto.js to node/browserify