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

azure, utils: Improve and dedupe randomUtils #1763

Merged
merged 2 commits into from
Aug 7, 2024
Merged
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
13 changes: 0 additions & 13 deletions azure/src/utils/randomUtils.ts
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved

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);
bwateratmsft marked this conversation as resolved.
Show resolved Hide resolved
}

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));
});
});
Loading