Created
November 3, 2017 14:56
-
-
Save diegojancic/9f78750f05550fa6039d2f6092e461e5 to your computer and use it in GitHub Desktop.
Random string generator, based on
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Based on Eric J's answer here: https://stackoverflow.com/a/1344255/72350 | |
- Fixed bias by using 64 characters | |
- Removed unneeded 'new char[62]' and 'new byte[1]' | |
- Using GetBytes instead of GetNonZeroBytes | |
*/ | |
using System.Security.Cryptography; | |
using System.Text; | |
namespace YourNamespace | |
{ | |
public static class TokenGenerator | |
{ | |
public static string GetUniqueKey(int length) | |
{ | |
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-".ToCharArray(); | |
byte[] data = new byte[length]; | |
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) | |
{ | |
crypto.GetBytes(data); | |
} | |
StringBuilder result = new StringBuilder(length); | |
foreach (byte b in data) | |
{ | |
result.Append(chars[b % (chars.Length)]); | |
} | |
return result.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment