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

Produce consistent length #3

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
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Ignore built files with webpack
lib/*
33 changes: 33 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module.exports = {
'env': {
'browser': true,
'commonjs': true,
'es2021': true,
'node': true
},
'extends': [
'eslint:recommended',
'plugin:mocha/recommended'
],
'parserOptions': {
'ecmaVersion': 'latest'
},
'rules': {
'indent': [
'error',
2
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
]
}
};
47 changes: 47 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Github CI

on:
push:
pull_request:
workflow_dispatch:

jobs:
lint:
runs-on: ubuntu-latest
name: Node Lint
steps:
- uses: actions/checkout@v2

- uses: actions/setup-node@v2
with:
node-version: 'lts/*'

- run: npm i
- run: npm run lint
test:
runs-on: ubuntu-latest
name: Node Test (Browser)
steps:
- uses: actions/checkout@v2

- uses: actions/setup-node@v2
with:
node-version: 'lts/*'

- run: npm i
- run: npm test
test-node:
runs-on: ubuntu-latest
strategy:
matrix:
node: [ '12', '14', '16' ]
name: Node Test ${{ matrix.node }}
steps:
- uses: actions/checkout@v2

- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node }}

- run: npm i
- run: npm run test:node
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
package-lock.json
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
package-lock.json
test.js
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Will create a random bytes HEX string, in node.js and browsers with crypto.
This library uses the [crypto.randomBytes()](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) in node.js,
and [crypto.getRandomValues()](https://developer.mozilla.org/en/docs/Web/API/RandomSource/getRandomValues) in the browser.

Both of those random generators should provide cryptographically strong pseudo-random data.
Both of those random generators should provide cryptographically strong pseudo-random data.

```
$ npm install randomhex
Expand All @@ -17,10 +17,13 @@ $ npm install randomhex
```js
var randomHex = require('randomhex');

randomHex(16); // get 16 random bytes as HEX string (0x + 32 chars)
randomHex(16); // get 16 random bytes as string (32 chars)
> "d59e72dbf8612798aa1674834c80894e"

randomHex(16, true); // get 16 random bytes as HEX string (0x + 32 chars)
> "0xd59e72dbf8612798aa1674834c80894e"

randomHex(32, console.log); // get 32 random bytes as HEX string (0x + 64 chars)
randomHex(32, true, console.log); // get 32 random bytes as HEX string (0x + 64 chars)
> null "0x409de75fc727d81a7d9f59580130ce3e76124679eb5c4647eb18c40512450c29"

```
40 changes: 40 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const webpack = require('webpack');
const path = require('path');
const os = require('os');

module.exports = function(config) {
config.set({
frameworks: [ 'mocha', 'webpack' ],
files: ['test.js'],
preprocessors: {
'test.js': [ 'webpack' ]
},
webpack: {
mode: 'development',
output: {
path: path.join(os.tmpdir(), '_karma_webpack_') + Math.floor(Math.random() * 1000000)
},
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser.js',
}),
],
resolve: {
fallback: {
assert: require.resolve('assert/'),
crypto: false,
},
}
},
plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-mocha',
'karma-webpack'
],
colors: true,
logLevel: 'info',
autoWatch: false,
browsers: [ 'ChromeHeadless', 'FirefoxHeadless' ]
});
};
1 change: 1 addition & 0 deletions lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 32 additions & 15 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
{
"name": "randomhex",
"version": "0.1.5",
"description": "Will generate a random HEX string of a specifc byte size.",
"repository": "https://github.com/frozeman/randomHex",
"license": "MIT",
"main": "src/index.js",
"browser": {
"crypto": "./src/browser.js"
},
"scripts": {
"test": "mocha test.js"
},
"devDependencies": {
"chai": "^3.0.0"
}
"name": "randomhex",
"version": "0.1.5",
"description": "Will generate a random HEX string of a specifc byte size.",
"repository": "https://github.com/frozeman/randomHex",
"license": "MIT",
"main": "src/index.js",
"browser": "lib/index.js",
"scripts": {
"test": "mocha test.js && karma start --single-run",
"test:node": "mocha test.js",
"test:browser": "karma start --single-run",
"lint": "eslint .",
"lint:fix": "eslint --fix .",
"build": "webpack"
},
"dependencies": {},
"devDependencies": {
"acorn": "^8.7.1",
"assert": "^2.0.0",
"chai": "^3.0.0",
"eslint": "^8.14.0",
"eslint-plugin-mocha": "^10.0.4",
"karma": "^6.3.19",
"karma-chrome-launcher": "^3.1.1",
"karma-firefox-launcher": "^2.1.2",
"karma-mocha": "^2.0.1",
"karma-webpack": "^5.0.0",
"mocha": "^10.0.0",
"process": "^0.11.10",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
}
}
86 changes: 86 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
function browser(size, cb) {
// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
var MAX_BYTES = 65536;

// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
var MAX_UINT32 = 4294967295;

// phantomjs needs to throw
if (typeof size !== 'number' || size > MAX_UINT32) {
throw new RangeError('requested too many random bytes');
}

var bytes = new Uint8Array(size);

// this is the max bytes crypto.getRandomValues
if (size > MAX_BYTES) {
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
for (var generated = 0; generated < size; generated += MAX_BYTES) {
window.crypto.getRandomValues(bytes.subarray(generated, generated + MAX_BYTES));
}
} else {
window.crypto.getRandomValues(bytes);
}

if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes);
});
}

return bytes;
}

function randomBytes(n, cb) {
var isBrowser = typeof window !== 'undefined';
if (!isBrowser) {
return require('crypto').randomBytes(n, cb);
} else if (window && window.crypto && window.crypto.getRandomValues) {
return browser(n, cb);
} else {
return new Error('Secure random number generation is not supported by this browser.\nUse Chrome or Firefox');
}
}

function bytesToHex(bytes, prefix) {
var hex = [];
for (var i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
if (prefix) {
return '0x' + hex.join('');
}
return hex.join('');
}

function randomHex(size, prefix, callback) {
var isCallback = (typeof callback === 'function');

if (size > 4294967295) {
if (isCallback) {
callback(new RangeError('Requested too many random bytes.'));
return;
} else {
throw new RangeError('Requested too many random bytes.');
}
}

if (isCallback) {
randomBytes(size, function(err, resp) {
if (!err) {
callback(null, bytesToHex(resp, prefix));
return;
} else {
callback(err);
return;
}
});
} else {
return bytesToHex(randomBytes(size), prefix);
}
}

module.exports = randomHex;
Loading