diff --git a/azure/src/utils/randomUtils.ts b/azure/src/utils/randomUtils.ts deleted file mode 100644 index eb4e96e7ed..0000000000 --- a/azure/src/utils/randomUtils.ts +++ /dev/null @@ -1,13 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import * as crypto from "crypto"; - -export namespace randomUtils { - export function getRandomHexString(length: number = 6): string { - const buffer: Buffer = crypto.randomBytes(Math.ceil(length / 2)); - return buffer.toString('hex').slice(0, length); - } -} diff --git a/utils/src/node/crypto.ts b/utils/src/node/crypto.ts index a906f34f1c..d8692c745a 100644 --- a/utils/src/node/crypto.ts +++ b/utils/src/node/crypto.ts @@ -5,4 +5,4 @@ /* eslint-disable */ import * as nodeCrypto from 'crypto'; -export const crypto = nodeCrypto.webcrypto as any; +export const crypto = nodeCrypto.webcrypto; diff --git a/utils/src/utils/randomUtils.ts b/utils/src/utils/randomUtils.ts index 7f054f5806..d1992d79ed 100644 --- a/utils/src/utils/randomUtils.ts +++ b/utils/src/utils/randomUtils.ts @@ -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 { diff --git a/utils/test/randomUtils.test.ts b/utils/test/randomUtils.test.ts new file mode 100644 index 0000000000..e260fdf7c1 --- /dev/null +++ b/utils/test/randomUtils.test.ts @@ -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)); + }); +});