Skip to content

Commit

Permalink
fix sonar findings
Browse files Browse the repository at this point in the history
Signed-off-by: David Liu <david-khala@hotmail.com>
  • Loading branch information
davidkhala committed Feb 3, 2024
1 parent e507a95 commit 14e824c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
3 changes: 2 additions & 1 deletion crypto/test/amclTest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {consoleLogger} from '@davidkhala/logger/log4.js';
import CTX from '@davidkhala/milagro-crypto-js';
import assert from 'assert';

const logger = consoleLogger('test:amcl');
const algorithmList = [
Expand All @@ -12,7 +13,7 @@ const algorithmList = [
describe('amcl', () => {
it('algorithm smoke', () => {
algorithmList.forEach(algo => {
new CTX(algo);
assert.doesNotThrow(() => new CTX(algo));
});
});

Expand Down
12 changes: 4 additions & 8 deletions light/random.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
// total: 293KB
import crypto from 'crypto';

export function randomKeyOf(obj) {
const keys = Object.keys(obj);
const keyIndex = Math.floor(Math.random() * keys.length);
const keyIndex = crypto.randomInt(keys.length);
return keys[keyIndex];
}

export const uuid = crypto.randomUUID;
export const randomHex = (length) => crypto.randomBytes(length / 2).toString('hex');

/**
*
* @param {number} length integer
* @return {string} alphaNumeric
*/
export const randomString = (length) => [...Array(length)].map(() => (~~(Math.random() * 36)).toString(36)).join('');
export const randomString = (length) => [...Array(length)].map(() => (~~(crypto.randomInt(36))).toString(36)).join('');

export function randomChars(length, charSet) {
if (!charSet) {
charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
}
let result = '';
for (let i = 0; i < length; i++) {
result += charSet.charAt(Math.floor(Math.random() * charSet.length));
}
return result;
return [...Array(length)].map(() => charSet.charAt(crypto.randomInt(charSet.length))).join('');
}

14 changes: 13 additions & 1 deletion light/test/randomTest.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import {randomHex, randomString, randomChars} from '../random.js';
import {randomHex, randomString, randomChars, randomKeyOf} from '../random.js';
import {consoleLogger} from '@davidkhala/logger/log4.js';
import assert from 'assert';

const logger = consoleLogger('test:random');


describe('test:random', () => {

it('randomKeyOf', () => {
const key = randomKeyOf({
a: 'B',
c: 'D'
});
assert.ok(['a', 'c'].includes(key));
});
it('randomHex', () => {
const hex = randomHex(20);
logger.debug(hex);
Expand Down

0 comments on commit 14e824c

Please sign in to comment.