private void AddFinished(OutgoingMessageBag outgoingMessages)
        {
            m_localHash.TransformFinalBlock(new byte[0], 0, 0);

            byte[] seed = m_localHash.Hash;
            m_localHash.Dispose();
            m_localHash = null;

            string label;

            if (SecurityParameters.Entity == ConnectionEnd.Server)
            {
                label = ServerFinishedLabel;
            }
            else
            {
                label = ClientFinshedLabel;
            }

            FinishedMessage finishedMessage = new FinishedMessage();

            finishedMessage.VerifyData =
                PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength);

            NetMQMessage outgoingMessage = finishedMessage.ToNetMQMessage();

            outgoingMessages.AddHandshakeMessage(outgoingMessage);
            m_lastSentMessage = HandshakeType.Finished;

            if (SecurityParameters.Entity == ConnectionEnd.Client)
            {
                HashRemote(outgoingMessage);
            }
        }
Beispiel #2
0
        private void AddFinished(OutgoingMessageBag outgoingMessages)
        {
            m_localHash.TransformFinalBlock(EmptyArray <byte> .Instance, 0, 0);

            byte[] seed = m_localHash.Hash;
            m_localHash.Dispose();
            m_localHash = null;

            var label = SecurityParameters.Entity == ConnectionEnd.Server ? ServerFinishedLabel : ClientFinshedLabel;

            var finishedMessage = new FinishedMessage
            {
                VerifyData = PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength)
            };

            NetMQMessage outgoingMessage = finishedMessage.ToNetMQMessage();

            outgoingMessages.AddHandshakeMessage(outgoingMessage);
            m_lastSentMessage = HandshakeType.Finished;

            if (SecurityParameters.Entity == ConnectionEnd.Client)
            {
                HashRemote(outgoingMessage);
            }
        }
Beispiel #3
0
        private void AddFinished(OutgoingMessageBag outgoingMessages)
        {
            m_localHash.TransformFinalBlock(EmptyArray <byte> .Instance, 0, 0);

            byte[] seed = m_localHash.Hash;
#if NET40
            m_localHash.Dispose();
#endif
            m_localHash = null;

            var label = SecurityParameters.Entity == ConnectionEnd.Server ? ServerFinishedLabel : ClientFinshedLabel;

            var finishedMessage = SubProtocolVersion.SequenceEqual(Constants.V3_3)?
                                  new V0_2.HandshakeMessages.FinishedMessage():
                                  new FinishedMessage();
            finishedMessage.VerifyData = PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength);
#if DEBUG
            Debug.WriteLine("[verify_data]:" + BitConverter.ToString(finishedMessage.VerifyData));
#endif
            NetMQMessage outgoingMessage = finishedMessage.ToNetMQMessage();
            outgoingMessages.AddHandshakeMessage(outgoingMessage);
            m_lastSentMessage = HandshakeType.Finished;

            if (SecurityParameters.Entity == ConnectionEnd.Client)
            {
                HashRemote(outgoingMessage);
            }
        }
Beispiel #4
0
        /// <exception cref="NetMQSecurityException">The Finished message must not be received while expecting a another message.</exception>
        /// <exception cref="NetMQSecurityException">The peer verification data must be valid.</exception>
        private void OnFinished(NetMQMessage incomingMessage, OutgoingMessageBag outgoingMessages)
        {
            if (
                (SecurityParameters.Entity == ConnectionEnd.Client &&
                 (!m_secureChannel.ChangeSuiteChangeArrived ||
                  m_lastReceivedMessage != HandshakeType.ServerHelloDone || m_lastSentMessage != HandshakeType.Finished)) ||
                (SecurityParameters.Entity == ConnectionEnd.Server &&
                 (!m_secureChannel.ChangeSuiteChangeArrived ||
                  m_lastReceivedMessage != HandshakeType.ClientKeyExchange || m_lastSentMessage != HandshakeType.ServerHelloDone)))
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeUnexpectedMessage, "Finished received when expecting another message");
            }

            if (SecurityParameters.Entity == ConnectionEnd.Server)
            {
                HashLocal(incomingMessage);
            }

            var finishedMessage = SubProtocolVersion.SequenceEqual(Constants.V3_3)?
                                  new V0_2.HandshakeMessages.FinishedMessage():
                                  new FinishedMessage();

            finishedMessage.SetFromNetMQMessage(incomingMessage);

            m_remoteHash.TransformFinalBlock(EmptyArray <byte> .Instance, 0, 0);

            byte[] seed = m_remoteHash.Hash;

#if NET40
            m_remoteHash.Dispose();
#else
            m_remoteHash.Clear();
#endif
            m_remoteHash = null;

            var label = SecurityParameters.Entity == ConnectionEnd.Client ? ServerFinishedLabel : ClientFinshedLabel;

            var verifyData = PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength);

#if DEBUG
            Debug.WriteLine("[verify_data]:" + BitConverter.ToString(verifyData));
#endif
            if (!verifyData.SequenceEqual(finishedMessage.VerifyData))
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeVerifyData, "peer verify data wrong");
            }

            if (SecurityParameters.Entity == ConnectionEnd.Server)
            {
                AddFinished(outgoingMessages);
#if DEBUG
                Debug.WriteLine("[finish]");
#endif
            }

            m_done = true;
        }
        private void OnFinished(NetMQMessage incomingMessage, OutgoingMessageBag outgoingMessages)
        {
            if (
                (SecurityParameters.Entity == ConnectionEnd.Client &&
                 (!m_secureChannel.ChangeSuiteChangeArrived ||
                  m_lastReceivedMessage != HandshakeType.ServerHelloDone || m_lastSentMessage != HandshakeType.Finished)) ||
                (SecurityParameters.Entity == ConnectionEnd.Server &&
                 (!m_secureChannel.ChangeSuiteChangeArrived ||
                  m_lastReceivedMessage != HandshakeType.ClientKeyExchange || m_lastSentMessage != HandshakeType.ServerHelloDone)))
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeUnexpectedMessage, "Finished received when expecting another message");
            }

            if (SecurityParameters.Entity == ConnectionEnd.Server)
            {
                HashLocal(incomingMessage);
            }

            FinishedMessage finishedMessage = new FinishedMessage();

            finishedMessage.SetFromNetMQMessage(incomingMessage);

            m_remoteHash.TransformFinalBlock(new byte[0], 0, 0);

            byte[] seed = m_remoteHash.Hash;
            m_remoteHash.Dispose();
            m_remoteHash = null;

            string label;

            if (SecurityParameters.Entity == ConnectionEnd.Client)
            {
                label = ServerFinishedLabel;
            }
            else
            {
                label = ClientFinshedLabel;
            }

            byte[] verifyData =
                PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength);

            if (!verifyData.SequenceEqual(finishedMessage.VerifyData))
            {
                throw  new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeVerifyData, "peer verify data wrong");
            }

            if (SecurityParameters.Entity == ConnectionEnd.Server)
            {
                AddFinished(outgoingMessages);
            }

            m_done = true;
        }
Beispiel #6
0
        public static string Decrypt(string encrypted, string key, string iv)
        {
            using (Aes aesAlg = Aes.Create())
            {
                SHA256 hash = SHA256.Create();
                aesAlg.Key = hash.ComputeHash(Encoding.UTF8.GetBytes(key));
                aesAlg.IV  = Convert.FromBase64String(iv);
                string decrypted = null;
                hash.Dispose();
                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encrypted)))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            decrypted = srDecrypt.ReadToEnd();
                        }
                    }
                }
                return(decrypted);
            }
        }
        /// <summary>
        /// Computes the SHA256 hash from a file content.
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static string ComputeSHA256HashFromFile(string fileName, bool base64)
        {
            FileStream stream = null;
            SHA256     hasher = null;

            try
            {
                stream = File.OpenRead(fileName);
                hasher = SHA256.Create();
                if (base64)
                {
                    return(Convert.ToBase64String(hasher.ComputeHash(stream)));
                }
                else
                {
                    return(BitConverter.ToString(hasher.ComputeHash(stream)).Replace("-", ""));
                }
            }
            finally
            {
                # region Freeing Resources

                if (hasher != null)
                {
                    hasher.Dispose();
                    hasher = null;
                }
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }

                # endregion
            }
Beispiel #8
0
        /// <summary>
        /// Checks if a file is a valid world file.
        /// </summary>
        /// <param name="path">The path of the file</param>
        /// <returns>Returns if the file is valid</returns>
        public static bool IsValidFile(string path)
        {
            if (File.Exists(path) && Path.GetExtension(path) == ".wld")
            {
                SHA256 sha256 = SHA256.Create();

                byte[] bytes    = Decompress(File.ReadAllBytes(path));
                byte[] hash     = sha256.ComputeHash(bytes.Take(bytes.Length - 32).ToArray());
                byte[] readHash = bytes.Skip(bytes.Length - 32).ToArray();

                // Compare hashes
                for (int i = 0; i < hash.Length; i++)
                {
                    if (hash[i] != readHash[i])
                    {
                        return(false);
                    }
                }

                sha256.Dispose();
                return(true);
            }

            return(false);
        }
Beispiel #9
0
 public void Init(string password = "")
 {
     if (IsSecure)
     {
         Message m    = new Message(Name, MessageType.Initialize);
         SHA256  sha  = SHA256.Create();
         byte[]  hash = sha.ComputeHash(Encoding.UTF8.GetBytes(password));
         sha.Dispose();
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < hash.Length; i++)
         {
             builder.Append(hash[i].ToString("x2"));
         }
         m.SetContent(builder.ToString());
         MessageHelpers.SetMessage(SStream, m);
     }
     else
     {
         Message m    = new Message(Name, MessageType.Initialize);
         SHA256  sha  = SHA256.Create();
         byte[]  hash = sha.ComputeHash(Encoding.UTF8.GetBytes(password));
         sha.Dispose();
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < hash.Length; i++)
         {
             builder.Append(hash[i].ToString("x2"));
         }
         m.SetContent(builder.ToString());
         MessageHelpers.SetMessage(Stream, m);
     }
 }
        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="content">要加密的内容,如果是一个对象必须要实现<see cref="SerializableAttribute"/></param>
        /// <returns></returns>
        public static string EncryptSHA256(object content)
        {
            if (StringUtil.IsNullOrEmpty(content))
            {
                return(string.Empty);
            }
            SHA256 managed = SHA256.Create();
            string result  = string.Empty;

            try
            {
                byte[] resultBytes = managed.ComputeHash(SerializeUtil.ToBinary(content));
                for (int i = 0; i < resultBytes.Length; i++)
                {
                    result += resultBytes.ElementAt(i).ToString("x2");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                managed.Dispose();
            }
            return(result);
        }
Beispiel #11
0
 public ActionResult Validate(string username, string password)
 {
     var _user = db.GetUserByName(username);
     if (_user != null)
     {
         SHA256 crypt = SHA256.Create();
         password = Encoding.ASCII.GetString(crypt.ComputeHash(Encoding.ASCII.GetBytes(password)));
         crypt.Dispose();
         if (_user.Phash == password)
         {
             HomeController.user = _user;
             ViewBag.User = _user;
             return Json(new {
                 status = true,
                 message = "Login Successfull!",
                 isAdmin = _user.IsAdmin == 0 ? false : true
             });
         }
         else
         {
             return Json(new {
                 status = false,
                 message = "Invalid Password!"
             });
         }
     }
     else
     {
         return Json(new {
             status = false,
             message = "Invalid Username!"
         });
     }
 }
Beispiel #12
0
        public MatchResult MatchPassword(string password)
        {
            if (!Encryted)
            {
                return(MatchResult.ChiefAdmin);
            }
            string sha256;

            using (SHA256 sha = SHA256.Create())
            {
                sha256 = Encoding.UTF8.GetString(sha.ComputeHash(Encoding.UTF8.GetBytes(password)));
                sha.Dispose();
            }
            if (chiefPassword == sha256)
            {
                return(MatchResult.ChiefAdmin);
            }
            else
            {
                foreach (DailyAdmin it in TodaysAdmins)
                {
                    if (it.MatchPassword(password))
                    {
                        return(new MatchResult(it));
                    }
                }
                return(MatchResult.Locked);
            }
        }
Beispiel #13
0
 public ActionResult Register(string username, string password)
 {
     User user = db.GetUserByName(username);
     if(user != null)
     {
         return Json(new {
             status = false,
             message = "User already exists"
         });
     }
     else
     {
         SHA256 crypt = SHA256.Create();
         byte[] hash = crypt.ComputeHash(Encoding.ASCII.GetBytes(password));
         string phash = Encoding.ASCII.GetString(hash);
         crypt.Dispose();
         user = new User {
             IsAdmin = 0,
             Username = username,
             Phash = phash
         };
         bool isSuccessful = db.AddUser(user);
         return Json(new {
             status = isSuccessful,
             message = "There was a problem registering"
         });
     }
 }
Beispiel #14
0
        public static string GenerateMerkleRoot(string Coinb1, string Coinb2, string ExtraNonce1, string ExtraNonce2, string[] MerkleNumbers)
        {
            string Coinbase = Coinb1 + ExtraNonce1 + ExtraNonce2 + Coinb2;

            byte[] Coinbasebytes = Utilities.HexStringToByteArray(Coinbase);

            SHA256 mySHA256 = SHA256.Create();

            mySHA256.Initialize();
            byte[] hashValue, hashValue2;


            hashValue  = mySHA256.ComputeHash(Coinbasebytes);
            hashValue2 = mySHA256.ComputeHash(hashValue);


            foreach (string s in MerkleNumbers)
            {
                hashValue  = mySHA256.ComputeHash(Utilities.HexStringToByteArray(Utilities.ByteArrayToHexString(hashValue2) + s));
                hashValue2 = mySHA256.ComputeHash(hashValue);
            }

            string MerkleRoot = Utilities.ByteArrayToHexString(Utilities.ReverseByteArrayByFours(hashValue2));

            mySHA256.Dispose();

            return(MerkleRoot);
        }
Beispiel #15
0
 public void Dispose()
 {
     _sha256.Dispose();
     _sha256 = null;
     _randomNumberGenerator.Dispose();
     _randomNumberGenerator = null;
 }
Beispiel #16
0
        private bool disposedValue = false; // To detect redundant calls

        protected override void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    try
                    {
                        topStream.Dispose(); // This call will flush and dispose all chained streams.
                    }
                    catch (CryptographicException)
                    {
                        topStream.Dispose();
                        throw;
                    }
                    finally
                    {
                        transform.Dispose();
                        csp.Dispose();
                        sha.Dispose();
                    }
                }

                disposedValue = true;
            }
        }
Beispiel #17
0
 public void Dispose()
 {
     if (_sha256 != null)
     {
         _sha256.Dispose();
         _sha256 = null;
     }
 }
Beispiel #18
0
    public static byte[] ComputeSha256(string data)
    {
        SHA256 sha256Hash = SHA256.Create();

        byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
        sha256Hash.Dispose();
        return(bytes);
    }
Beispiel #19
0
 public void Dispose()
 {
     if (shaM != null)
     {
         shaM.Dispose();
         shaM = null;
     }
 }
Beispiel #20
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         ((IDisposable)_awsHttpConnection)?.Dispose();
         _sha256?.Dispose();
     }
 }
 protected override void Dispose(bool disposing)
 {
     if (disposing && _implementation != null)
     {
         _implementation.Dispose();
         _implementation = null;
     }
     base.Dispose(disposing);
 }
Beispiel #22
0
        private string GenerateDeterministicId()
        {
            bundleHash.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
            byte[] manifestHash = bundleHash.Hash;
            bundleHash.Dispose();
            bundleHash = null;

            return(Convert.ToBase64String(manifestHash).Substring(BundleIdLength).Replace('/', '_'));
        }
        public static String GenerateSHA256String(String inputString)
        {
            SHA256 sha256 = SHA256Managed.Create();

            Byte[] bytes = Encoding.UTF8.GetBytes(inputString);
            Byte[] hash  = sha256.ComputeHash(bytes);
            sha256.Dispose();
            return(GetStringFromHash(hash));
        }
Beispiel #24
0
        public override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _hasher.Dispose();
            }

            base.Dispose(disposing);
        }
Beispiel #25
0
        // функция для хэширования массива байт заданным алгоритмом, на выходе 16-ричная строка
        // аргументы: входные байты сообщения, алгоритм хэширования
        public static string HeshAlg(Byte[] arrayByte_in, string selectedAlgHesh)
        {
            byte[] arrayByte_out = new byte[0]; // Выходная последовательность байт после хеширования
            string heshString    = "";          // Хеш строка (16 ричный вид)

            try
            {
                switch (selectedAlgHesh) // Получение хеша определенным алгоритмом
                {
                case "MD5":
                    MD5 md5 = MD5.Create();
                    arrayByte_out = md5.ComputeHash(arrayByte_in);
                    md5.Dispose();
                    break;

                case "RIPEMD160":
                    RIPEMD160 ripemd160 = RIPEMD160.Create();
                    arrayByte_out = ripemd160.ComputeHash(arrayByte_in);
                    ripemd160.Dispose();
                    break;

                case "SHA1":
                    SHA1 sha1 = SHA1.Create();
                    arrayByte_out = sha1.ComputeHash(arrayByte_in);
                    sha1.Dispose();
                    break;

                case "SHA256":
                    SHA256 sha256 = SHA256.Create();
                    arrayByte_out = sha256.ComputeHash(arrayByte_in);
                    sha256.Dispose();
                    break;

                case "SHA384":
                    SHA384 sha384 = SHA384.Create();
                    arrayByte_out = sha384.ComputeHash(arrayByte_in);
                    sha384.Dispose();
                    break;

                case "SHA512":
                    SHA512 sha512 = SHA512.Create();
                    arrayByte_out = sha512.ComputeHash(arrayByte_in);
                    sha512.Dispose();
                    break;

                default: break;
                }
                heshString = BitConverter.ToString(arrayByte_out).Replace("-", "");
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "НЕПРЕДВИДЕННАЯ ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(heshString);
        }
Beispiel #26
0
        public static string GetSHA256(string input)
        {
            SHA256 sha256 = SHA256.Create();

            byte[] data = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));

            sha256.Dispose();

            return(BytesToHash(data));
        }
        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            if (sha != null)
            {
                sha.Dispose();
                sha = null;
            }

            GC.SuppressFinalize(this);
        }
Beispiel #28
0
        /// <summary>
        /// Creates a token and sends it to the users email if user exists.
        /// </summary>
        /// <param name="username"></param>
        /// <returns>True if token is created and email sent</returns>
        public bool CreateResetToken(string username)
        {
            //Checks if username exists
            if (dal.GetStudent(username) != null)
            {
                //make random string

                string token      = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
                SHA256 sha        = SHA256.Create();
                byte[] hashedbyte = sha.ComputeHash(Encoding.UTF8.GetBytes(token));

                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < hashedbyte.Length; i++)
                {
                    sb.Append(hashedbyte[i].ToString("x2"));
                }
                string hashed = sb.ToString();

                if (dal.SetToken(username, hashed))
                {
                    sha.Dispose();
                    //send email with the token
                    try
                    {
                        Email email = new Email();

                        string mail    = username + "@zbc.dk";
                        string message = "Brug dette link til at reset dit password: <http://skprgopg.zbc.dk/Reset.aspx?tkn=" + token + ">";
                        email.SendEmail(mail, "Reset Password, SKP PDB", message);

                        return(true);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        return(false);
                    }
                }
                sha.Dispose();
            }
            return(false);
        }
Beispiel #29
0
        public static byte[] GenerateNextUUID(string salt)
        {
            SHA256 sha256 = SHA256.Create();

            DateTime timestamp            = DateTime.Now;
            string   guidGeneratorPayload = timestamp.ToString("dd-MM-yyyy%THHmmss%.FFFFFFK") + salt;

            byte[] rawPayload = Encoding.ASCII.GetBytes(guidGeneratorPayload);
            byte[] result     = sha256.ComputeHash(rawPayload);
            sha256.Dispose();
            return(result);
        }
Beispiel #30
0
        private bool disposedValue = false; // To detect redundant calls

        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _hasher.Dispose();
                }

                disposedValue = true;
            }
        }