Utils for c#

less than 1 minute read

I have used many functions before, but I was lazy to recorded it. These functions are just the beginnings of my recording.

/// <summary>
/// get random string (ex: one time password)
/// </summary>
/// <remarks></remarks>
public static string getRandomStr(int strlen)
{
    string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= strlen; i++)
    {
        int idx = r.Next(0, s.Length - 1);
        sb.Append(s.Substring(idx, 1));
    }
    return sb.ToString();
}

/// <summary>
/// MD5 String
/// </summary>
/// <param name="theInput"></param>
/// <returns></returns>
public static string GetHashMD5(string theInput)
{
    using (MD5 hasher = MD5.Create())    // create hash object
    {
        // Convert to byte array and get hash
        byte[] dbytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput));
        // sb to create string from bytes
        StringBuilder sBuilder = new StringBuilder();
        // convert byte data to hex string
        for (int n = 0; n <= dbytes.Length - 1; n++)
            sBuilder.Append(dbytes[n].ToString("X2"));
        return sBuilder.ToString();
    }
}

Tags: ,

Categories:

Updated:

Leave a comment