• XSS.stack #1 – первый литературный журнал от юзеров форума

[C#] Класс для генерации рандомных строк

r3xq1

(L3) cache
Пользователь
Регистрация
14.01.2020
Сообщения
233
Реакции
146
За место Random используйте всегда RNGCryptoServiceProvider или RandomNumberGenerator Они более безопасны в использование.
P.S: Генерация случайных чисел в .Net
C#:
/* Author r3xq1 */
namespace MoreInfoTest.RandomClass
{
    using System;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;

    public class GenRandomString
    {
        private static readonly char[] AvailableCharacters =
        {
           'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
           'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
           'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
           'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
        };

        // OutPut: uqlseSTR88znYK6XkkX4gnk4XKVoAT1ScZ1wjRCG
        internal static string GenerateIdentifier(int length)
        {
            char[] identifier = new char[length];
            byte[] randomData = new byte[length];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(randomData);
            }

            for (int idx = 0; idx < identifier.Length; idx++)
            {
                identifier[idx] = AvailableCharacters[randomData[idx] % AvailableCharacters.Length];
            }

            return new string(identifier);
        }
        // OutPut: bKdkeZXx3tUxUZmOgGxQoXlRncCpGszgZenKU9PF
        internal static string RandomString(int length)
        {
            const string ALPHABIT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            var res = new StringBuilder();
            using (var rng = new RNGCryptoServiceProvider())
            {
                byte[] uintBuffer = new byte[sizeof(uint)];

                while (length-- > 0)
                {
                    rng.GetBytes(uintBuffer);
                    uint num = BitConverter.ToUInt32(uintBuffer, 0);
                    res.Append(ALPHABIT[(int)(num % (uint)ALPHABIT.Length)]);
                }
            }

            return res?.ToString();
        }
        // OutPut: DF-16-CD-28-31-F8-E2-D1-FF-B9-28-3D-7F-9C-8F-88
        internal static string GenNumber()
        {
            using (var rnd = RandomNumberGenerator.Create())
            {
                byte[] buffer = new byte[16];
                rnd.GetBytes(buffer);
                return BitConverter.ToString(buffer);
            }
        }
        // OutPut: zV6rzn7LJhcFdUbzvOow66ouRlYrL36EbB4vDMwjW
        internal static string GenerateRandomSecret()
        {
            char[] validChars = Enumerable.Range('A', 26).Concat(Enumerable.Range('a', 26)).Concat(Enumerable.Range('0', 10)).Select(i => (char)i).ToArray();
            byte[] randomByte = new byte[0x40 + 1];

            using (var rnd = new RNGCryptoServiceProvider())
            {
                rnd.GetBytes(randomByte);
                int secretLength = 0x20 + (int)(0x20 * (randomByte[0] / (double)byte.MaxValue));

                return new string(randomByte.Skip(1).Take(secretLength).Select(b => (int)((validChars.Length - 1) * (b / (double)byte.MaxValue))).Select(i => validChars[i]).ToArray());
            }
        }
        // OutPut: 304e0c4789d1ffeec4114350be24aee5d8211cb6ced59f2cc399db4819f9a08c
        internal static string GenToken()
        {
            using (var rng = new RNGCryptoServiceProvider())
            {
                byte[] randomBuffer = new byte[16];
                rng.GetBytes(randomBuffer);

                using (var md5 = SHA256.Create())
                {
                    byte[] hashBytes = md5.ComputeHash(randomBuffer);

                    var sBuilder = new StringBuilder();
                    foreach (byte byt in hashBytes)
                    {
                        sBuilder.Append(byt.ToString("x2"));
                    }

                    return sBuilder?.ToString();
                }
            }
        }
    }
}
Время выполнения каждого метода:
C#:
Console.WriteLine(RandomClass.GenRandomString.RandomString(40)); // 3,2702 ms
Console.WriteLine(RandomClass.GenRandomString.GenerateIdentifier(40)); // 2,6839 ms
Console.WriteLine(RandomClass.GenRandomString.GenerateRandomSecret()); // 26,6338 ms
Console.WriteLine(RandomClass.GenRandomString.GenNumber()); // 7,2761 ms
Console.WriteLine(RandomClass.GenRandomString.GenToken()); // 10,223 ms
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх