Skip to content

Commit cccaa4d

Browse files
authored
Merge pull request #18 from YassinLokhat/16-fix-code-scanning-alert---workflow-does-not-contain-permissions
Fix Insecure randomness
2 parents b22be04 + 3ae2f24 commit cccaa4d

1 file changed

Lines changed: 19 additions & 19 deletions

File tree

UnitTests/UnitTestsHelper.cs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -86,22 +86,13 @@ public static void ClearTestEnvironment([CallerMemberName] string username = "")
8686

8787
public static string GetUsername([CallerMemberName] string username = "") => username;
8888

89-
private static RandomNumberGenerator _randomNumberGenerator => RandomNumberGenerator.Create();
90-
private static Random _getRandom()
91-
{
92-
byte[] byteSeed = new byte[4];
93-
_randomNumberGenerator.GetBytes(byteSeed);
94-
int seed = BitConverter.ToInt32(byteSeed, 0);
95-
return new Random(seed);
96-
}
89+
private static RandomNumberGenerator _random => RandomNumberGenerator.Create();
9790

9891
public static string[] GetRandomStringArray(int count = 0)
9992
{
100-
Random random = _getRandom();
101-
10293
if (count == 0)
10394
{
104-
count = random.Next(2, 5);
95+
count = GetRandomInt(2, 5);
10596
}
10697

10798
List<string> passkeys = [];
@@ -115,25 +106,34 @@ public static string[] GetRandomStringArray(int count = 0)
115106

116107
public static string GetRandomString(int min = 10, int max = 0)
117108
{
118-
Random random = _getRandom();
119-
120109
if (max == 0)
121110
{
122111
max = min + 10;
123112
}
124113

125-
int length = random.Next(min, max);
126-
127-
byte[] bytes = new byte[length];
114+
int length = GetRandomInt(min, max);
128115

129-
random.NextBytes(bytes);
116+
byte[] randomBytes = new byte[length];
117+
_random.GetBytes(randomBytes);
130118

131-
return Convert.ToBase64String(bytes)[..length];
119+
return Convert.ToBase64String(randomBytes)[..length];
132120
}
133121

134122
public static int GetRandomInt(int max) => GetRandomInt(0, max);
135123

136-
public static int GetRandomInt(int min, int max) => _getRandom().Next(min, max);
124+
public static int GetRandomInt(int min, int max)
125+
{
126+
byte[] randomBytes = new byte[4];
127+
_random.GetBytes(randomBytes);
128+
129+
uint value = BitConverter.ToUInt32(randomBytes, 0);
130+
131+
uint interval = (uint)(max - min);
132+
value = value % interval;
133+
value += (uint)min;
134+
135+
return (int)value;
136+
}
137137

138138
public static void LastLogsShouldMatch(IDatabase database, string[] expectedLogs)
139139
{

0 commit comments

Comments
 (0)