Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: add a crypto.uuid() method #23441

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,15 @@ function createVerify(algorithm, options) {
return new Verify(algorithm, options);
}

function uuid() {
// Generate 32 random hexadecimal characters
const src = randomBytes(16).toString('hex');

// The 13th random hex character is discarded and replaced with '4'
return `${src.substr(0, 8)}-${src.substr(8, 4)}-4${src.substr(13, 3)}` +
`-${src.substr(16, 4)}-${src.substr(20, 32)}`;
}

module.exports = exports = {
// Methods
createCipheriv,
Expand Down Expand Up @@ -169,6 +178,7 @@ module.exports = exports = {
scryptSync,
setEngine,
timingSafeEqual,
uuid,
getFips: !fipsMode ? getFipsDisabled :
fipsForced ? getFipsForced : getFipsCrypto,
setFips: !fipsMode ? setFipsDisabled :
Expand Down
17 changes: 17 additions & 0 deletions test/parallel/test-crypto-uuid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');

const assert = require('assert');
const crypto = require('crypto');

const UUID_V4_REGEX =
/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}/;

// Test crypto.randomBytes() implementation
for (let i = 0; i < 100; i++) {
const uuid = crypto.uuid();
assert.ok(UUID_V4_REGEX.test(uuid));
}