diff --git a/lib/crypto.js b/lib/crypto.js index bff21f6dd65799..756adb7b6aac51 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -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, @@ -169,6 +178,7 @@ module.exports = exports = { scryptSync, setEngine, timingSafeEqual, + uuid, getFips: !fipsMode ? getFipsDisabled : fipsForced ? getFipsForced : getFipsCrypto, setFips: !fipsMode ? setFipsDisabled : diff --git a/test/parallel/test-crypto-uuid.js b/test/parallel/test-crypto-uuid.js new file mode 100644 index 00000000000000..8d5ecd460d48f5 --- /dev/null +++ b/test/parallel/test-crypto-uuid.js @@ -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)); +}