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

feat: implement getRandomValues and randomUUID - resolves #213 and #214 #215

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
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()
})