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

Secure random in RandomStrings #69

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
49 changes: 46 additions & 3 deletions src/ProtonVPN.Common/Helpers/RandomStrings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
* Copyright (c) 2022 Proton Technologies AG
*
* This file is part of ProtonVPN.
Expand All @@ -18,6 +18,7 @@
*/

using System;
using System.Security.Cryptography;

namespace ProtonVPN.Common.Helpers
{
Expand All @@ -26,7 +27,7 @@ namespace ProtonVPN.Common.Helpers
/// </summary>
public class RandomStrings
{
private readonly Random _random = new Random();
private readonly RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider();

public string RandomString(int length)
{
Expand All @@ -37,10 +38,52 @@ public string RandomString(int length)

for (var i = 0; i < randomChars.Length; i++)
{
randomChars[i] = chars[_random.Next(chars.Length)];
randomChars[i] = chars[Next(chars.Length)];
}

return new string(randomChars);
}

/// <summary>
/// Returns a random number within a specified range.
/// </summary>
private int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue));
}

if (maxValue == 0)
{
return 0;
}

while (true)
{
uint rand = GetRandomUInt32();

long max = 1 + (long)uint.MaxValue;

if (rand < max)
{
return (int)(rand % maxValue);
}
}
}

/// <summary>
/// Gets one random unsigned 32bit integer in a thread safe manner.
/// </summary>
private uint GetRandomUInt32()
{
lock (this)
{
var buffer = new byte[sizeof(uint)];
_random.GetBytes(buffer, 0, buffer.Length);
uint rand = BitConverter.ToUInt32(buffer, 0);
return rand;
}
}
}
}