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(); }
/// <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))); } }
public static string Hash(byte[] data) { using (SHA256Cng sha256 = new SHA256Cng()) { return Convert.ToBase64String(sha256.ComputeHash(data)); } }
public byte[] SignWithCertificate(string message, byte[] rawData, string password) { X509Certificate2 x509Certificate = new X509Certificate2(rawData, password); if (x509Certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits) { throw new ArgumentOutOfRangeException("rawData", string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits)); } X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(x509Certificate); RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider; RSACryptoServiceProvider newRsa = null; try { newRsa = GetCryptoProviderForSha256(rsa); using (SHA256Cng sha = new SHA256Cng()) { return newRsa.SignData(Encoding.UTF8.GetBytes(message), sha); } } finally { if (newRsa != null && !ReferenceEquals(rsa, newRsa)) { newRsa.Dispose(); } } }
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(); }
public static byte[] HashString(string input) { using (var hasher = new SHA256Cng()) { return hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); } }
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(); }
private static Func<SHA256> GetSHA256Factory() { // Note: ASP.NET 4.5 always prefers CNG, but the CNG algorithms are not that // performant on 4.0 and below. The following list is optimized for speed // given our scenarios. if (!CryptoConfig.AllowOnlyFipsAlgorithms) { // This provider is not FIPS-compliant, so we can't use it if FIPS compliance // is mandatory. return () => new SHA256Managed(); } try { using (SHA256Cng sha256 = new SHA256Cng()) { return () => new SHA256Cng(); } } catch (PlatformNotSupportedException) { // CNG not supported (perhaps because we're not on Windows Vista or above); move on } // If all else fails, fall back to CAPI. return () => new SHA256CryptoServiceProvider(); }
public static string Compute(HashType type, bool format, string data, string salt) { HashAlgorithm hash; string prefix; switch (type) { case HashType.MD5: prefix = "MD5"; hash = new MD5Cng(); break; case HashType.SHA1: prefix = "SHA1"; hash = new SHA1Cng(); break; case HashType.SHA256: prefix = "SHA256"; hash = new SHA256Cng(); break; case HashType.SHA384: prefix = "SHA384"; hash = new SHA384Cng(); break; case HashType.SHA512: prefix = "SHA512"; hash = new SHA512Cng(); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(salt+data); byte[] hashed = hash.ComputeHash(inputBytes); return format ? $"{{{prefix}:{GetHashHex(hashed)}}}" : GetHashHex(hashed); }
public string CreateSha256Hash(string input) { using (SHA256Cng sha = new SHA256Cng()) { UTF8Encoding encoding = new UTF8Encoding(); return Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(input))); } }
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 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); }
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; } }
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; } }
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); } }
/// <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(); }
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(); }
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; }
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; } } } }
/// <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(); } }
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; }
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; }
public static byte[] SignWithCertificate(string message, X509Certificate2 x509Certificate) { X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(x509Certificate); RSACryptoServiceProvider rsa = x509Key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, true) as RSACryptoServiceProvider; RSACryptoServiceProvider newRsa = null; try { newRsa = GetCryptoProviderForSha256(rsa); using (SHA256Cng sha = new SHA256Cng()) { return newRsa.SignData(Encoding.UTF8.GetBytes(message), sha); } } finally { if (newRsa != null && !object.ReferenceEquals(rsa, newRsa)) { newRsa.Dispose(); } } }
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); }
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; } }
/// <summary> /// This function uses the asymmetric key specified by the key path /// and decrypts an encrypted CEK with RSA encryption algorithm. /// </summary> /// <param name="masterKeyPath">Complete path of an asymmetric key in CNG</param> /// <param name="encryptionAlgorithm">Asymmetric Key Encryption Algorithm</param> /// <param name="encryptedColumnEncryptionKey">Encrypted Column Encryption Key</param> /// <returns>Plain text column encryption key</returns> public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey) { // Validate the input parameters ValidateNonEmptyKeyPath(masterKeyPath, isSystemOp: true); if (null == encryptedColumnEncryptionKey) { throw SQL.NullEncryptedColumnEncryptionKey(); } if (0 == encryptedColumnEncryptionKey.Length) { throw SQL.EmptyEncryptedColumnEncryptionKey(); } // Validate encryptionAlgorithm ValidateEncryptionAlgorithm(encryptionAlgorithm, isSystemOp: true); // Create RSA Provider with the given CNG name and key name RSACng rsaCngProvider = CreateRSACngProvider(masterKeyPath, isSystemOp: true); // Validate whether the key is RSA one or not and then get the key size int keySizeInBytes = GetKeySize(rsaCngProvider); // Validate and decrypt the EncryptedColumnEncryptionKey // Format is // version + keyPathLength + ciphertextLength + keyPath + ciphervtext + signature // // keyPath is present in the encrypted column encryption key for identifying the original source of the asymmetric key pair and // we will not validate it against the data contained in the CMK metadata (masterKeyPath). // Validate the version byte if (encryptedColumnEncryptionKey[0] != _version[0]) { throw SQL.InvalidAlgorithmVersionInEncryptedCEK(encryptedColumnEncryptionKey[0], _version[0]); } // Get key path length int currentIndex = _version.Length; UInt16 keyPathLength = BitConverter.ToUInt16(encryptedColumnEncryptionKey, currentIndex); currentIndex += sizeof(UInt16); // Get ciphertext length UInt16 cipherTextLength = BitConverter.ToUInt16(encryptedColumnEncryptionKey, currentIndex); currentIndex += sizeof(UInt16); // Skip KeyPath // KeyPath exists only for troubleshooting purposes and doesnt need validation. currentIndex += keyPathLength; // validate the ciphertext length if (cipherTextLength != keySizeInBytes) { throw SQL.InvalidCiphertextLengthInEncryptedCEKCng(cipherTextLength, keySizeInBytes, masterKeyPath); } // Validate the signature length // Signature length should be same as the key side for RSA PKCSv1.5 int signatureLength = encryptedColumnEncryptionKey.Length - currentIndex - cipherTextLength; if (signatureLength != keySizeInBytes) { throw SQL.InvalidSignatureInEncryptedCEKCng(signatureLength, keySizeInBytes, masterKeyPath); } // Get ciphertext byte[] cipherText = new byte[cipherTextLength]; Buffer.BlockCopy(encryptedColumnEncryptionKey, currentIndex, cipherText, 0, cipherText.Length); currentIndex += cipherTextLength; // Get signature byte[] signature = new byte[signatureLength]; Buffer.BlockCopy(encryptedColumnEncryptionKey, currentIndex, signature, 0, signature.Length); // Compute the hash to validate the signature byte[] hash; using (SHA256Cng sha256 = new SHA256Cng()) { sha256.TransformFinalBlock(encryptedColumnEncryptionKey, 0, encryptedColumnEncryptionKey.Length - signature.Length); hash = sha256.Hash; } Debug.Assert(hash != null, @"hash should not be null while decrypting encrypted column encryption key."); // Validate the signature if (!RSAVerifySignature(hash, signature, rsaCngProvider)) { throw SQL.InvalidSignature(masterKeyPath); } // Decrypt the CEK return RSADecrypt(rsaCngProvider, cipherText); }
static CheckResult CheckFile(string dir, RepoFileInfo f, ref string msg, bool checkHash) { string fname = dir + f.Name; var fi = new FileInfo(fname); if (!fi.Exists) { msg = String.Format("File '{0}' does not exist.", f.Name); return CheckResult.NotExist; } if (f.Size.HasValue && fi.Length != f.Size) { msg = String.Format("File '{0}' size {1} mismatches, needs {2}.", f.Name, fi.Length, f.Size); return CheckResult.BadSize; } if (checkHash) { string hType = f.CsumType.ToUpper(); HashAlgorithm hAlg; if (!algs.TryGetValue(hType, out hAlg)) { if (hType == "SHA256") hAlg = new SHA256Cng(); else hAlg = HashAlgorithm.Create(hType); algs[hType] = hAlg; } string hash; using (var fs = File.OpenRead(fname)) hash = String.Join("", hAlg.ComputeHash(fs).Select(b => b.ToString("x2"))); if (f.Csum.ToLower() != hash) { msg = String.Format("File '{0}' {1}-hash {2} mismatches needed {3}.", f.Name, f.CsumType, hash, f.Csum); return CheckResult.BadHash; } } return CheckResult.OK; }
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); }
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()))); } }