Skip to content

Commit

Permalink
feat: implement getRandomValues and randomUUID - resolves #213 and #214
Browse files Browse the repository at this point in the history
  • Loading branch information
markhughes committed Feb 20, 2023
1 parent 460a13b commit 49c5b0e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
23 changes: 23 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
'use strict'

exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')

exports.getRandomValues = function (abv) {
var l = abv.length
while (l--) {
var bytes = exports.randomBytes(7)
var randomFloat = (bytes[0] % 32) / 32

for (var i = 0; i < bytes.length; i++) {
var byte = bytes[i]
randomFloat = (randomFloat + byte) / 256
}

abv[l] = Math.floor(randomFloat * 256)
}
return abv
}

exports.randomUUID = function () {
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, function (c) {
return (c ^ (exports.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
})
}

exports.createHash = exports.Hash = require('create-hash')
exports.createHmac = exports.Hmac = require('create-hmac')

Expand Down
3 changes: 3 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ if (!process.browser) {
}

require('./pbkdf2')

require('./random-uuid')

try {
require('randombytes')(8)
require('./ecdh')
Expand Down
17 changes: 17 additions & 0 deletions test/random-uuid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var test = require('tape')
var crypto = require('../')

test('randomuuid', function (t) {
var uuid1 = crypto.randomUUID()
var uuid2 = crypto.randomUUID()

t.ok(uuid1, 'first uuid truthy')
t.ok(uuid2, 'second uuid truthy')

t.notEqual(uuid1, uuid2, 'consecutive uuid\'s do not match')

t.match(uuid1, /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 'first uuid matches uuid regex')
t.match(uuid2, /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 'second uuid matches uuid regex')

t.end()
})

0 comments on commit 49c5b0e

Please sign in to comment.