protected BaseProcessor(Stream inputStream, Stream outputStream, OperationType operationType, HashTypes hashType = HashTypes.Undefined) { this.hashType = hashType; this.inputStream = inputStream; this.outputStream = outputStream; this.operationType = operationType; }
public static string GetHash(byte[] bytes, HashTypes hashType) { dynamic cryptoService = GetCryptoServiceProvider(hashType); if (cryptoService == null) return null; var hashBytes = cryptoService.ComputeHash(bytes); return FormatHash(hashBytes); }
public static string GetHash(FileStream stream, HashTypes hashType) { dynamic cryptoService = GetCryptoServiceProvider(hashType); if (cryptoService == null) return null; var hashBytes = cryptoService.ComputeHash(stream); stream.Close(); return FormatHash(hashBytes); }
///<summary>Returns a Password container with the hashedPass. Will always include a salt. Generates it using the passed in hashType. ///Throws an exception if a passed in hash type is not implimented.</summary> public static PasswordContainer GenerateLoginDetails(string inputPass, HashTypes hashType) { //No need to check RemotingRole; no call to db. //Always generate a salt because this should be used for passwords, which shuold always have salt. string salt = GenerateSalt(hashType); //Use salt to generate new hash. string passNew = GetHash(inputPass, salt, hashType); return(new PasswordContainer(hashType, salt, passNew)); }
public static bool CheckHashType(HashTypes hashType, bool throwException) { var valid = Enum.IsDefined(typeof(HashTypes), hashType); if (!valid && throwException) { throw new ArgumentException(string.Format("Invalid hash type {0}", hashType)); } return(valid); }
public void Reset() { mstrSaltValue = String.Empty; mstrOriginalString = String.Empty; mstrHashString = String.Empty; mboolUseSalt = false; mbytHashType = HashTypes.SHA1; mhash = null; }
///<summary>Compares a inputPass password and salt against a hash using the given hashing algorithm.</summary> public static bool CheckPassword(string inputPass, string salt, string hash, HashTypes hashType) { //No need to check RemotingRole; no call to db. if (salt == null) { salt = ""; } string key = GetHash(inputPass, salt, hashType); return(ConstantEquals(key, hash)); }
private HashTypes GetRolledUpHashTypes(HashTypes[] hashTypes) { HashTypes requestedHashes = 0; foreach (var ht in hashTypes) { requestedHashes = requestedHashes | ht; } return(requestedHashes); }
///<summary>Updates a password for a given Reseller account and saves it to the database. Suggested hash type is SHA3-512.</summary> public static bool UpdatePasswordReseller(Reseller user, string inputPass, HashTypes hashType = HashTypes.SHA3_512) { //No need to check RemotingRole; no call to db. user.LoginDetails = GenerateLoginDetails(inputPass, hashType); try { Resellers.Update(user); } catch { return(false); } return(true); }
public static Hash HashHash(Hash hash1, Hash hash2, HashTypes resultType) { var b1 = hash1.RawData; var b2 = hash2.RawData; var hashData = new byte[b1.Count + b2.Count]; Buffer.BlockCopy(b1.Array, b1.Offset, hashData, 0, b1.Count); Buffer.BlockCopy(b2.Array, b2.Offset, hashData, b1.Count, b2.Count); return(Hash.Generate(resultType, hashData)); }
public static Hasher GetHasher(HashTypes hashType) { switch(hashType) { case HashTypes.SHA256: return new SHA256Hasher(); case HashTypes.MD5: return new MD5Hasher(); default: return new MD5Hasher(); } }
public static int GetHashSize(HashTypes hashType) { switch(hashType) { case HashTypes.SHA256: return 32; case HashTypes.MD5: return 16; default: return 16; } }
///<summary>Initialize a PasswordContainer struct with the passed in values. ///If the password hash passed in is null or empty then HashType will be set to None with a blank Salt.</summary> public PasswordContainer(HashTypes hashType, string salt, string passwordHash) { if (string.IsNullOrEmpty(passwordHash)) { HashType = HashTypes.None; Salt = ""; } else { HashType = hashType; Salt = salt; } Hash = passwordHash; }
public static Hash Empty(HashTypes hashType) { if (_empty.TryGetValue(hashType, out var hash)) { return(hash); } var data = new byte[GetHashBytes(hashType, true)]; data[0] = (byte)hashType; hash = Restore(new ArraySegment <byte>(data)); _empty[hashType] = hash; return(hash); }
///<summary>Updates a password for a given Userod account and saves it to the database. Suggested hash type is SHA3-512. ///Throws an exception if a passed in hash type is not implimented.</summary> public static bool UpdatePasswordUserod(Userod user, string inputPass, HashTypes hashType = HashTypes.SHA3_512) { //No need to check RemotingRole; no call to db. //Calculate the password strength. bool passStrength = String.IsNullOrEmpty(Userods.IsPasswordStrong(inputPass)); PasswordContainer loginDetails = GenerateLoginDetails(inputPass, hashType); try { Userods.UpdatePassword(user, loginDetails, passStrength); } catch { return(false); } return(true); }
public static Dictionary <HashTypes, HashAlgorithm> GetHashers(this HashTypes hashTypes) { var hashers = new Dictionary <HashTypes, HashAlgorithm>(); var types = Enum.GetValues(hashTypes.GetType()); foreach (HashTypes type in types) { if ((hashTypes & type) == type) { hashers.Add(type, type.GetHasher()); } } return(hashers); }
public static byte[] GetHash(this string str, HashTypes type = HashTypes.DEFAULT) { switch (type) { case HashTypes.DEFAULT: return(BitConverter.GetBytes(str.GetHashCode())); case HashTypes.SHA3: return(SHA3(str)); case HashTypes.SHALE: return(SHALE(str)); } throw new ArgumentException("HashType does not exist"); }
public static ushort GetHashBytes(HashTypes hashType, bool padding = true) { if (hashType == HashTypes.Sha1) { return((ushort)(SHA1_BYTES + (padding ? PADDING_BYTES : 0))); } if (hashType == HashTypes.Sha256) { return((ushort)(SHA256_BYTES + (padding ? PADDING_BYTES : 0))); } if (hashType == HashTypes.Sha512) { return((ushort)(SHA512_BYTES + (padding ? PADDING_BYTES : 0))); } throw new ArgumentException(string.Format("Hash type not implemented {0}", hashType)); }
public static Hash Generate(HashTypes hashType, Stream stream) { if (hashType == HashTypes.Sha1) { return(new Sha1Hash(default(ArraySegment <byte>), stream, true)); } if (hashType == HashTypes.Sha512) { return(new Sha512Hash(default(ArraySegment <byte>), stream, true)); } if (hashType == HashTypes.Sha256) { return(new Sha256Hash(default(ArraySegment <byte>), stream, true)); } throw new ArgumentException(string.Format("Hash type not implemented {0}", hashType)); }
private static string getHash(string str, HashTypes type) { dynamic hasher = new MD5CryptoServiceProvider(); switch (type) { case HashTypes.SHA1: hasher = new SHA1CryptoServiceProvider(); break; case HashTypes.SHA256: hasher = new SHA256CryptoServiceProvider(); break; } return(getHexString(hasher.ComputeHash(Encoding.Default.GetBytes(str)))); }
public override string ToString() { return "QueryPlanIndexItemForge{" + "unique=" + IsUnique + ", hashProps=" + HashProps.RenderAny() + ", rangeProps=" + RangeProps.RenderAny() + ", hashTypes=" + HashTypes.RenderAny() + ", rangeTypes=" + RangeTypes.RenderAny() + ", advanced=" + AdvancedIndexProvisionDesc?.IndexDesc.IndexTypeName + "}"; }
/// <summary> /// </summary> /// <param name="threadsCount">Count of workers.</param> /// <param name="hashType">Type of hash.</param> /// <param name="collback"></param> public BlocksHandler(int threadsCount, HashTypes hashType, OperationType operationType, Action<string> collback) { this.inpitLockObject = new object(); this.outputLockObject = new object(); this.input = new Queue<Block>(); this.output = new Queue<Block>(); this.workers = new Thread[threadsCount]; for (int i = 0; i < threadsCount; i++) { this.workers[i] = new Thread(()=> Run(operationType)); this.workers[i].Priority = ThreadPriority.Lowest; } this.hashType = hashType; this.collback = collback; }
///<summary>Will return the hash of whatever is passed in, including empty strings. ///Throws an exception if a passed in hash type is not implimented.</summary> public static string GetHash(string inputPass, string salt, HashTypes type) { //No need to check RemotingRole; no call to db. //Switch based on hashtype passed in. switch (type) { case HashTypes.MD5: return(HashPasswordMD5(salt + inputPass, false)); case HashTypes.MD5_ECW: return(HashPasswordMD5(inputPass, true)); //Backwards no salt ASCII way. >:( case HashTypes.SHA3_512: return(HashPasswordSHA512(inputPass, salt)); //512 bit hash (64 byte) case HashTypes.None: return(inputPass); } throw new ApplicationException(Lans.g("Authentication", "Hash Type not implimented:") + " " + type.ToString()); }
public static string HashPassword(string password) { if (string.IsNullOrEmpty(password) || password == "non-existant password") { return("non-existant password"); } Func <HashAlgorithm> func; if (!HashTypes.TryGetValue(HashAlgo.ToLower(), out func)) { throw new NotSupportedException(String.Format("Hashing algorithm {0} is not supported", (HashAlgo.ToLower()))); } using (var hash = func()) { var bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(password)); return(bytes.Aggregate("", (s, b) => s + b.ToString("X2"))); } }
/// <summary> /// Hashes the given string with the chosen hash algorithm /// </summary> /// <param name="toHash">string to hash</param> /// <param name="hashType">hash algorithm with which the string must be hashed</param> /// <returns>a hashed array or an empty byte array</returns> public byte[] Hash(string toHash, HashTypes hashType = HashTypes.SHA1) { LogService.Log(LogService.LogType.Info, "Cryptography - Hash called"); byte[] hash; if (hashType == HashTypes.SHA1) { SHA1Managed sha1 = new SHA1Managed(); hash = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(toHash)); } else if (hashType == HashTypes.SHA256) { SHA256Managed sha256 = new SHA256Managed(); hash = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(toHash)); } else { hash = new byte[] { } }; LogService.Log(LogService.LogType.Info, "successfully hashed the given value"); return(hash); }
public static ErrorCodes Run(string[] args, HashTypes hashType) { var filepath = ExeUtil.GetValue(args, 0); if (string.IsNullOrEmpty(filepath) || !File.Exists(filepath)) { return ErrorCodes.InvalidUsage; } var expectedHash = ExeUtil.GetValue(args, 1); var fileName = Path.GetFileName(filepath); Console.WriteLine("Getting {0} hash for {1}...", hashType, fileName); var fileHash = HashChecker.GetFileHash(filepath, hashType); Console.WriteLine(fileHash); Console.WriteLine(); if (string.IsNullOrWhiteSpace(expectedHash)) { return ErrorCodes.Success; } expectedHash = expectedHash.Trim(); Console.WriteLine(expectedHash); Console.WriteLine("is provided hash."); Console.WriteLine(); if (string.Equals(fileHash, expectedHash, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Success, file is valid"); } else { Console.Write("Invalid, Hash does not match"); return ErrorCodes.InvalidHash; } return ErrorCodes.Success; }
///<summary>Generates a random, base-64 encoded salt for a given hashtype.</summary> public static string GenerateSalt(HashTypes hashType) { //No need to check RemotingRole; no call to db. int hashLen; //hashLen should reflect the size of the algorithm output. SHA3-512 makes a 64 byte hash, so the salt should be 64 bytes also. switch (hashType) { case HashTypes.SHA3_512: hashLen = 64; break; case HashTypes.MD5: hashLen = 16; break; //eCW and None hashtypes don't use a salt. case HashTypes.MD5_ECW: case HashTypes.None: default: hashLen = 0; break; } return(GenerateSalt(hashLen)); }
private static string HashPassword(string password, string saltValue, HashTypes hashType) { if ((password == null) || (saltValue == null)) { return(null); } var saltBuffer = new byte[] { byte.Parse(saltValue.Substring(0, 2), NumberStyles.HexNumber), byte.Parse(saltValue.Substring(2, 2), NumberStyles.HexNumber), byte.Parse(saltValue.Substring(4, 2), NumberStyles.HexNumber), byte.Parse(saltValue.Substring(6, 2), NumberStyles.HexNumber) }; var passwordBuffer = Encoding.Unicode.GetBytes(password); var hashBuffer = new byte[4 + passwordBuffer.Length]; saltBuffer.CopyTo(hashBuffer, 0); passwordBuffer.CopyTo(hashBuffer, 4); return(saltValue + BinaryToHex(Hash(hashBuffer, hashType))); }
private static dynamic GetCryptoServiceProvider(HashTypes hashType) { dynamic cryptoService; switch (hashType) { case HashTypes.MD5: { cryptoService = new MD5CryptoServiceProvider(); } break; case HashTypes.SHA1: { cryptoService = new SHA1CryptoServiceProvider(); } break; case HashTypes.SHA256: { cryptoService = new SHA256CryptoServiceProvider(); } break; case HashTypes.SHA384: { cryptoService = new SHA384CryptoServiceProvider(); } break; case HashTypes.SHA512: { cryptoService = new SHA512CryptoServiceProvider(); } break; default: { return null; } } return cryptoService; }
/// <summary>Hash加密</summary> /// <param name="inputString">输入内容</param> /// <param name="hashType">Hash类型</param> /// <param name="lower">输出是否小写</param> /// <returns>Hash结果</returns> public static string Hash(string inputString, HashTypes hashType, bool lower) { return(Hash(inputString, hashType, Encoding.UTF8, lower)); }
/// <summary>Hash加密</summary> /// <param name="inputString">输入内容</param> /// <param name="hashType">Hash类型</param> /// <returns>Hash结果</returns> public static string Hash(string inputString, HashTypes hashType) { return(Hash(inputString, hashType, Encoding.UTF8, false)); }
protected Signature(KeyTypes keyType, HashTypes hashType) { KeyType = keyType; DataHashType = hashType; }
private async Task FillMissingHashes(SVR_VideoLocal vlocal, CancellationToken token, IProgress <ICommand> progress = null) { HashTypes types = 0; if (string.IsNullOrEmpty(vlocal.CRC32)) { types |= HashTypes.CRC; } if (string.IsNullOrEmpty(vlocal.MD5)) { types |= HashTypes.MD5; } if (string.IsNullOrEmpty(vlocal.SHA1)) { types |= HashTypes.SHA1; } if (types > 0) { FillVideoHashes(vlocal); } types = 0; if (string.IsNullOrEmpty(vlocal.CRC32)) { types |= HashTypes.CRC; } if (string.IsNullOrEmpty(vlocal.MD5)) { types |= HashTypes.MD5; } if (string.IsNullOrEmpty(vlocal.SHA1)) { types |= HashTypes.SHA1; } if (types > 0) { _hashingState = true; DateTime start = DateTime.Now; logger.Trace("Calculating missing {1} hashes for: {0}", File.FullName, types.ToString("F")); // update the VideoLocal record with the Hash, since cloud support we calculate everything Hasher h = new Hasher(File, HashAll); string error = await h.RunAsync(new ChildProgress(20, 60, this, progress), token); TimeSpan ts = DateTime.Now - start; logger.Trace("Hashed file in {0:#0.0} seconds --- {1} ({2})", ts.TotalSeconds, File.FullName, Utils.FormatByteSize(vlocal.FileSize)); if (error != null) { logger.Error("Unable to add additional hashes missing {1} hashes for: {0} Error {2}", File.FullName, types.ToString("F"), error); } else { if ((types & HashTypes.CRC) > 0) { vlocal.CRC32 = h.Result.GetHash(HashTypes.CRC); } if ((types & HashTypes.MD5) > 0) { vlocal.MD5 = h.Result.GetHash(HashTypes.MD5); } if ((types & HashTypes.SHA1) > 0) { vlocal.SHA1 = h.Result.GetHash(HashTypes.SHA1); } WebCacheAPI.Instance.AddHash(new List <WebCache_FileHash> { vlocal.ToHashRequest() }); } } }
public CompressionProcessor(Stream inputStream, Stream outputStream, int blockSize, HashTypes hashType = HashTypes.Undefined) : base(inputStream, outputStream, OperationType.Compress, blockSize, hashType) { }
public Hash(HashTypes HashType, string OriginalString) { mbytHashType = HashType; mstrOriginalString = OriginalString; }
public Hash(HashTypes HashType) { mbytHashType = HashType; }
public static string GetFileHash(string fullPathToFile, HashTypes hashType) { var stream = File.OpenRead(fullPathToFile); return GetHash(stream, hashType); }
public void TestGenerateHashFromFileInfo(string filename, string expectedHash, HashTypes hashType) { var fi = new FileInfo(filename); var hashResult = fi.GenerateHash(hashType); hashResult.Should().Be(expectedHash); }
public static string GetHash(string text, HashTypes hashType) { var encoder = new UTF8Encoding(); var bytes = encoder.GetBytes(text); return GetHash(bytes, hashType); }
public Hash() { mbytHashType = HashTypes.SHA1; }
public static string Get(HashTypes hashType, string originalString, string saltString) { Hash pHash = new Hash(); return(pHash.CreateHash(originalString, hashType, saltString)); }