Exemplo n.º 1
0
        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()))));
            }
        }
Exemplo n.º 4
0
        /// <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;
                        }
        }
Exemplo n.º 5
0
        /// <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));
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
 public void ComputeHash(String filePath)
 {
     using (var md5 = SHA256Cng.Create())
     {
         this.md5String = md5.ComputeHash(File.ReadAllBytes(filePath));
     }
 }
Exemplo n.º 8
0
        /// <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);
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 11
0
        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();
                }
            }
        }
Exemplo n.º 12
0
 public static string Hash(byte[] data)
 {
     using (SHA256Cng sha256 = new SHA256Cng())
     {
         return(Convert.ToBase64String(sha256.ComputeHash(data)));
     }
 }
Exemplo n.º 13
0
        /// <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);
        }
Exemplo n.º 14
0
 public static byte[] ToSHA256Cng(this string s, Encoding encoding)
 {
     using (var sha256 = new SHA256Cng())
     {
         return(sha256.ComputeHash(s.GetBytes(encoding)));
     }
 }
Exemplo n.º 15
0
        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));
        }
Exemplo n.º 16
0
 public static byte[] ToSHA256(this byte[] s)
 {
     using (var sha256 = new SHA256Cng())
     {
         return(sha256.ComputeHash(s));
     }
 }
Exemplo n.º 17
0
        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());
        }
Exemplo n.º 18
0
 //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)));
     }
 }
Exemplo n.º 20
0
        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) { }
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        // 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);
            }
        }
Exemplo n.º 23
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))));
     }
 }
Exemplo n.º 24
0
 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();
         }
     }
 }
Exemplo n.º 25
0
        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);
        }
Exemplo n.º 26
0
 public static byte[] HashString(string input)
 {
     using (var hasher = new SHA256Cng())
     {
         return(hasher.ComputeHash(Encoding.UTF8.GetBytes(input)));
     }
 }
Exemplo n.º 27
0
        /// <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("");
            }
        }
Exemplo n.º 28
0
 public string CreateSha256Hash(string input)
 {
     using (SHA256Cng sha = new SHA256Cng())
     {
         UTF8Encoding encoding = new UTF8Encoding();
         return(Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(input))));
     }
 }
Exemplo n.º 29
0
 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"))));
     }
 }
Exemplo n.º 30
0
 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;
     }
 }