-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomGenerator.cs
57 lines (49 loc) · 1.66 KB
/
RandomGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ShareMe
{
public static class RandomGenerator
{
private const string availableCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static RandomNumberGenerator rand = RandomNumberGenerator.Create();
public static string GetRandomHex(int length)
{
if (length > 1 && length % 2 == 0)
{
byte[] randomBytes = new byte[length / 2];
rand.GetBytes(randomBytes);
return BitConverter.ToString(randomBytes).Replace("-", string.Empty).ToLower();
}
else
{
throw new ArgumentOutOfRangeException(nameof(length), length, "Must be even and > 1");
}
}
public static string GetRandomString(int length)
{
if (length > 0)
{
StringBuilder sb = new StringBuilder(length);
while (sb.Length != length)
{
byte[] oneByte = new byte[1];
rand.GetBytes(oneByte);
char character = (char)oneByte[0];
if (availableCharacters.Contains(character))
{
sb.Append(character);
}
}
return sb.ToString();
}
else
{
throw new ArgumentOutOfRangeException(nameof(length), length, "Must be greater than 0");
}
}
}
}