Skip to content

Commit b0257de

Browse files
Potential fix for code scanning alert no. 10: Insecure randomness
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1 parent fa63c47 commit b0257de

1 file changed

Lines changed: 24 additions & 3 deletions

File tree

src/app/grid-lite/grid-lite-data.service.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,19 +44,40 @@ export class GridLiteDataService {
4444
private priorities: ('Low' | 'Standard' | 'High')[] = ['Low', 'Standard', 'High'];
4545

4646
private randomInt(min: number, max: number): number {
47-
return Math.floor(Math.random() * (max - min + 1)) + min;
47+
// Use crypto.getRandomValues for cryptographically secure randomness
48+
const range = max - min + 1;
49+
if (range <= 0) {
50+
throw new Error('Invalid range');
51+
}
52+
// Find the number of bits needed to express the range
53+
const maxUint32 = 0xFFFFFFFF;
54+
const array = new Uint32Array(1);
55+
let randomNum: number;
56+
let limit = maxUint32 - (maxUint32 % range);
57+
do {
58+
window.crypto.getRandomValues(array);
59+
randomNum = array[0];
60+
} while (randomNum >= limit);
61+
return min + (randomNum % range);
4862
}
4963

5064
private randomFloat(min: number, max: number, precision = 2): number {
51-
return parseFloat((Math.random() * (max - min) + min).toFixed(precision));
65+
// Get a random float in [0,1) using crypto.getRandomValues
66+
const array = new Uint32Array(1);
67+
window.crypto.getRandomValues(array);
68+
// Divide by 2^32 to get a float in [0,1)
69+
const random01 = array[0] / 2 ** 32;
70+
return parseFloat((random01 * (max - min) + min).toFixed(precision));
5271
}
5372

5473
private randomElement<T>(array: T[]): T {
5574
return array[this.randomInt(0, array.length - 1)];
5675
}
5776

5877
private randomBoolean(): boolean {
59-
return Math.random() < 0.5;
78+
const array = new Uint8Array(1);
79+
window.crypto.getRandomValues(array);
80+
return (array[0] & 1) === 0;
6081
}
6182

6283
private generateId(): string {

0 commit comments

Comments
 (0)