Skip to content

Commit 7fe2162

Browse files
committed
1 parent e4dea40 commit 7fe2162

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

lib/crypto.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,15 @@ function createVerify(algorithm, options) {
139139
return new Verify(algorithm, options);
140140
}
141141

142+
function uuid() {
143+
// Generate 32 random hexadecimal characters
144+
const src = randomBytes(16).toString('hex');
145+
146+
// The 13th random hex character is discarded and replaced with '4'
147+
return `${src.substr(0, 8)}-${src.substr(8, 4)}-4${src.substr(13, 3)}` +
148+
`-${src.substr(16, 4)}-${src.substr(20, 32)}`;
149+
}
150+
142151
module.exports = exports = {
143152
// Methods
144153
createCipheriv,
@@ -169,6 +178,7 @@ module.exports = exports = {
169178
scryptSync,
170179
setEngine,
171180
timingSafeEqual,
181+
uuid,
172182
getFips: !fipsMode ? getFipsDisabled :
173183
fipsForced ? getFipsForced : getFipsCrypto,
174184
setFips: !fipsMode ? setFipsDisabled :

test/parallel/test-crypto-uuid.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
if (!common.hasCrypto)
5+
common.skip('missing crypto');
6+
7+
const assert = require('assert');
8+
const crypto = require('crypto');
9+
10+
const UUID_V4_REGEX =
11+
/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}/;
12+
13+
// Test crypto.randomBytes() implementation
14+
for (let i = 0; i < 100; i++) {
15+
const uuid = crypto.uuid();
16+
assert.ok(UUID_V4_REGEX.test(uuid));
17+
}

0 commit comments

Comments
 (0)