public static HashAlgorithm Create(HashType hash) { switch (hash) { case HashType.CRC32: return CRC32.Create(); case HashType.MD5: return MD5.Create(); case HashType.SHA256: return SHA256.Create(); case HashType.SHA384: return SHA384.Create(); case HashType.SHA512: return SHA512.Create(); case HashType.SHA1: return SHA1.Create(); default: throw new NotSupportedException("not support hash algorithm :" + hash.ToString()); } }
public static HashAlgorithm Create(HashType hash) { switch (hash) { case HashType.CRC32: return(CRC32.Create()); case HashType.MD5: return(MD5.Create()); case HashType.SHA256: return(SHA256.Create()); case HashType.SHA384: return(SHA384.Create()); case HashType.SHA512: return(SHA512.Create()); case HashType.SHA1: return(SHA1.Create()); default: throw new NotSupportedException("not support hash algorithm :" + hash.ToString()); } }
public unsafe void DeriveSecret(IHashProvider hashProvider, HashType hashType, void *salt, int saltSize, void *output, int outputSize) { SafeBCryptSecretHandle returnPtr; ExceptionHelper.CheckReturnCode(BCryptSecretAgreement(_key, _peerKey, out returnPtr, 0)); var buffDescription = new BCryptBufferDesc(); var bufferArray = stackalloc BCryptBuffer[2]; var algId = System.Text.Encoding.Unicode.GetBytes(hashType.ToString().ToUpper() + "\0"); buffDescription.pBuffers = (IntPtr)bufferArray; buffDescription.cBuffers = 2; fixed(byte *algPtr = algId) { bufferArray[0] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_HASH_ALGORITHM, cbBuffer = algId.Length, pvBuffer = algPtr }; bufferArray[1] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_HMAC_KEY, cbBuffer = saltSize, pvBuffer = salt }; int sizeOfResult; ExceptionHelper.CheckReturnCode(BCryptDeriveKey(returnPtr, BCRYPT_KDF_HMAC, &buffDescription, (IntPtr)output, outputSize, out sizeOfResult, 0)); returnPtr.Dispose(); Dispose(); } }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText"> /// Plaintext value to be hashed. The function does not check whether /// this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <returns> /// Hash value formatted as a base64-encoded string. /// </returns> public static string ComputeHash(string plainText, HashType hashType) { // Convert plain text into a byte array. var plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text. var plainTextWithSaltBytes = new byte[plainTextBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Initialize appropriate hashing algorithm class. switch (hashType.ToString()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. var hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. var hashWithSaltBytes = new byte[hashBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; }
/// <inheritdoc /> public override string GetCommandLineArgs(LocalServerConfiguration localContentServerConfiguration = null, string scenario = null, bool logAutoFlush = false, bool passMaxConnections = false) { var args = new StringBuilder(base.GetCommandLineArgs(localContentServerConfiguration, scenario, logAutoFlush, false)); args.AppendFormat(" /hashType:{0}", HashType.ToString()); args.AppendFormat(" /path:{0}", SourcePath.Path); return(args.ToString()); }
private Tuple <SafeBCryptAlgorithmHandle, SafeBCryptAlgorithmHandle> GetProviders(HashType hashType) { SafeBCryptAlgorithmHandle hash, hmac; var hashId = hashType.ToString().ToUpper(); BCryptOpenAlgorithmProvider(out hash, hashId, null, BCryptOpenAlgorithmProviderFlags.None); BCryptOpenAlgorithmProvider(out hmac, hashId, null, BCryptOpenAlgorithmProviderFlags.BCRYPT_ALG_HANDLE_HMAC_FLAG); return(Tuple.Create(hash, hmac)); }
/// <summary> /// Serialize to string. /// </summary> public static string Serialize(this HashType hashType) { if (ValueToName.TryGetValue(hashType, out var result)) { return(result); } return(hashType.ToString().ToUpperInvariant()); }
public override void PutFileStart(Context context, AbsolutePath path, FileRealizationMode mode, HashType hashType, bool trusted) { if (_eventSource.IsEnabled()) { _eventSource.PutFileStart(context.TraceId, path.Path, (int)mode, hashType.ToString()); } base.PutFileStart(context, path, mode, hashType, trusted); }
public override void PutStreamStart(Context context, HashType hashType) { if (_eventSource.IsEnabled()) { _eventSource.PutStreamStart(context.TraceId, hashType.ToString()); } base.PutStreamStart(context, hashType); }
public static byte[] ComputeHash(byte[] plainTextBytes, HashType hashType) { // Allocate array, which will hold plain text. var plainTextWithSaltBytes = new byte[plainTextBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) { plainTextWithSaltBytes[i] = plainTextBytes[i]; } // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Initialize appropriate hashing algorithm class. switch (hashType.ToString()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. var hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. var hashWithSaltBytes = new byte[hashBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) { hashWithSaltBytes[i] = hashBytes[i]; } return(hashWithSaltBytes); }
private async void generateButton_Click(object sender, EventArgs e) { outputTextBox.Clear(); if (string.IsNullOrWhiteSpace(inputTextBox.Text)) { MessageBox.Show(Resources.MainForm_generateButton_Click_Input_URLs_list_cannot_be_empty, Resources.MainForm_generateButton_Click_Error, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (var wc = new WebClient()) { foreach (var line in inputTextBox.Lines) { var trimmedLine = line.Trim(); if (Uri.IsWellFormedUriString(trimmedLine, UriKind.Absolute)) { byte[] fileData = await wc.DownloadDataTaskAsync(trimmedLine); HashType hashAlg = GetHashAlgo(); string hash = GenerateSRIHash(fileData, hashAlg); if (trimmedLine.EndsWith(".css")) { outputTextBox.AppendText(string.Format(css, trimmedLine, hashAlg.ToString().ToLower(), hash)); } else if (line.EndsWith(".js")) { outputTextBox.AppendText(string.Format(js, trimmedLine, hashAlg.ToString().ToLower(), hash)); } else { outputTextBox.AppendText($"{hashAlg.ToString().ToLower()}-{hash}{Environment.NewLine}"); } outputTextBox.AppendText(Environment.NewLine); } else { outputTextBox.AppendText($"⚠️ INVALID URL: {trimmedLine}"); } } } }
/// <summary> /// /// </summary> /// <param name="hType">Hashing Algorithm used (SHA1 or MD5)</param> /// <param name="keyLength">Size of encryption key in bits. Allowed values are: 128, 192, and 256.</param> /// <param name="iterations">Number of iterations used to generate password.</param> /// <param name="initVector">16 ASCII character Initialization Vector</param> /// <param name="passPhrase">Unicode phrase used to generate encryption string</param> /// <param name="saltValue">Unicode value to salt data with (secondary key)</param> public Crypto(HashType hType, int keyLength, int iterations, string initVector, string passPhrase, string saltValue) { m_hType = hType.ToString(); m_keyLength = keyLength; m_iterations = iterations; m_initVector = initVector; m_passPhrase = passPhrase; m_saltValue = saltValue; }
// Encripta en Has256 public static string ComputeHash(this string input, HashType hashType) { byte[] numArray; byte[] bytes = Encoding.ASCII.GetBytes(input); using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashType.ToString().ToUpperInvariant())) { numArray = hashAlgorithm.ComputeHash(bytes); } return(BitConverter.ToString(numArray).Replace("-", string.Empty).ToLower()); }
/// <summary> /// Creates the password hash using a given HashType algoritm. /// </summary> /// <param name="salt">The salt.</param> /// <param name="password">The password.</param> /// <param name="hashType">Type of the hash.</param> /// <returns></returns> public static string CreatePasswordHash(string salt, string password, HashType hashType) { string hashString = string.Empty; if (!string.IsNullOrEmpty(password)) { HashAlgorithm hashAlg = HashAlgorithm.Create(hashType.ToString()); byte[] pwordData = Encoding.Default.GetBytes(salt + password); byte[] hash = hashAlg.ComputeHash(pwordData); hashString = Convert.ToBase64String(hash); } return hashString; }
/// <summary> /// Creates the password hash using a given HashType algorithm. /// </summary> /// <param name="salt">The salt.</param> /// <param name="password">The password.</param> /// <param name="hashType">Type of the hash.</param> /// <returns></returns> public static string CreatePasswordHash(string salt, string password, HashType hashType) { string hashString = string.Empty; if (!string.IsNullOrEmpty(password)) { HashAlgorithm hashAlgorithm = HashAlgorithm.Create(hashType.ToString()); byte[] passwordData = Encoding.Default.GetBytes(salt + password); byte[] hash = hashAlgorithm.ComputeHash(passwordData); hashString = Convert.ToBase64String(hash); } return(hashString); }
public static string ComputeHash(string text, HashType hashType) { StringBuilder builder = new StringBuilder(); using (HashAlgorithm algorithm = HashAlgorithm.Create(hashType.ToString())) { byte[] hashBuffer = algorithm.ComputeHash(Encoding.UTF8.GetBytes(text)); foreach (byte b in hashBuffer) { builder.Append(b.ToString("x2")); } } return(builder.ToString()); }
public static HashAlgorithm CreateInstance(HashType theHash) { HashAlgorithm hash = null; switch(theHash) { case HashType.MD5: { hash = new MD5CryptoServiceProvider(); break; } case HashType.RIPEMD160: { hash = new RIPEMD160Managed(); break; } case HashType.SHA1: { hash = new SHA1CryptoServiceProvider(); break; } case HashType.SHA256: { hash = new SHA256CryptoServiceProvider(); break; } case HashType.SHA384: { hash = new SHA384CryptoServiceProvider(); break; } case HashType.SHA512: { hash = new SHA512CryptoServiceProvider(); break; } default: { throw new NotSupportedException(String.Format("The hash algorithm '{0}' is not supported", theHash.ToString())); } } return hash; }
private void button8_Click(object sender, EventArgs e) { KeyType pub = new KeyType(); HashType priv = new HashType(); ConfigManager.noconnectflg = true; using (Connector node = new Connector()) { if (node.GenKeyPair(ref pub, ref priv)) { MessageBox.Show(string.Format("Key pair generated\r\npub key:\r\n{0}\r\npriv key:\r\n{1}", pub.ToString(), priv.ToString())); } else { MessageBox.Show("Key pair do not been generated"); } } }
/// <summary> /// Computes the hash value for the specified <see cref="byte" />[] using the specified <see cref="HashType" /> and repeats computation a specified number of times. /// </summary> /// <param name="data">The <see cref="byte" />[] to be used in the hash computation.</param> /// <param name="type">The <see cref="HashType" /> specifying the algorithm that is used.</param> /// <param name="passes">A <see cref="int" /> value indicating the number of times <paramref name="data" /> should be processed. For successive passes, the binary result of the previous pass is used as input value for the next pass.</param> /// <returns> /// A <see cref="byte" />[] representing the fixed-length binary of the hash of the <paramref name="data" /> parameter. /// </returns> public static byte[] ComputeRaw(byte[] data, HashType type, int passes) { Check.ArgumentNull(data, nameof(data)); Check.ArgumentOutOfRangeEx.Greater0(passes, nameof(passes)); if (type == HashType.Adler32) { Repeat(ref data, HashAlgorithms.ComputeAdler32); } else if (type == HashType.CRC32) { Repeat(ref data, HashAlgorithms.ComputeCrc32); } else if (type == HashType.CRC64) { Repeat(ref data, HashAlgorithms.ComputeCrc64); } else { using HashAlgorithm hash = HashAlgorithm.Create(type.ToString()); if (hash == null) { throw Throw.InvalidEnumArgument(nameof(type), type); } else { Repeat(ref data, hash.ComputeHash); } } return(data); void Repeat(ref byte[] bytes, Func <byte[], byte[]> func) { for (int i = 0; i < passes; i++) { bytes = func(bytes); } } }
public static string CalculateHash(string sharedSecret, HashType hashType, string stringToSign) { string signature; switch (hashType) { default: throw new NotSupportedException($"Hashing using {hashType.ToString()} is not supported"); case HashType.MD5: using (var hmac = MD5.Create()) { var bytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(stringToSign + '\n' + sharedSecret)); signature = BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant(); } break; case HashType.Sha1: using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(sharedSecret))) { signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); } break; case HashType.Sha256: // This should be the default. Use other methods only, of the client system // cannot create SHA256 hashes using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(sharedSecret))) { signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); } break; } return(signature); }
private static HashAlgorithm CreateNative(HashType hashType) { switch(hashType) { case HashType.Md5: return MD5.Create(); case HashType.Sha1: return SHA1.Create(); case HashType.Sha256: return SHA256.Create(); case HashType.Sha384: return SHA384.Create(); case HashType.Sha512: return SHA512.Create(); #if NETFULL case HashType.RipeMd160: return RIPEMD160.Create(); #endif default: throw new NotSupportedException(hashType.ToString() + " is not supported"); } }
private static HashAlgorithm CreateNative(HashType hashType) { switch (hashType) { case HashType.Md5: return(MD5.Create()); case HashType.Sha1: return(SHA1.Create()); case HashType.Sha256: return(SHA256.Create()); case HashType.Sha384: return(SHA384.Create()); case HashType.Sha512: return(SHA512.Create()); default: throw new NotSupportedException(hashType.ToString() + " is not supported"); } }
public unsafe void DeriveMasterSecretTls12(IHashProvider hashProvider, HashType hashType, void *seed, int seedLength, void *output, int outputLength) { uint version = 0x0303; var buffDescription = new BCryptBufferDesc(); var bufferArray = stackalloc BCryptBuffer[4]; var algId = Encoding.Unicode.GetBytes(hashType.ToString() + "\0"); fixed(void *algPtr = algId) { bufferArray[0] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_HASH_ALGORITHM, cbBuffer = algId.Length, pvBuffer = algPtr }; bufferArray[1] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_TLS_PRF_LABEL, cbBuffer = Tls13.Internal.Tls1_2Consts.MasterSecretLabelSize, pvBuffer = (void *)Tls13.Internal.Tls1_2Consts.MasterSecretLabelPointer }; bufferArray[2] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_TLS_PRF_SEED, cbBuffer = seedLength, pvBuffer = seed }; bufferArray[3] = new BCryptBuffer() { BufferType = NCryptBufferDescriptors.KDF_TLS_PRF_PROTOCOL, cbBuffer = 4, pvBuffer = &version }; buffDescription.cBuffers = 4; buffDescription.pBuffers = (IntPtr)bufferArray; int sizeOfResult; SafeBCryptSecretHandle secretPointer; ExceptionHelper.CheckReturnCode(BCryptSecretAgreement(_key, _peerKey, out secretPointer, 0)); ExceptionHelper.CheckReturnCode( BCryptDeriveKey(secretPointer, BCRYPT_KDF_TLS_PRF, &buffDescription, (IntPtr)output, outputLength, out sizeOfResult, 0)); secretPointer.Dispose(); Dispose(); } }
private HashAlgorithm GetHashAlgorithm(HashType hashType) { return((HashAlgorithm)CryptoConfig.CreateFromName(hashType.ToString())); }
public static string Format(HashType type, string input) { return $"{{{type.ToString()}:{input}}}"; }
/// <summary> /// Compares a hash of the specified plain text value to a given hash /// value. Plain text is hashed with the same salt value as the original /// hash. /// </summary> /// <param name="plainText"> /// Plain text to be verified against the specified hash. The function /// does not check whether this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified, /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="hashValue"> /// Base64-encoded hash value produced by ComputeHash function. This value /// includes the original salt appended to it. /// </param> /// <returns> /// If computed hash mathes the specified hash the function the return /// value is true; otherwise, the function returns false. /// </returns> public static bool VerifyHash(string plainText, HashType hashType, string hashValue) { // Convert base64-encoded hash value into a byte array. var hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Size of hash is based on the specified algorithm. switch (hashType.ToString()) { case "SHA1": hashSizeInBits = 160; break; case "SHA256": hashSizeInBits = 256; break; case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) { return(false); } // Allocate array to hold original salt bytes retrieved from hash. var saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) { saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; } // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashType); // If the computed hash matches the specified hash, // the plain text value must be correct. return(hashValue == expectedHashString); }
public override string ToString() { return("hashType:" + hashType.ToString() + ", nodes offset:" + nodesBeginOffset.ToString()); }
/// <summary> /// Encrypt string with salt /// </summary> public static string Encrypt(this string text, string salt, HashType type) { return(FormsAuthentication.HashPasswordForStoringInConfigFile(text + salt, type.ToString())); }
/// <summary> /// Serialize to string. /// </summary> public static string Serialize(this HashType hashType) { return(hashType.ToString().ToUpperInvariant()); }
public String AddJob (byte[] hash, HashType type, int maxLength) { var localId = Guid.NewGuid ().ToString (); var localJob = new LocalJob (); var starters = Enumerable.Range (ASCII_0, ASCII_z - ASCII_0 + 1).ToList (); lock (LocalJobs) { LocalJobs.Add (localId, localJob); int i = 0; foreach (var rs in Sockets.Values) { var request = new NetMQMessage (); request.Append ("job"); request.Append (hash); request.Append (type.ToString ()); request.Append (maxLength); for (int a = 0; a < starters.Count; a++) { if (a % Sockets.Count == i) { request.Append (Encoding.ASCII.GetString (new byte[] { (byte)starters [a] })); } } rs.SendMessage (request); var recv = rs.ReceiveMessage (); int id = recv [0].ConvertToInt32 (); RemoteIdToLocal.Add (id, localId); localJob.Nodes.Add (rs, id); i++; } localJob.Status = Common.Status.PROCESSING; } return localId; }
private static void RunHash(HashType hashtype) { Console.WriteLine("Hash type: " + hashtype.ToString()); //Random r = new Random(); DateTime starttime = DateTime.Now; //ConcurrentBag<String> SmallBag = new ConcurrentBag<String>(); //ConcurrentBag<String> MediumBag = new ConcurrentBag<String>(); //ConcurrentBag<String> LargeBag = new ConcurrentBag<String>(); //ConcurrentBag<String> GiantBag = new ConcurrentBag<String>(); Hasher hasher = new Hasher(); #region slow also //ConcurrentBag<Int32> smallarrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> mediumarrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> largearrdisty = new ConcurrentBag<Int32>(); //ConcurrentBag<Int32> giantarrdisty = new ConcurrentBag<Int32>(); //Int32 smallarraycollisions = 0; //Int32 mediumarraycollisions = 0; //Int32 largearraycollisions = 0; //Int32 giantarraycollisions = 0; //IEnumerable<Hash> smallhash = null; //IEnumerable<Hash> mediumhash = null; //IEnumerable<Hash> largehash = null; //IEnumerable<Hash> gianthash = null; //Parallel.Invoke( // () => smallhash = hasher.Hash(SmallBag, hashtype), // () => mediumhash = hasher.Hash(MediumBag, hashtype), // () => largehash = hasher.Hash(LargeBag, hashtype), // () => gianthash = hasher.Hash(GiantBag, hashtype) // ); //Parallel.Invoke(() => // Parallel.ForEach(smallhash, h => // { // if (smallarrdisty.Contains(h.HashCode)) // smallarraycollisions++; // else // smallarrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(mediumhash, h => // { // if (mediumarrdisty.Contains(h.HashCode)) // mediumarraycollisions++; // else // mediumarrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(largehash, h => // { // if (largearrdisty.Contains(h.HashCode)) // largearraycollisions++; // else // largearrdisty.Add(h.HashCode); // }), () => // Parallel.ForEach(gianthash, h => // { // if (giantarrdisty.Contains(h.HashCode)) // giantarraycollisions++; // else // giantarrdisty.Add(h.HashCode); // })); ////() => ////{ //// hasher.Hash(MediumBag, hashtype).Map(h => //// { //// if (mediumarrdisty.Contains(h.HashCode)) //// mediumarraycollisions++; //// else //// mediumarrdisty.Add(h.HashCode); //// }); ////}, () => ////{ //// hasher.Hash(LargeBag, hashtype).Map(h => //// { //// if (largearrdisty.Contains(h.HashCode)) //// largearraycollisions++; //// else //// largearrdisty.Add(h.HashCode); //// }); ////}, () => ////{ //// hasher.Hash(GiantBag, hashtype).Map(h => //// { //// if (giantarrdisty.Contains(h.HashCode)) //// giantarraycollisions++; //// else //// giantarrdisty.Add(h.HashCode); //// }); ////}); #endregion #region slow way //List<Int32> smallarrdisty = new List<Int32>(SmallArray.Length); //Int32 smallarraycollisions = 0; //hasher.Hash(SmallArray, hashtype).Map(h => // { // if (smallarrdisty.Contains(h.HashCode)) // smallarraycollisions++; // else // smallarrdisty.Add(h.HashCode); // }); //List<Int32> mediumarrdisty = new List<Int32>(MediumArray.Length); //Int32 mediumarraycollisions = 0; //hasher.Hash(MediumArray, hashtype).AsParallel().Map(h => // { // if (mediumarrdisty.Contains(h.HashCode)) // mediumarraycollisions++; // else // mediumarrdisty.Add(h.HashCode); // }); //List<Int32> largearrdisty = new List<Int32>(LargeArray.Length); //Int32 largearraycollisions = 0; //hasher.Hash(LargeArray, hashtype).AsParallel().Map(h => // { // if (largearrdisty.Contains(h.HashCode)) // largearraycollisions++; // else // largearrdisty.Add(h.HashCode); // }); //List<Int32> superarrdisty = new List<Int32>(SuperArray.Length); //Int32 superarraycollisions = 0; //hasher.Hash(SuperArray, hashtype).AsParallel().Map(h => // { // if (superarrdisty.Contains(h.HashCode)) // superarraycollisions++; // else // superarrdisty.Add(h.HashCode); // }); #endregion #region best way //ConcurrentDictionary<Int32, Int32> smallarraydistribution = new ConcurrentDictionary<int, int>(20, 5500); //ConcurrentDictionary<Int32, Int32> mediumarraydistribution = new ConcurrentDictionary<int, int>(20, 60000); //ConcurrentDictionary<Int32, Int32> largearraydistribution = new ConcurrentDictionary<int, int>(20, 500000); //ConcurrentDictionary<Int32, Int32> superarraydistribution = new ConcurrentDictionary<int, int>(20, 20000000); Dictionary<Int32, Int32> smallarraydistribution = new Dictionary<Int32, Int32>(5500); Dictionary<Int32, Int32> mediumarraydistribution = new Dictionary<Int32, Int32>(60000); Dictionary<Int32, Int32> largearraydistribution = new Dictionary<Int32, Int32>(500000); Dictionary<Int32, Int32> superarraydistribution = new Dictionary<Int32, Int32>(20000000); IEnumerable<Hash> smallhash = null; IEnumerable<Hash> mediumhash = null; IEnumerable<Hash> largehash = null; IEnumerable<Hash> superhash = null; DateTime starthash = DateTime.Now; Parallel.Invoke( () => smallhash = hasher.Hash(SmallArray, hashtype), () => mediumhash = hasher.Hash(MediumArray, hashtype), () => largehash = hasher.Hash(LargeArray, hashtype), () => superhash = hasher.Hash(SuperArray, hashtype) ); DateTime endhash = DateTime.Now; DateTime startdist = DateTime.Now; #region seems threads get too swamped //Parallel.ForEach(smallhash, h => // { // if (smallarraydistribution.ContainsKey(h.HashCode)) // smallarraydistribution[h.HashCode] += 1; // else // smallarraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(mediumhash, h => // { // if (mediumarraydistribution.ContainsKey(h.HashCode)) // mediumarraydistribution[h.HashCode] += 1; // else // mediumarraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(largehash, h => // { // if (largearraydistribution.ContainsKey(h.HashCode)) // largearraydistribution[h.HashCode] += 1; // else // largearraydistribution.TryAdd(h.HashCode, 1); // }); //Parallel.ForEach(superhash, h => // { // if (superarraydistribution.ContainsKey(h.HashCode)) // { // Int32 old = superarraydistribution[h.HashCode]; // if(!superarraydistribution.TryUpdate(h.HashCode, old + 1, old)) // Console.WriteLine("Super Distribution failed to update: " + h.HashCode); // } // else // if (!superarraydistribution.TryAdd(h.HashCode, 1)) // Console.WriteLine("Super Distribution failed to add: " + h.HashCode); // }); #endregion smallarraydistribution = smallhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); mediumarraydistribution = mediumhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); largearraydistribution = largehash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); superarraydistribution = superhash.Select<Int32, Int32, Hash>((h, d) => { if (d.ContainsKey(h.HashCode)) d[h.HashCode] += 1; else d.Add(h.HashCode, 1); }); DateTime enddist = DateTime.Now; Int32 smalltotalcollisions = 0, mediumtotalcollisions = 0, largetotalcollisions= 0, supertotalcollisions = 0; Int32 smallcollisions = smallarraydistribution.Count(d =>{ if (d.Value > 1) { smalltotalcollisions += d.Value; return true; } else return false; }); Int32 mediumcollisions = mediumarraydistribution.Count(d => { if (d.Value > 1) { mediumtotalcollisions += d.Value; return true; } else return false; }); Int32 largecollisions = largearraydistribution.Count(d => { if (d.Value > 1) { largetotalcollisions += d.Value; return true; } else return false; }); Int32 supercollisions = superarraydistribution.Count(d => { if (d.Value > 1) { supertotalcollisions += d.Value; return true; } else return false; }); #endregion Console.WriteLine("Small Array Collisions: " + smallcollisions); Console.WriteLine("Small Array Total Collisions: " + smalltotalcollisions); Console.WriteLine("Medium Array Collisions: " + mediumcollisions); Console.WriteLine("Medium Array Total Collisions: " + mediumtotalcollisions); Console.WriteLine("Large Array Collisions: " + largecollisions); Console.WriteLine("Large Array Total Collisions: " + largetotalcollisions); Console.WriteLine("Super Array Collisions: " + supercollisions); Console.WriteLine("Super Array Total Collisions: " + supertotalcollisions); Console.WriteLine("Total Timer: " + (DateTime.Now - starttime).TotalSeconds); Console.WriteLine("Hash Timer: " + (endhash - starthash).TotalSeconds); Console.WriteLine("Distribution Timer: " + (enddist - startdist).TotalSeconds); Console.WriteLine(); }
public static string GetName(HashType code) => code.ToString().Replace("_", "-").ToLower();
/// <summary> /// Compares a hash of the specified plain text value to a given hash /// value. Plain text is hashed with the same salt value as the original /// hash. /// </summary> /// <param name="plainText"> /// Plain text to be verified against the specified hash. The function /// does not check whether this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified, /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="hashValue"> /// Base64-encoded hash value produced by ComputeHash function. This value /// includes the original salt appended to it. /// </param> /// <returns> /// If computed hash mathes the specified hash the function the return /// value is true; otherwise, the function returns false. /// </returns> public static bool VerifyHash(string plainText, HashType hashType, string hashValue) { // Convert base64-encoded hash value into a byte array. var hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Size of hash is based on the specified algorithm. switch (hashType.ToString()) { case "SHA1": hashSizeInBits = 160; break; case "SHA256": hashSizeInBits = 256; break; case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits/8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. var saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashType); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); }
NotSupportedException NotSupportedHashAlgorithmException() { return(new NotSupportedException("not support hash algorithm :" + Type.ToString())); }
/// <summary> /// Create a HashInfo instance from HashType. /// </summary> public static HashInfo Find(HashType hashType) { Contract.Check(HashInfoByType.ContainsKey(hashType))?.Assert($"Invalid HashType passed for HashInfoLookup: [{hashType.ToString()}], hashCode: {hashType.GetHashCode()}"); return(HashInfoByType[hashType]); }