Skip to content

Commit

Permalink
azure, utils: Improve and dedupe randomUtils (#1763)
Browse files Browse the repository at this point in the history
  • Loading branch information
bwateratmsft authored Aug 7, 2024
1 parent bbd9dbf commit a49dd97
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 15 deletions.
13 changes: 0 additions & 13 deletions azure/src/utils/randomUtils.ts

This file was deleted.

2 changes: 1 addition & 1 deletion utils/src/node/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

/* eslint-disable */
import * as nodeCrypto from 'crypto';
export const crypto = nodeCrypto.webcrypto as any;
export const crypto = nodeCrypto.webcrypto;
8 changes: 7 additions & 1 deletion utils/src/utils/randomUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ export namespace randomUtils {
}

export function getRandomHexString(length: number = 6): string {
return crypto.randomUUID().slice(0, length);
if (length <= 0) {
throw new Error(`Length must be strictly positive`);
}

const array = new Uint8Array(Math.ceil(length / 2)); // Each byte is represented by 2 hex characters
crypto.getRandomValues(array);
return Buffer.from(array).toString('hex').slice(0, length);
}

export function getRandomInteger(minimumInclusive: number, maximumExclusive: number): number {
Expand Down
21 changes: 21 additions & 0 deletions utils/test/randomUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import assert = require('assert');
import { randomUtils } from '../src/utils/randomUtils';


suite('randomUtils', function (this: Mocha.Suite): void {
test('getRandomHexString', async () => {
// An even number length
assert.strictEqual(randomUtils.getRandomHexString(6).length, 6);

// An odd number length
assert.strictEqual(randomUtils.getRandomHexString(5).length, 5);

// Zero length should throw
assert.throws(() => randomUtils.getRandomHexString(0));
});
});

0 comments on commit a49dd97

Please sign in to comment.