Esempio n. 1
0
 internal static byte[] ToAesKey(this SecureString password)
 {
     using (SHA256Cng sha256 = new SHA256Cng())
     {
         byte[] passwordBytes = password.ToArray();
         byte[] passwordHash = sha256.ComputeHash(passwordBytes);
         byte[] passwordHash2 = sha256.ComputeHash(passwordHash);
         Array.Clear(passwordBytes, 0, passwordBytes.Length);
         Array.Clear(passwordHash, 0, passwordHash.Length);
         return passwordHash2;
     }
 }
Esempio n. 2
0
 public static byte[] ToAesKey(this string password)
 {
     using (SHA256Cng sha256 = new SHA256Cng())
     {
         byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
         byte[] passwordHash = sha256.ComputeHash(passwordBytes);
         byte[] passwordHash2 = sha256.ComputeHash(passwordHash);
         Array.Clear(passwordBytes, 0, passwordBytes.Length);
         Array.Clear(passwordHash, 0, passwordHash.Length);
         return passwordHash2;
     }
 }
Esempio n. 3
0
 /// <summary>
 /// Hash function: H(data)
 /// </summary>
 public static string Hash(string message)
 {
     using (SHA256Cng sha256 = new SHA256Cng())
     {
         return Convert.ToBase64String(sha256.ComputeHash(Encoding.Unicode.GetBytes(message)));
     }
 }
        static void Main(string[] args)
        {
            Console.WriteLine("MD5 und SHA Beispiel - Salt & Pepper");
            Console.WriteLine("====================================");

            //sollte aus einer anderen Quelle gelesen werden. Der Einfachheit halber wird ein String verwendet
            var pepper = "@ktdRdotewStee31223!!!33sdrt532sv224vvl420094";

            //Eingabe lesen und in ein Byte-Array verwandeln
            var salt = Salt("Benutzer");
            var bytes = new ASCIIEncoding().GetBytes(string.Format("{0}{1}{2}",Input(), salt, pepper));

            //MD5
            var md5 = new MD5Cng();
            string md5Hash = BitConverter.ToString(md5.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("MD5-Hash:\t{0}", md5Hash);

            //SHA1
            var sha1Cng = new SHA1Cng();
            string sha1Hash = BitConverter.ToString(sha1Cng.ComputeHash(bytes)).Replace("-","").ToLower();
            Console.WriteLine("SHA1-Hash:\t{0}", sha1Hash);

            //SHA256
            var sha256 = new SHA256Cng();
            string sha256Hash = BitConverter.ToString(sha256.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("SHA256-Hash:\t{0}", sha256Hash);

            Console.WriteLine("Beliebige Taste drücken zum beenden");
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("MD5 und SHA Beispiel");
            Console.WriteLine("====================");

            //Eingabe lesen und in ein Byte-Array verwandeln
            var bytes = new ASCIIEncoding().GetBytes(Input());

            //MD5
            var md5 = new MD5Cng();
            string md5Hash = BitConverter.ToString(md5.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("MD5-Hash:\t{0}", md5Hash);

            //SHA1
            var sha1Cng = new SHA1Cng();
            string sha1Hash = BitConverter.ToString(sha1Cng.ComputeHash(bytes)).Replace("-","").ToLower();
            Console.WriteLine("SHA1-Hash:\t{0}", sha1Hash);

            //SHA256
            var sha256 = new SHA256Cng();
            string sha256Hash = BitConverter.ToString(sha256.ComputeHash(bytes)).Replace("-", "").ToLower();
            Console.WriteLine("SHA256-Hash:\t{0}", sha256Hash);

            Console.WriteLine("Beliebige Taste drücken zum beenden");
            Console.ReadKey();
        }
Esempio n. 6
0
 public String hashearSHA256(String input)
 {
     SHA256Cng encriptador = new SHA256Cng();
     byte[] inputEnBytes = System.Text.Encoding.UTF8.GetBytes(input);
     byte[] inputHashBytes = encriptador.ComputeHash(inputEnBytes);
     return BitConverter.ToString(inputHashBytes).Replace("-", string.Empty).ToLower();
 }
Esempio n. 7
0
 public static byte[] HashString(string input)
 {
     using (var hasher = new SHA256Cng())
     {
         return hasher.ComputeHash(Encoding.UTF8.GetBytes(input));
     }
 }
Esempio n. 8
0
 public static string Hash(byte[] data)
 {
     using (SHA256Cng sha256 = new SHA256Cng())
     {
         return Convert.ToBase64String(sha256.ComputeHash(data));
     }
 }
Esempio n. 9
0
 public void HashPassword()
 {
     const string password = "******";
     var algorithm = new SHA256Cng();
     var unicoding = new UnicodeEncoding();
     var hash = unicoding.GetString(algorithm.ComputeHash(unicoding.GetBytes(password)));
     Log(hash);
 }
 public string CreateSha256Hash(string input)
 {
     using (SHA256Cng sha = new SHA256Cng())
     {
         UTF8Encoding encoding = new UTF8Encoding();
         return Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(input)));
     }
 }
        public static byte[] GetHash([NotNull] string input, [CanBeNull] HashAlgorithm algorithm = null)
        {
            byte[] buffer = Encoding.Unicode.GetBytes(input);
            if (algorithm != null)
                return algorithm.ComputeHash(buffer);

            using (algorithm = new SHA256Cng())
                return algorithm.ComputeHash(buffer);
        }
Esempio n. 12
0
 public CtVerifier(byte[] publicKey)
 {
     var key = DecodeSubjectPublicKeyInfo(publicKey);
     if (key == null)
     {
         throw new ArgumentException("Could not decode public key.", nameof(publicKey));
     }
     _key = key;
     using (var sha = new SHA256Cng())
     {
         LogId = sha.ComputeHash(publicKey);
     }
 }
Esempio n. 13
0
 public ActionResult Unlock(UnlockerModel model)
 {
     var algorithm = new SHA256Cng();
     var unicoding = new UnicodeEncoding();
     var hashed = unicoding.GetString(algorithm.ComputeHash(unicoding.GetBytes(model.Passphrase)));
     if (hashed == "嘃ᥐ倹⦦듑ꈳ囬쀺诫谾臭ᰠ屯")
     {
         FormsAuthentication.SetAuthCookie("Manager", false);
         var url = Handy.BaseUrl() + (model.ReturnUrl ?? Url.Action("Unlock"));
         return Redirect(url);
     }
     ModelState.AddModelError("AuthenticationFailed", "Wrong Passphrase");
     return View();
 }
Esempio n. 14
0
        /// <summary>Gets the SHA-2 Hash of a file.</summary>
        /// <param name="str">The string to calculate hash.</param>
        /// <returns>The SHA-2 Hash.</returns>
        public static string GetHash(string str)
        {
            var buff = new StringBuilder(10);
            using (var sha2 = new SHA256Cng())
            {
                sha2.ComputeHash(Encoding.Unicode.GetBytes(str));
                foreach (byte hashByte in sha2.Hash)
                {
                    buff.Append(string.Format(CultureInfo.InvariantCulture, "{0:X1}", hashByte));
                }
            }

            return buff.ToString();
        }
Esempio n. 15
0
        public static HashData ComputeHashes(string fileName)
        {
            try
            {
                using (FileStream stream = File.OpenRead(fileName))
                {
                    using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
                    {
                        string md5, sha1, sha256;
                        byte[] checksum;

                        using (var md5Cng = new MD5Cng())
                        {
                            checksum = md5Cng.ComputeHash(bufferedStream);
                            md5 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        stream.Seek(0, SeekOrigin.Begin);
                        bufferedStream.Seek(0, SeekOrigin.Begin);

                        using (var sha1Cng = new SHA1Cng())
                        {
                            checksum = sha1Cng.ComputeHash(bufferedStream);
                            sha1 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        stream.Seek(0, SeekOrigin.Begin);
                        bufferedStream.Seek(0, SeekOrigin.Begin);

                        using (var sha256Cng = new SHA256Cng())
                        {
                            checksum = sha256Cng.ComputeHash(bufferedStream);
                            sha256 = BitConverter.ToString(checksum).Replace("-", string.Empty);
                        }

                        return new HashData(md5, sha1, sha256);
                    }
                }
            }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
            return null;
        }
Esempio n. 16
0
        public static string ComputeSha256Hash(string fileName)
        {
            string sha256Hash = null;

            try
            {
                using (FileStream stream = File.OpenRead(fileName))
                {
                    using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
                    {
                        var sha = new SHA256Cng();
                        byte[] checksum = sha.ComputeHash(bufferedStream);
                        sha256Hash = BitConverter.ToString(checksum).Replace("-", String.Empty);
                    }
                }
            }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
            return sha256Hash;
        }
        /// <summary>
        /// Gets the input string as a SHA256 Base64 encoded string.
        /// </summary>
        /// <param name="input">The input to hash.</param>
        /// <param name="isCaseSensitive">If set to <c>false</c> the function will produce the same value for any casing of input.</param>
        /// <returns>The hashed value.</returns>
        public static string GetHashedId(string input, bool isCaseSensitive = false)
        {
            // for nulls, return an empty string, else hash.
            if (input == null)
            {
                return string.Empty;
            }

            using (SHA256 hasher = new SHA256Cng())
            {
                string temp = input;
                if (isCaseSensitive == false)
                {
                    temp = input.ToUpperInvariant();
                }

                byte[] buffer = hasher.ComputeHash(Encoding.UTF8.GetBytes(temp));
                return new SoapBase64Binary(buffer).ToString();
            }
        }        
Esempio n. 18
0
        public static byte[] ComputeSHA256(IList<string> parameters)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    foreach (string parameter in parameters)
                    {
                        bw.Write(parameter); // also writes the length as a prefix; unambiguous
                    }
                    bw.Flush();

                    using (SHA256Cng sha256 = new SHA256Cng())
                    {
                        byte[] retVal = sha256.ComputeHash(ms.GetBuffer(), 0, checked((int)ms.Length));
                        return retVal;
                    }
                }
            }
        }
Esempio n. 19
0
		public static byte[] ComputeSHA256(IList<string> parameters)
		{
			byte[] result;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
				{
					foreach (string current in parameters)
					{
						binaryWriter.Write(current);
					}
					binaryWriter.Flush();
					using (SHA256Cng sHA256Cng = new SHA256Cng())
					{
						byte[] array = sHA256Cng.ComputeHash(memoryStream.GetBuffer(), 0, checked((int)memoryStream.Length));
						result = array;
					}
				}
			}
			return result;
		}
 private string GetImageHash(byte[] image)
 {
     var sha256 = new SHA256Cng();
     return Encoding.Default.GetString(sha256.ComputeHash(image));
 }
Esempio n. 21
0
 private static byte[] ComputeHash(string hashAlgorithmName, string fileName)
 {
     HashAlgorithm hashAlgorithm = null;
     switch (hashAlgorithmName)
     {
         case StrMd5:
             hashAlgorithm = new MD5Cng();
             break;
         case StrSha1:
             hashAlgorithm = new SHA1Cng();
             break;
         case StrSha256:
             hashAlgorithm = new SHA256Cng();
             break;
     }
     if (null != hashAlgorithm)
     {
         using (var stream = File.OpenRead(fileName))
         {
             return hashAlgorithm.ComputeHash(stream);
         }
     }
     var message = String.Format("Invalid hash algorithm name: {0}", hashAlgorithmName);
     throw new ApplicationException(message);
 }
Esempio n. 22
0
        private static string EncryptAES(string decrypted)
        {
            if (string.IsNullOrEmpty(decrypted)) {
                ASF.ArchiLogger.LogNullError(nameof(decrypted));
                return null;
            }

            try {
                byte[] key;
                using (SHA256Cng sha256 = new SHA256Cng()) {
                    key = sha256.ComputeHash(EncryptionKey);
                }

                byte[] encryptedData = Encoding.UTF8.GetBytes(decrypted);
                encryptedData = SteamKit2.CryptoHelper.SymmetricEncrypt(encryptedData, key);
                return Convert.ToBase64String(encryptedData);
            } catch (Exception e) {
                ASF.ArchiLogger.LogGenericException(e);
                return null;
            }
        }
Esempio n. 23
0
 public static byte[] ComputeHash(string password, byte[] salt)
 {
     var sha = new SHA256Cng();
     return sha.ComputeHash(sha.ComputeHash(Encoding.UTF8.GetBytes(password)).Select((b, i) => (byte)(b ^ salt[i])).ToArray());
 }
Esempio n. 24
0
 public static string CreateSessionId()
 {
     var sha = new SHA256Cng();
     return sha.ComputeHash(Guid.NewGuid().ToByteArray()).Aggregate("", (s, b) => s += b.ToString("X"));
 }
Esempio n. 25
0
		private static string DecryptAES(string encrypted) {
			if (string.IsNullOrEmpty(encrypted)) {
				Logging.LogNullError(nameof(encrypted));
				return null;
			}

			try {
				byte[] key;
				using (SHA256Cng sha256 = new SHA256Cng()) {
					key = sha256.ComputeHash(EncryptionKey);
				}

				byte[] decryptedData = Convert.FromBase64String(encrypted);
				decryptedData = SteamKit2.CryptoHelper.SymmetricDecrypt(decryptedData, key);
				return Encoding.UTF8.GetString(decryptedData);
			} catch (Exception e) {
				Logging.LogGenericException(e);
				return null;
			}
		}
        private string ComputePasswordHash(string password, string salt)
        {
            var sha256 = new SHA256Cng();
            password += salt;

            byte[] hash = sha256.ComputeHash(Encoding.Default.GetBytes(password));

            return BitConverter.ToString(hash, 0);
        }
 public static byte[] GetHash([NotNull]Stream inputStream, [CanBeNull] HashAlgorithm algorithm = null)
 {
     if (algorithm != null)
         return algorithm.ComputeHash(inputStream);
     using (algorithm = new SHA256Cng())
         return algorithm.ComputeHash(inputStream);
 }
Esempio n. 28
0
 static Byte[] ComputeFIPS(Byte[] bytes)
 {
     SHA256Cng sha256 = new SHA256Cng();
     return sha256.ComputeHash(bytes);
 }
        public static byte[] GetHash([NotNull]byte[] buffer, int offset = 0, int count = -1, [CanBeNull] HashAlgorithm algorithm = null)
        {
            if (count < 0) count = buffer.Length;
            // ReSharper disable AssignNullToNotNullAttribute
            if (algorithm != null)
                return offset != 0 || count != buffer.Length
                    ? algorithm.ComputeHash(buffer, offset, count)
                    : algorithm.ComputeHash(buffer);

            using (algorithm = new SHA256Cng())
                return offset != 0 || count != buffer.Length
                    ? algorithm.ComputeHash(buffer, offset, count)
                    : algorithm.ComputeHash(buffer);
            // ReSharper restore AssignNullToNotNullAttribute
        }
        internal string GetChildActionUniqueId(ActionExecutingContext filterContext)
        {
            StringBuilder uniqueIdBuilder = new StringBuilder();

            // Start with a prefix, presuming that we share the cache with other users
            uniqueIdBuilder.Append(CacheKeyPrefix);

            // Unique ID of the action description
            uniqueIdBuilder.Append(filterContext.ActionDescriptor.UniqueId);

            // Unique ID from the VaryByCustom settings, if any
            uniqueIdBuilder.Append(DescriptorUtil.CreateUniqueId(VaryByCustom));
            if (!String.IsNullOrEmpty(VaryByCustom))
            {
                string varyByCustomResult = filterContext.HttpContext.ApplicationInstance.GetVaryByCustomString(HttpContext.Current, VaryByCustom);
                uniqueIdBuilder.Append(varyByCustomResult);
            }

            // Unique ID from the VaryByParam settings, if any
            uniqueIdBuilder.Append(GetUniqueIdFromActionParameters(filterContext, SplitVaryByParam(VaryByParam)));

            // The key is typically too long to be useful, so we use a cryptographic hash
            // as the actual key (better randomization and key distribution, so small vary
            // values will generate dramtically different keys).
            using (SHA256Cng sha = new SHA256Cng())
            {
                return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(uniqueIdBuilder.ToString())));
            }
        }