public static bool IsMd5Valid(string messageBody, string expectedMd5)
        {
            if (messageBody == null)
            {
                throw new ArgumentNullException("messageBody");
            }

            // Define the hash algorithm to use
            byte[] hashBytes;
            using (var hash = new MD5Cng())
            {
                hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(messageBody));
                hash.Clear();
            }

            var messageBodyMd5 = hashBytes.ToHex();
            if (messageBodyMd5 == expectedMd5)
            {
                return true;
            }

            return false;
        }
Example #2
0
        /// <summary>
        /// MD5Cng
        /// 此类型的任何公共static成员都是线程安全的。但不保证所有实例成员都是线程安全的
        /// </summary>
        private static string Encrypt_static(string clearText, Encoding encode)
        {
            MD5 md5 = null;
            try
            {
                byte[] originalBytes = encode.GetBytes(clearText); //Encoding.UTF8.GetBytes(clearText);

                md5 = new MD5Cng();
                byte[] data = md5.ComputeHash(originalBytes);

                StringBuilder builder = new StringBuilder();
                foreach (var item in data)
                {
                    builder.Append(item.ToString("X2"));
                }

                return builder.ToString();
            }
            catch (ArgumentNullException) { return clearText; }
            catch (EncoderFallbackException) { return clearText; }
            //catch (TargetInvocationException) { return clearText; }
            catch (ObjectDisposedException) { return clearText; }
            catch (InvalidOperationException) { return clearText; }

            catch { return clearText; }
            finally
            {
                if (md5 != null)
                {
                    md5.Clear();
                    md5.Dispose();
                }

                md5 = null;
            }
        }