public byte[] GetDataKey() { SHA256Cng sha256 = new SHA256Cng(); StringBuilder builder = new StringBuilder("matkhau#cucki#ma%nh,mo!t^minhanhcha%phe%t.rah thi cu hack :) :3"); return(sha256.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()))); }
/// <summary> /// Computes a SHA-256 hash of a given file /// </summary> /// <param name="filePath">Path to the file to hash.</param> /// <returns>Lowercase string representation of the hash.</returns> public static string GetFileHash(string filePath) { byte[] hash; SHA256 sha; // This is a work around for Windows XP. try { sha = new SHA256Cng(); } catch (PlatformNotSupportedException) { sha = SHA256.Create(); } using (sha) { using (FileStream stream = File.OpenRead(filePath)) { hash = sha.ComputeHash(stream); } } return(string.Concat(hash.Select(x => x.ToString("x2")))); }
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 DescriptorUtil.AppendUniqueId(uniqueIdBuilder, 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 BuildUniqueIdFromActionParameters(uniqueIdBuilder, filterContext); // 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())))); } }
/// <summary> /// Given a file path, compute the file hashes. /// </summary> /// <param name="filePath"></param> /// <param name="md5Hash"></param> /// <param name="sha1Hash"></param> /// <param name="sha256Hash"></param> public static void ComputeHashes(string filePath, out byte[] md5Hash, out byte[] sha1Hash, out byte[] sha256Hash) { using (var md5 = MD5Cng.Create()) using (var sha1 = SHA1Cng.Create()) using (var sha256 = SHA256Cng.Create()) using (var input = File.OpenRead(filePath)) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { md5.TransformBlock(buffer, 0, bytesRead, buffer, 0); sha1.TransformBlock(buffer, 0, bytesRead, buffer, 0); sha256.TransformBlock(buffer, 0, bytesRead, buffer, 0); } // We have to call TransformFinalBlock, but we don't have any // more data - just provide 0 bytes. md5.TransformFinalBlock(buffer, 0, 0); sha1.TransformFinalBlock(buffer, 0, 0); sha256.TransformFinalBlock(buffer, 0, 0); md5Hash = md5.Hash; sha1Hash = sha1.Hash; sha256Hash = sha256.Hash; } }
/// <summary> /// Generates a Jws Signature. /// </summary> /// <param name="header"></param> /// <param name="payload"></param> /// <returns></returns> public string GenerateSignature(Dictionary <string, object> header, Dictionary <string, object> payload) { string securedInput = SecureInput(header, payload); byte[] message = Encoding.UTF8.GetBytes(securedInput); SHA256Cng sha256Hasher = new SHA256Cng(); byte[] hashedMessage = sha256Hasher.ComputeHash(message); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, _privateKey); BigInteger[] results = signer.GenerateSignature(hashedMessage); // Concated to create signature var a = results[0].ToByteArrayUnsigned(); var b = results[1].ToByteArrayUnsigned(); // a,b are required to be exactly the same length of bytes if (a.Length != b.Length) { int largestLength = Math.Max(a.Length, b.Length); a = ByteArrayPadLeft(a, largestLength); b = ByteArrayPadLeft(b, largestLength); } string signature = UrlBase64.Encode(a.Concat(b).ToArray()); return(String.Format("{0}.{1}", securedInput, signature)); }
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 void ComputeHash(String filePath) { using (var md5 = SHA256Cng.Create()) { this.md5String = md5.ComputeHash(File.ReadAllBytes(filePath)); } }
/// <summary> /// Returns a hash value from a byte array. /// </summary> /// <param name="input">The byte array to hash.</param> /// <param name="bits">The length of the hash (256, 384, or 512).</param> /// <returns></returns> private static Byte[] BytesToHash(Byte[] input, Int32 bits) { Byte[] hash = new Byte[0]; switch (bits) { case 256: hash = new SHA256Cng().ComputeHash(input); break; case 384: hash = new SHA384Cng().ComputeHash(input); break; case 512: hash = new SHA512Cng().ComputeHash(input); break; default: hash = new SHA256Cng().ComputeHash(input); break; } return(hash); }
private byte[] ComputeQueryStringHash(string queryString) { // Validate the input parameters if (string.IsNullOrWhiteSpace(queryString)) { string argumentName = "queryString"; if (null == queryString) { throw SQL.NullArgumentInternal(argumentName, ClassName, ComputeQueryStringHashName); } else { throw SQL.EmptyArgumentInternal(argumentName, ClassName, ComputeQueryStringHashName); } } byte[] queryStringBytes = Encoding.Unicode.GetBytes(queryString); // Compute hash byte[] hash; using (SHA256Cng sha256 = new SHA256Cng()) { sha256.TransformFinalBlock(queryStringBytes, 0, queryStringBytes.Length); hash = sha256.Hash; } return(hash); }
public byte[] CreateUsernamePasswordHash(String Username, String Password) { if (String.IsNullOrEmpty(Username) || String.IsNullOrEmpty(Password)) { return(null); } this.Username = Username; SHA256 mySha = SHA256Cng.Create(); MemoryStream mYStream = new MemoryStream(); byte[] ID = Encoding.ASCII.GetBytes(Username); mYStream.Write(ID, 0, ID.Length); ID = Encoding.ASCII.GetBytes(Password); mYStream.Write(ID, 0, ID.Length); byte[] byteReturn = mySha.ComputeHash(mYStream.ToArray()); mYStream = new MemoryStream(); Debug.WriteLine("Created " + BitConverter.ToString(byteReturn)); ID = BitConverter.GetBytes(base.GetCreationTime()); Debug.WriteLine("TIME STAMP " + BitConverter.ToString(ID)); mYStream.Write(ID, 0, ID.Length); mYStream.Write(byteReturn, 0, byteReturn.Length); Debug.WriteLine("PREHASH " + BitConverter.ToString(mYStream.ToArray())); mySHAHash = mySha.ComputeHash(mYStream.ToArray()); InternalSettings.UserID = mySHAHash; base.UserID = InternalSettings.UserID; InternalSettings.Username = Username; Debug.WriteLine("GENERATED HASH " + BitConverter.ToString(mySHAHash)); return(byteReturn); }
public byte[] SignWithCertificate(string message, X509Certificate2 certificate) { if (certificate.PublicKey.Key.KeySize < ClientAssertionCertificate.MinKeySizeInBits) { throw new ArgumentOutOfRangeException("rawData", string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.CertificateKeySizeTooSmallTemplate, ClientAssertionCertificate.MinKeySizeInBits)); } X509AsymmetricSecurityKey x509Key = new X509AsymmetricSecurityKey(certificate); 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 static string Hash(byte[] data) { using (SHA256Cng sha256 = new SHA256Cng()) { return(Convert.ToBase64String(sha256.ComputeHash(data))); } }
/// <summary> /// Hash the data passed using the hash size specified defaulting to 256 if nothing is specified. /// </summary> /// <param name="data">The data to get a hash value (signature).</param> /// <param name="hashSize">The hash size to use (1, 256, 384 or 512)</param> /// <returns>A Byte[] the is a unique signature of the data passed.</returns> public static Byte[] SHACngHash(Byte[] data, Int32 hashSize) { Byte[] lHash = null; if (data != null) { if (hashSize == 512) { using (SHA512Cng sha = new SHA512Cng()) { lHash = sha.ComputeHash(data); } } else if (hashSize == 384) { using (SHA384Cng sha = new SHA384Cng()) { lHash = sha.ComputeHash(data); } } else if (hashSize == 256) { using (SHA256Cng sha = new SHA256Cng()) { lHash = sha.ComputeHash(data); } } else { using (SHA1Cng sha = new SHA1Cng()) { lHash = sha.ComputeHash(data); } } } return(lHash); }
public static byte[] ToSHA256Cng(this string s, Encoding encoding) { using (var sha256 = new SHA256Cng()) { return(sha256.ComputeHash(s.GetBytes(encoding))); } }
public void ByteBlockHashTest() { byte[] bytes = new byte[bufferSize]; Random r = new Random(); r.NextBytes(bytes); int offset = bufferSize / 2; int length = bufferSize - offset; DataBlock b1 = new DataBlock(bytes); DataBlock b2 = new DataBlock(b1, offset); byte[] h0; using (var h = new SHA256Cng()) { h.TransformFinalBlock(bytes, offset, length); h0 = h.Hash; } byte[] h1; using (var h = new SHA256Cng()) { h.TransformFinalBlock(b1, offset, length); h1 = h.Hash; } byte[] h2; using (var h = new SHA256Cng()) { h.TransformFinalBlock(b2, 0, b2.Length); h2 = h.Hash; } Assert.IsTrue(h0.SequenceEqual(h1)); Assert.IsTrue(h0.SequenceEqual(h2)); }
public static byte[] ToSHA256(this byte[] s) { using (var sha256 = new SHA256Cng()) { return(sha256.ComputeHash(s)); } }
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()); }
//https://tools.ietf.org/html/rfc5246#section-7.4.9 verify_data use PRF hash public static byte[] Hash(byte[] handshakeMessages) { using (var hash = new SHA256Cng()) { return(hash.ComputeHash(handshakeMessages)); } }
public byte[] CreateSha256HashBytes(string input) { using (var sha = new SHA256Cng()) { return(sha.ComputeHash(Encoding.UTF8.GetBytes(input))); } }
public static void ComputeHashes(string fileName, out string md5, out string sha1, out string sha256) { sha1 = sha256 = md5 = null; try { using (FileStream stream = File.OpenRead(fileName)) { using (var bufferedStream = new BufferedStream(stream, 1024 * 32)) { var md5Cng = new MD5Cng(); byte[] checksum = md5Cng.ComputeHash(bufferedStream); md5 = BitConverter.ToString(checksum).Replace("-", String.Empty); stream.Seek(0, SeekOrigin.Begin); bufferedStream.Seek(0, SeekOrigin.Begin); 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); var sha256Cng = new SHA256Cng(); checksum = sha256Cng.ComputeHash(bufferedStream); sha256 = BitConverter.ToString(checksum).Replace("-", String.Empty); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } }
public HashSalt GetHashValue(string input) { CustomSaltFunction saltFunc = new CustomSaltFunction(); string salt = saltFunc.GetSaltValue(32); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input + salt); SHA256 sha = new SHA256Cng(); // Hash function byte[] hash = sha.ComputeHash(bytes); // Generate hash in bytes // Store the hash value as string with uppercase letters. StringBuilder hashPassword = new StringBuilder(); // To store the hash value foreach (byte b in hash) { hashPassword.Append(b.ToString("X2")); } HashSalt hashSalt = new HashSalt { Hash = hashPassword.ToString(), Salt = salt }; return(hashSalt); }
// Private #region Methods private byte[] calculateHash(byte[] bytes, int offset) { using (var hasher = new SHA256Cng()) { hasher.TransformFinalBlock(bytes, offset + HashCalculationStartPosition, _clusterSizeBytes - HashCalculationStartPosition); return(hasher.Hash); } }
/// <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 Canary15DataSegment() { Canary15Trace.TraceDateTime(Canary15DataSegment.UtcNow, 0, "Canary15DataSegment().UtcNow."); Canary15Trace.TraceTimeSpan(Canary15DataSegment.defaultRefreshPeriod, 1, "Canary15DataSegment().defaultRefreshPeriod."); Canary15Trace.TraceTimeSpan(Canary15DataSegment.ReplicationDuration, 2, "Canary15DataSegment().ReplicationDuration."); Canary15DataSegment.topoConfigSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(false, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 119, ".cctor", "f:\\15.00.1497\\sources\\dev\\clients\\src\\common\\Canary15DataSegment.cs"); Canary15DataSegment.adClientAccessObjectId = Canary15DataSegment.topoConfigSession.GetClientAccessContainerId(); Canary15DataSegment.LoadClientAccessADObject(); byte[] array = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest().ObjectGuid.ToByteArray(); byte[] array2 = Canary15DataSegment.topoConfigSession.GetDatabasesContainerId().ObjectGuid.ToByteArray(); Canary15DataSegment.adObjectIdsBinary = new byte[array.Length + array2.Length]; array.CopyTo(Canary15DataSegment.adObjectIdsBinary, 0); array2.CopyTo(Canary15DataSegment.adObjectIdsBinary, array.Length); if (Canary15Trace.IsTraceEnabled(TraceType.DebugTrace)) { using (SHA256Cng sha256Cng = new SHA256Cng()) { byte[] bytes = sha256Cng.ComputeHash(Canary15DataSegment.adObjectIdsBinary); Canary15Trace.TraceDebug(2L, "adObjectIdsBinaryHash:{0}", new object[] { Canary15DataSegment.GetHexString(bytes) }); sha256Cng.Clear(); } } }
public static byte[] ComputeHash(byte[] userContextIdBinary, byte[] timestampBinary, string logOnUniqueKey, out long keyIndex, out int segmentIndex) { long ticks = BitConverter.ToInt64(timestampBinary, 0); byte[] array; if (Canary15DataManager.GetEntry(ticks, out array, out keyIndex, out segmentIndex)) { byte[] bytes = new UnicodeEncoding().GetBytes(logOnUniqueKey); int num = userContextIdBinary.Length + timestampBinary.Length + bytes.Length; num += array.Length; byte[] array2 = new byte[num]; int num2 = 0; userContextIdBinary.CopyTo(array2, num2); num2 += userContextIdBinary.Length; timestampBinary.CopyTo(array2, num2); num2 += timestampBinary.Length; bytes.CopyTo(array2, num2); num2 += bytes.Length; array.CopyTo(array2, num2); byte[] result; using (SHA256Cng sha256Cng = new SHA256Cng()) { result = sha256Cng.ComputeHash(array2); sha256Cng.Clear(); } return(result); } return(null); }
public static byte[] HashString(string input) { using (var hasher = new SHA256Cng()) { return(hasher.ComputeHash(Encoding.UTF8.GetBytes(input))); } }
/// <summary> /// Generates a hash based on the original value and salt of the dto /// </summary> /// <param name="dto"> DTO that contains original value and a salt </param> /// <returns> hashed value </returns> public string Hash(HashDTO dto) { // changes the hashDTO original to bytes string result = ""; try { byte[] convertedOriginal = Encoding.ASCII.GetBytes(dto.Original); // creates the hash in bytes based on the converted original using (SHA256Cng sha256 = new SHA256Cng()) { byte[] hash = sha256.ComputeHash(convertedOriginal); //converts back to string result += Convert.ToBase64String(hash); } return(result); } catch (EncoderFallbackException) { return(""); } catch (ObjectDisposedException) { return(""); } catch (ArgumentException) { return(""); } }
public string CreateSha256Hash(string input) { using (SHA256Cng sha = new SHA256Cng()) { UTF8Encoding encoding = new UTF8Encoding(); return(Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(input)))); } }
public static String ComputeSHA256(byte[] bytes) { using (var hashAlgorithmImpl = new SHA256Cng()) { var hashBytes = hashAlgorithmImpl.ComputeHash(bytes); return(String.Concat(hashBytes.Select(b => b.ToString("x2")))); } }
public byte[] HashString(string s) { using (var hasher = new SHA256Cng()) { byte[] bytes = Encoding.Unicode.GetBytes(s); hasher.TransformFinalBlock(bytes, 0, bytes.Length); return hasher.Hash; } }