using System.Text; using System.Text.RegularExpressions; using System.Security.Cryptography; using Types.Annotations; namespace Types.Utils; [Injectable(InjectionType.Singleton)] public partial class HashUtil { /// /// Create a 24 character id using the sha256 algorithm + current timestamp /// /// 24 character hash public static string Generate() { throw new NotImplementedException(); } /// /// is the passed in string a valid mongo id /// /// String to check /// True when string is a valid mongo id public static bool IsValidMongoId(string stringToCheck) { return MongoIdRegex().IsMatch(stringToCheck); } public static string GenerateMd5ForData(string data) { return GenerateHashForData(HashingAlgorithm.MD5, data); } public static string GenerateSha1ForData(string data) { return GenerateHashForData(HashingAlgorithm.SHA1, data); } public static string GenerateCrc32ForData(string data) { // TODO: Could not find a ms way of doing this. // May need a custom impl to avoid an external lib. - CJ throw new NotImplementedException(); } /// /// Create a hash for the data parameter /// /// algorithm to use to hash /// data to be hashed /// hash value /// thrown if the provided algorithm is not implemented> public static string GenerateHashForData(HashingAlgorithm algorithm, string data) { switch (algorithm) { case HashingAlgorithm.MD5: var md5HashData = MD5.HashData(Encoding.UTF8.GetBytes(data)); return Convert.ToHexString(md5HashData).Replace("-", string.Empty); case HashingAlgorithm.SHA1: var sha1HashData = SHA1.HashData(Encoding.UTF8.GetBytes(data)); return Convert.ToHexString(sha1HashData).Replace("-", string.Empty); } throw new NotImplementedException("Provided hash algorithm is not supported."); } /// /// Generates an account ID for a profile /// /// Generated account ID public static int GenerateAccountId() { const int min = 1000000; const int max = 1999999; var random = new Random(); return random.Next() * (max - min + 1) + min; } [GeneratedRegex("^[a-fA-F0-9]{24}$", RegexOptions.IgnoreCase, "en")] private static partial Regex MongoIdRegex(); } public enum HashingAlgorithm { MD5, SHA1, }