Skip to content

Instantly share code, notes, and snippets.

@craigtp
Created April 29, 2016 12:16
Show Gist options
  • Select an option

  • Save craigtp/92402910ea4a0d2400c1a7912d723f8c to your computer and use it in GitHub Desktop.

Select an option

Save craigtp/92402910ea4a0d2400c1a7912d723f8c to your computer and use it in GitHub Desktop.

Revisions

  1. craigtp created this gist Apr 29, 2016.
    70 changes: 70 additions & 0 deletions RandomString.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    using System;
    using System.Text;

    namespace RandomString
    {
    public class RandomString : IDisposable
    {
    // Can use the BetterRandom class here or just use the built-in System.Random class.
    private BetterRandom random = new BetterRandom();
    private const string alpha_selection = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string numeric_selection = "1234567890";
    private const string symbol_selection = "!£$%^&*()-+=";

    public string GenerateRandomString()
    {
    var length = random.Next(5, 15);
    return GenerateRandomString(length);
    }

    public string GenerateRandomString(int length, bool onlyUseAlphaNumerics = false)
    {
    var alphanumeric_selection = alpha_selection + numeric_selection;
    var characterSelection = onlyUseAlphaNumerics ? alphanumeric_selection : alphanumeric_selection + symbol_selection;
    return GenerateRandomString(length, characterSelection);
    }

    public string GenerateRandomString(int length, string characterSelection)
    {
    var result = new StringBuilder();
    for (var i = 0; i < length; i++)
    {
    var chr = characterSelection.Substring(random.Next(0, characterSelection.Length), 1);
    result.Append(chr);
    }
    return result.ToString();
    }

    public string GenerateHashString(string stringToHash)
    {
    using (var crypto = new System.Security.Cryptography.SHA1CryptoServiceProvider())
    {
    return BitConverter.ToString(crypto.ComputeHash(Encoding.Unicode.GetBytes(stringToHash))).Replace("-", string.Empty);
    }
    }

    public string GenerateRandomHashString()
    {
    return GenerateHashString(GenerateRandomString(1024));
    }


    public void Dispose()
    {
    Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
    if (disposing)
    {
    if (random != null)
    {
    random.Dispose();
    random = null;
    }
    }
    GC.SuppressFinalize(this);
    }
    }
    }