Created
April 29, 2013 05:49
-
-
Save adeperio/5479915 to your computer and use it in GitHub Desktop.
How to generate a unique string using the FIPS compliant Microsoft Crypto Libraries
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
using System.Security.Cryptography; | |
using System.Text; | |
namespace UniqueKey | |
{ | |
public class KeyGenerator | |
{ | |
public static string GetUniqueKey(int maxSize) | |
{ | |
char[] chars = new char[62]; | |
chars = | |
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); | |
byte[] data = new byte[1]; | |
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); | |
crypto.GetNonZeroBytes(data); | |
data = new byte[maxSize]; | |
crypto.GetNonZeroBytes(data); | |
StringBuilder result = new StringBuilder(maxSize); | |
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