예제 #1
0
        public static string Sha256_2(string bla)
        {
            byte[] ba = System.Text.Encoding.UTF8.GetBytes(bla);

            using (System.Security.Cryptography.SHA256CryptoServiceProvider sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
            {
                ba = sha256.ComputeHash(ba);
                ba = sha256.ComputeHash(ba);
            } // End Using sha256

            return(System.BitConverter.ToString(ba).Replace("-", "").ToLowerInvariant());
        } // End Function Sha256_2
예제 #2
0
        public static string Sha256(string path)
        {
            string strResult   = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.SHA256CryptoServiceProvider sha256Hasher = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            try
            {
                oFileStream     = new System.IO.FileStream(path, System.IO.FileMode.Open);
                arrbytHashValue = sha256Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult   = strHashData;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                oFileStream.Close();
            }

            return(strResult);
        }
예제 #3
0
        /// <summary>
        /// SHA-256
        /// </summary>
        /// <param name="str"></param>
        public static string SHA_256(string str)
        {
            System.Security.Cryptography.SHA256CryptoServiceProvider sha256Csp = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash  = sha256Csp.ComputeHash(bytValue);
            sha256Csp.Clear();
            string hashStr = "";

            for (int counter = 0; counter < bytHash.Count(); counter++)
            {
                long i       = bytHash[counter] / 16;
                var  tempStr = "";
                if (i > 9)
                {
                    tempStr = ((char)(i - 10 + 0x41)).ToString();
                }
                else
                {
                    tempStr = ((char)(i + 0x30)).ToString();
                }
                i = bytHash[counter] % 16;
                if (i > 9)
                {
                    tempStr += ((char)(i - 10 + 0x41)).ToString();
                }
                else
                {
                    tempStr += ((char)(i + 0x30)).ToString();
                }
                hashStr += tempStr;
            }
            return(hashStr);
        }
예제 #4
0
파일: Types.cs 프로젝트: nRafinia/GrpcCache
        private static long GetInt64HashCode(string strText)
        {
            long hashCode = 0;

            if (string.IsNullOrEmpty(strText))
            {
                return(hashCode);
            }

            //Unicode Encode Covering all character set
            var byteContents = Encoding.Unicode.GetBytes(strText);

            System.Security.Cryptography.SHA256 hash =
                new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var hashText = hash.ComputeHash(byteContents);
            //32Byte hashText separate
            //hashCodeStart = 0~7  8Byte
            //hashCodeMedium = 8~23  8Byte
            //hashCodeEnd = 24~31  8Byte
            //and Fold
            var hashCodeStart  = BitConverter.ToInt64(hashText, 0);
            var hashCodeMedium = BitConverter.ToInt64(hashText, 8);
            var hashCodeEnd    = BitConverter.ToInt64(hashText, 24);

            hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
            return(hashCode);
        }
예제 #5
0
        public static string aesDecryptBase64(string SourceStr, ulong Key)
        {
            string decrypt = "";

            try
            {
                var    aes    = new System.Security.Cryptography.AesCryptoServiceProvider();
                var    md5    = new System.Security.Cryptography.MD5CryptoServiceProvider();
                var    sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] key    = sha256.ComputeHash(BitConverter.GetBytes(Key));
                byte[] iv     = md5.ComputeHash(BitConverter.GetBytes(Key));
                aes.Key = key;
                aes.IV  = iv;

                byte[] dataByteArray = Convert.FromBase64String(SourceStr);
                using (var ms = new System.IO.MemoryStream())
                {
                    using (var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(dataByteArray, 0, dataByteArray.Length);
                        cs.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception e)
            {
            }
            return(decrypt);
        }
예제 #6
0
        public byte[] Hash(HashAlgorithmName algName, byte[] inputDataBytes)
        {
            switch (algName)
            {
            case HashAlgorithmName.SHA256:
            {
                using (System.Security.Cryptography.SHA256CryptoServiceProvider hasher = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                {
                    return(hasher.ComputeHash(inputDataBytes));
                }
            }

            case HashAlgorithmName.SHA512:
            {
                using (System.Security.Cryptography.SHA512CryptoServiceProvider hasher = new System.Security.Cryptography.SHA512CryptoServiceProvider())
                {
                    return(hasher.ComputeHash(inputDataBytes));
                }
            }

            case HashAlgorithmName.MD5:
            default:
            {
                using (System.Security.Cryptography.MD5CryptoServiceProvider hasher = new System.Security.Cryptography.MD5CryptoServiceProvider())         // hash size 128
                {
                    return(hasher.ComputeHash(inputDataBytes));
                }
            }
            }
        }
예제 #7
0
        /// <summary>
        /// 使用UTF-8进行SHA256签名
        /// 加盐&key={sign_key},若sign_key.IsNullOrWhiteSpace()则不加盐
        /// </summary>
        /// <param name="content">签名原文</param>
        /// <param name="sign_key">签名密钥 为空则不加盐</param>
        /// <param name="format">大小写格式化 默认:FromatSign.UPPER</param>
        /// <returns></returns>
        public static string Sign(string content, string sign_key, FromatSign format = FromatSign.UPPER)
        {
            if (content.IsNullOrWhiteSpace())
            {
                return(string.Empty);
            }

            if (!sign_key.IsNullOrWhiteSpace())
            {
                content = $"{content}&key={sign_key}";
            }

            var _format = format == FromatSign.UPPER
                        ? "X2"              /*大写*/
                        : "x2";             /*小写*/

            var result = new StringBuilder();

            using (var provider = new System.Security.Cryptography.SHA256CryptoServiceProvider())
            {
                var byte_sign = provider.ComputeHash(Encoding.UTF8.GetBytes(content));

                // 把二进制转化为十六进制
                for (int i = 0; i < byte_sign.Length; i++)
                {
                    result.Append(byte_sign[i].ToString(format: _format));
                }
            }

            return(result.ToString());
        }
        private Int64 CalculateTypeIdHash()
        {
            string strText = Name;

            if (Properties.Count > 0)
            {
                var keys = Properties.Keys.ToList();
                keys.Sort();
                strText += keys.Aggregate((i, j) => i + j);
            }

            Int64 hashCode = 0;

            if (!string.IsNullOrEmpty(strText))
            {
                //Unicode Encode Covering all characterset
                byte[] byteContents = Encoding.Unicode.GetBytes(strText);
                System.Security.Cryptography.SHA256 hash =
                    new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText = hash.ComputeHash(byteContents);
                //32Byte hashText separate
                //hashCodeStart = 0~7  8Byte
                Int64 hashCodeStart = BitConverter.ToInt64(hashText, 0);
                //hashCodeMedium = 8~23  8Byte
                Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);
                //hashCodeEnd = 24~31  8Byte
                Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24);
                //and Fold
                hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
            }
            return(hashCode);
        }
예제 #9
0
        public Boolean ValidaSelloDigital(string selloDigital, string cert, string cadena, out Boolean MD5, out Boolean SHA256, out String Error)
        {
            Boolean Resultado = false;

            MD5    = false;
            SHA256 = false;
            Error  = null;
            try
            {
                Byte[] sello_byte = Convert.FromBase64String(selloDigital);
                Byte[] cert_byte  = Convert.FromBase64String(cert);
                System.Security.Cryptography.X509Certificates.X509Certificate2 certificado = new System.Security.Cryptography.X509Certificates.X509Certificate2(cert_byte);
                String spk = certificado.PublicKey.Key.ToXmlString(false);
                System.Security.Cryptography.AsymmetricAlgorithm pk = System.Security.Cryptography.AsymmetricAlgorithm.Create();
                pk.FromXmlString(spk);
                System.Security.Cryptography.RSACryptoServiceProvider rsa = (System.Security.Cryptography.RSACryptoServiceProvider)pk;
                rsa.PersistKeyInCsp = false;
                Byte[] cadena_byte = System.Text.Encoding.UTF8.GetBytes(cadena);
                System.Security.Cryptography.SHA256CryptoServiceProvider x = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                Byte[] data = x.ComputeHash(cadena_byte);
                System.Security.Cryptography.MD5CryptoServiceProvider x2 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                Byte[] data2 = x2.ComputeHash(cadena_byte);
                MD5    = rsa.VerifyHash(data2, System.Security.Cryptography.CryptoConfig.MapNameToOID("MD5"), sello_byte);
                SHA256 = rsa.VerifyHash(data, System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"), sello_byte);
                //if (MD5 || SHA1)
                Resultado = true;
            }
            catch (Exception ex)
            {
                Error = "Error al desencriptar el sello digital Error:" + ex.Message;
            }
            return(Resultado);
        }
예제 #10
0
파일: Program.cs 프로젝트: kkrnt/Brute
 public string SHA256(string str)
 {
     var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
     var bs = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
     sha256.Clear();
     return bs.Aggregate("", (current, b) => current + (b.ToString("x2")));
 }
예제 #11
0
        private Boolean GenerarSelloSHA256(String CadenaOriginal, Certificado cert, out String Resultado, out List <String> ErrorSellado)
        {
            Boolean Devolver = false;

            Resultado = String.Empty;
            String SelloDigital  = String.Empty;
            String ErrorSellador = String.Empty;

            ErrorSellado = new List <string>();
            System.Security.Cryptography.SHA256CryptoServiceProvider EncriptaSHA256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            Byte[] CadenaOriginalEnBytes = EncriptaSHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(CadenaOriginal));

            System.Security.Cryptography.RSACryptoServiceProvider RSA = null;
            byte[] keyblob = cert.bKey;
            if (keyblob != null)
            {
                if (SSLKey.opensslkey.DecodeEncryptedPrivateKeyInfo(keyblob, cert.ContrasenaSegura, out RSA, out ErrorSellador))
                {
                    //RSA.FromXmlString(LLavePrivada);
                    System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                    RSAFormatter.SetHashAlgorithm("SHA256");
                    CadenaOriginalEnBytes = RSAFormatter.CreateSignature(CadenaOriginalEnBytes);
                    SelloDigital          = Convert.ToBase64String(CadenaOriginalEnBytes);
                    Resultado             = SelloDigital;
                    Devolver = true;
                }
                else
                {
                    ErrorSellado.Add(ErrorSellador);
                }
            }

            return(Devolver);
        }
예제 #12
0
        public static string Sha256Encrypt(string plainTxt)
        {
            var bytes        = System.Text.Encoding.Default.GetBytes(plainTxt);
            var sha256       = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var encryptBytes = sha256.ComputeHash(bytes);

            return(Convert.ToBase64String(encryptBytes));
        }
예제 #13
0
 /// <summary>
 /// Calculates SHA256 hash for a byte[] and sets as ETag. Ensures Cache-Control: private header is added.
 /// </summary>
 /// <param name="response"></param>
 /// <param name="content">If byte[] is null or empty, will only add cache-control</param>
 public static void AddCacheHeader(this HttpResponse response, byte[] content)
 {
     if (content == null || content.Length <= 0)
     {
         return;
     }
     using var sha1 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
     response.Headers.Add("ETag", string.Concat(sha1.ComputeHash(content).Select(x => x.ToString("X2"))));
 }
예제 #14
0
 private static string GenerateFileHash(string hashType, string pathToFile)
 {
     try
     {
         using (var stream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read, FileShare.None))
         {
             if (hashType == "md5")
             {
                 using (var hash = new System.Security.Cryptography.MD5CryptoServiceProvider())
                 {
                     var data = hash.ComputeHash(stream);
                     return(BitConverter.ToString(data).Replace("-", "").ToLower());
                 }
             }
             else if (hashType == "sha1")
             {
                 using (var hash = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                 {
                     var data = hash.ComputeHash(stream);
                     return(BitConverter.ToString(data).Replace("-", "").ToLower());
                 }
             }
             else if (hashType == "sha256")
             {
                 using (var hash = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                 {
                     var data = hash.ComputeHash(stream);
                     return(BitConverter.ToString(data).Replace("-", "").ToLower());
                 }
             }
             else if (hashType == "sha384")
             {
                 using (var hash = new System.Security.Cryptography.SHA384CryptoServiceProvider())
                 {
                     var data = hash.ComputeHash(stream);
                     return(BitConverter.ToString(data).Replace("-", "").ToLower());
                 }
             }
             else if (hashType == "sha512")
             {
                 using (var hash = new System.Security.Cryptography.SHA512CryptoServiceProvider())
                 {
                     var data = hash.ComputeHash(stream);
                     return(BitConverter.ToString(data).Replace("-", "").ToLower());
                 }
             }
             else
             {
                 throw new Exception("Unsupported hashType: " + hashType);
             }
         }
     }
     catch (Exception e)
     {
         return("Error: " + e.Message);
     }
 }
예제 #15
0
        public virtual Dictionary <ProfileAttributeType, String> GetAttributes(String identifyer)
        {
            Dictionary <ProfileAttributeType, String> attributes = new Dictionary <ProfileAttributeType, String>();

            System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            Byte[] inputBytes;
            Byte[] outputBytes;
            string outputString;
            string data = "";

            switch (Format)
            {
            case TimestampFormat.aaaammgghhmmss:
                data = DateTime.Now.ToString("yyyyMMddHHmm");
                break;
            }

            // Calcolo della chiave di hash

            inputBytes   = ASCIIEncoding.Default.GetBytes(identifyer + data + SecretKey);
            outputBytes  = sha256.ComputeHash(inputBytes);
            outputString = Convert(outputBytes);
            String url = RemoteApiUrl;

            if (RemoteApiUrl.Contains("{0}") && RemoteApiUrl.Contains("{1}"))
            {
                try
                {
                    WebClient webClient = new WebClient();
                    string    json      = webClient.DownloadString(String.Format(RemoteApiUrl, identifyer, outputString));
                    if (!String.IsNullOrEmpty(json) && json != "{\"result\":\"\"}")
                    {
                        var deserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        var result       = (Dictionary <String, object>)deserializer.DeserializeObject(json);
                        if (result != null && Attributes != null && Attributes.Where(a => a.Deleted == BaseStatusDeleted.None).Any())
                        {
                            foreach (Dictionary <String, object> jStruct in result.Values.Where(v => v != null))
                            {
                                foreach (String key in jStruct.Keys)
                                {
                                    JsonAttribute attribute = Attributes.Where(a => a.Deleted == BaseStatusDeleted.None && a.Name == key.ToLower()).FirstOrDefault();
                                    if (attribute != null)
                                    {
                                        attributes.Add(attribute.Type, jStruct[key].ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (ArgumentException e)
                {
                }
            }
            return(attributes);
        }
예제 #16
0
        public static string GetHash(string input)
        {
            System.Security.Cryptography.HashAlgorithm hashAlgorithm = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);

            byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);

            return(Convert.ToBase64String(byteHash));
        }
예제 #17
0
 private static Int64 ComputeTaskHash(string data)
 {
     if (String.IsNullOrEmpty(data))
     {
         return(0L);
     }
     byte[] rawHash;
     using (var sha = new System.Security.Cryptography.SHA256CryptoServiceProvider())
         rawHash = sha.ComputeHash(Encoding.Unicode.GetBytes(data));
     return(BitConverter.ToInt64(rawHash, 0) ^ BitConverter.ToInt64(rawHash, 8) ^ BitConverter.ToInt64(rawHash, 24));
 }
예제 #18
0
 public static string Encrypt(string text)
 {
     if (string.IsNullOrWhiteSpace(text))
     {
         return("");
     }
     byte[] byteArray = Encoding.UTF8.GetBytes(text);
     using (System.Security.Cryptography.SHA256CryptoServiceProvider shaCSP = new System.Security.Cryptography.SHA256CryptoServiceProvider())
     {
         return(BitConverter.ToString(shaCSP.ComputeHash(byteArray)).Replace("-", ""));
     }
 }
예제 #19
0
        /// <summary>
        /// It returns the entered data as SHA256 Hash.
        /// </summary>
        /// <param name="content">Text in string value to be converted to SHA256.</param>
        /// <returns>SHA256 output will be returned.</returns>
        public string Create(string content)
        {
            System.Security.Cryptography.SHA256 ee = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            ee.ComputeHash(UTF8Encoding.UTF8.GetBytes(content));
            byte[]        result = ee.Hash;
            StringBuilder sb     = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x2"));
            }
            return(sb.ToString());
        }
예제 #20
0
        /// <summary>
        /// It is used to calculate the SHA256 Hash data of the file in the specified location.
        /// </summary>
        /// <param name="file">The location of the file in string value.</param>
        /// <returns>SHA256 output of the file will be returned.</returns>
        public string FileFingerprint(string file)
        {
            System.Security.Cryptography.SHA256 ee = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            ee.ComputeHash(File.ReadAllBytes(file));
            byte[]        result = ee.Hash;
            StringBuilder sb     = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x2"));
            }
            return(sb.ToString());
        }
예제 #21
0
        internal static bool CheckProcessSignature()
        {
            if (!IsAttached)
            {
                return(false);
            }

            // Create new instance of the SHA256 service provider
            var shaCrypt   = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var stringHash = new StringBuilder();

            try
            {
                // Read the executable data for the selected process
                var exePath  = MemorySharp.Modules.MainModule.Path;
                var exeBytes = File.ReadAllBytes(exePath);

                // Compute module hash
                var moduleHash = shaCrypt.ComputeHash(exeBytes);

                // Convert hash to string

                foreach (var hashByte in moduleHash)
                {
                    stringHash.Append(hashByte.ToString("X2"));
                }
            }
            catch
            {
                var proceed = MessageBox.Show("An error occurred while validating the selected process:\n{ex.Message}\n\nWould you like to continue anyway?", "Process verification error",
                                              MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                return(proceed == MessageBoxResult.Yes);
            }


            // Compare against known hashes
            if (!FFX_Hashes.Contains(stringHash.ToString()))
            {
                // No matching hash
                Console.WriteLine("Hash: " + stringHash);
                var proceed = MessageBox.Show("The selected process does not appear to match any known compatible processes.\n\n" +
                                              "Farplane will attempt to calculate offsets automatically, but proceeding " +
                                              "may cause errors or cause the game to crash. Now is a good time to make a " +
                                              "backup of your saved games!\n\n" +
                                              "Are you sure you wish to continue?", "Unknown process error",
                                              MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                return(proceed == MessageBoxResult.Yes);
            }

            return(true);
        }
예제 #22
0
        public static string GetHash(string url)
        {
            byte[] input = Encoding.ASCII.GetBytes(url);
            var    sha   = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] hash   = sha.ComputeHash(input);
            string result = "";

            for (int i = 0; i < Math.Min(hash.Length, 15); i++)
            {
                result = result + string.Format("{0:X2}", hash[i]);
            }
            return(result);
        }
예제 #23
0
        public static string RetornarHashSHA256(string valor)
        {
            string strSenha = Helpers.Configuracoes.Recuperar("SIAC_SECRET") + valor;

            System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            System.Text.StringBuilder           sb  = new StringBuilder();
            sha.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(strSenha));
            byte[] result = sha.Hash;
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x2"));
            }
            return(sb.ToString());
        }
예제 #24
0
파일: SHA.cs 프로젝트: hyfree/UpYunLibrary
        public static string Hash256Encrypt(string password)
        {
            var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            byte[] hashedDataBytes;
            hashedDataBytes = sha256.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(password));
            StringBuilder tmp = new StringBuilder();

            foreach (byte i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }
            return(tmp.ToString());
        }
        public ActionResult CreateAccPwd(int?id)
        {
            var data = rep.Find(id.Value);

            data.帳號 = "qweerty0322";
            var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); //建立一個SHA256

            byte[] source = System.Text.Encoding.Default.GetBytes("123456");             //將字串轉為Byte[]
            byte[] crypto = sha256.ComputeHash(source);                                  //進行SHA256加密
            string result = Convert.ToBase64String(crypto);                              //把加密後的字串從Byte[]轉為字串

            data.密碼 = result;
            rep.UnitOfWork.Commit();
            return(RedirectToAction("Index", "Home"));
        }
예제 #26
0
        /// <summary>
        /// 获取字符串的唯一Hash值(比MD5快)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long GetLongHashCode(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(0);
            }
            byte[] byteContents = Encoding.UTF8.GetBytes(str);
            System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] hashText       = hash.ComputeHash(byteContents);
            long   hashCodeStart  = BitConverter.ToInt64(hashText, 0);
            long   hashCodeMedium = BitConverter.ToInt64(hashText, 8);
            long   hashCodeEnd    = BitConverter.ToInt64(hashText, 24);

            return(hashCodeStart ^ hashCodeMedium ^ hashCodeEnd);
        }
        public static string Generate(string name)
        {
            var bytes  = Encoding.UTF8.GetBytes(name);
            var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var hash   = sha256.ComputeHash(bytes);

            var sb = new StringBuilder();

            for (var i = 1; i < 11; i++)
            {
                var n = BitEncoding.ByteToB64(hash[i] & 63);
                sb.Append(n);
            }
            return(sb.ToString());
        }
예제 #28
0
        internal static ushort GetInt16HashCode(string source)
        {
            ushort hashCode = 0;

            if (!string.IsNullOrEmpty(source))
            {
                byte[] byteContents = Encoding.Unicode.GetBytes(source);
                System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText       = hash.ComputeHash(byteContents);
                ushort hashCodeStart  = BitConverter.ToUInt16(hashText, 0);
                ushort hashCodeMedium = BitConverter.ToUInt16(hashText, 8);
                ushort hashCodeEnd    = BitConverter.ToUInt16(hashText, 24);
                hashCode = (ushort)(hashCodeStart ^ hashCodeMedium ^ hashCodeEnd);
            }
            return(hashCode);
        }
예제 #29
0
        private string GetAppHash()
        {
            System.Security.Cryptography.SHA256CryptoServiceProvider sha2 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            FileStream stream = new FileStream(Process.GetCurrentProcess().MainModule.FileName, FileMode.Open, FileAccess.Read);

            sha2.ComputeHash(stream);

            stream.Close();

            StringBuilder sb = new StringBuilder();

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

            return(sb.ToString().ToUpperInvariant());
        }
예제 #30
0
        //- For sorting
        public static long TextToNumber(string text)
        {
            Int64 hashCode = 0;

            if (!string.IsNullOrEmpty(text))
            {
                //Unicode Encode Covering all characterset
                byte[] byteContents = Encoding.Unicode.GetBytes(text);
                System.Security.Cryptography.SHA256 hash =
                    new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] hashText       = hash.ComputeHash(byteContents);
                Int64  hashCodeStart  = BitConverter.ToInt64(hashText, 0);
                Int64  hashCodeMedium = BitConverter.ToInt64(hashText, 8);
                Int64  hashCodeEnd    = BitConverter.ToInt64(hashText, 24);
                hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
            }
            return(hashCode);
        }
예제 #31
0
 public static string EncryptFile(string path)
 {
     try
     {
         byte[] ba;
         using (var csp = new System.Security.Cryptography.SHA256CryptoServiceProvider())
         {
             using (FileStream fs = File.OpenRead(path))
                 ba = csp.ComputeHash(fs);
         }
         return(Convert.ByteArrayToString(ba));
     }
     catch (Exception ex)
     {
         Log.Debug(ex);
         return(string.Empty);
     }
 }
예제 #32
0
        /// <summary>
        /// 计算SHA-256码
        /// </summary>
        /// <param name="word">字符串</param>
        /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
        /// <returns></returns>
        public static string Hash_SHA_256(string word, bool toUpper = true)
        {
            try
            {
                System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP
                    = new System.Security.Cryptography.SHA256CryptoServiceProvider();

                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
                byte[] bytHash = SHA256CSP.ComputeHash(bytValue);
                SHA256CSP.Clear();

                //根据计算得到的Hash码翻译为SHA-1码
                string sHash = "", sTemp = "";
                for (int counter = 0; counter < bytHash.Count(); counter++)
                {
                    long i = bytHash[counter] / 16;
                    if (i > 9)
                    {
                        sTemp = ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp = ((char)(i + 0x30)).ToString();
                    }
                    i = bytHash[counter] % 16;
                    if (i > 9)
                    {
                        sTemp += ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp += ((char)(i + 0x30)).ToString();
                    }
                    sHash += sTemp;
                }

                //根据大小写规则决定返回的字符串
                return toUpper ? sHash : sHash.ToLower();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #33
0
        private string GetFileHash(string filePath)
        {
            FileInfo fi = new System.IO.FileInfo(filePath);
            String retVal = null;

            // Bootstrapper is always signed with the SHA-256 algorithm, no matter which version of
            // the .NET Framework we are targeting.  In ideal situations, bootstrapper files will be
            // pre-signed anwyay; this is a fallback in case we ever encounter a bootstrapper that is
            // not signed.  
            System.Security.Cryptography.SHA256CryptoServiceProvider sha = new System.Security.Cryptography.SHA256CryptoServiceProvider();

            using (Stream s = fi.OpenRead())
            {
                retVal = ByteArrayToString(sha.ComputeHash(s));
            }
            return retVal;
        }
예제 #34
0
 /// <summary>
 /// Return unique Int64 value for input string
 /// </summary>
 /// <param name="strText"></param>
 /// <returns></returns>
 private static UInt64 GetInt64HashCode(string strText)
 {
     UInt64 hashCode = 0;
       if (!string.IsNullOrEmpty(strText)) {
     //Unicode Encode Covering all characterset
     byte[] byteContents = Encoding.Unicode.GetBytes(strText);
     System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider();
     byte[] hashText = hash.ComputeHash(byteContents);
     //32Byte hashText separate
     //hashCodeStart = 0~7  8Byte
     //hashCodeMedium = 8~23  8Byte
     //hashCodeEnd = 24~31  8Byte
     //and Fold
     UInt64 hashCodeStart = BitConverter.ToUInt64(hashText, 0);
     UInt64 hashCodeMedium = BitConverter.ToUInt64(hashText, 8);
     UInt64 hashCodeEnd = BitConverter.ToUInt64(hashText, 24);
     hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
       }
       return (hashCode);
 }
예제 #35
0
            static Settings()
            {
                var props = from p in typeof(Settings).GetProperties(BindingFlags.Public | BindingFlags.Static)
                            let t = typeof(DefaultValueAttribute)
                            where p.IsDefined(t, inherit: false)
                            let a = p.GetCustomAttributes(t, inherit: false).Single() as DefaultValueAttribute
                            select new { PropertyInfo = p, DefaultValue = a };

                foreach (var pair in props)
                {
                    pair.PropertyInfo.SetValue(null, Convert.ChangeType(pair.DefaultValue.Value, pair.PropertyInfo.PropertyType), null);
                }

                // this assists in debug and is also good for prd, the version is a hash of the main assembly

                string location;
                try
                {
                    location = typeof (Settings).Assembly.Location;
                }
                catch
                {
                    location = HttpContext.Current.Server.MapPath("~/bin/MiniProfiler.dll");
                }

                try
                {
                    List<string> files = new List<string>();
                    files.Add(location);

                    string customUITemplatesPath = "";
                    if (HttpContext.Current != null)
                        customUITemplatesPath = HttpContext.Current.Server.MapPath(MiniProfiler.Settings.CustomUITemplates);

                    if (System.IO.Directory.Exists(customUITemplatesPath))
                    {
                        files.AddRange(System.IO.Directory.EnumerateFiles(customUITemplatesPath));
                    }

                    using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                    {
                        byte[] hash = new byte[sha256.HashSize / 8];
                        foreach (string file in files)
                        {
                            // sha256 can throw a FIPS exception, but SHA256CryptoServiceProvider is FIPS BABY - FIPS
                            byte[] contents = System.IO.File.ReadAllBytes(file);
                            byte[] hashfile = sha256.ComputeHash(contents);
                            for (int i = 0; i < (sha256.HashSize / 8); i++)
                            {
                                hash[i] = (byte)(hashfile[i] ^ hash[i]);
                            }
                        }
                        Version = System.Convert.ToBase64String(hash);
                    }
                }
                catch
                {
                    Version = Guid.NewGuid().ToString();
                }

                typesToExclude = new HashSet<string>
                {
                    // while we like our Dapper friend, we don't want to see him all the time
                    "SqlMapper"
                };

                methodsToExclude = new HashSet<string>
                {
                    "lambda_method",
                    ".ctor"
                };

                assembliesToExclude = new HashSet<string>
                {
                    // our assembly
                    typeof(Settings).Assembly.GetName().Name,

                    // reflection emit
                    "Anonymously Hosted DynamicMethods Assembly",

                    // the man
                    "System.Core",
                    "System.Data",
                    "System.Data.Linq",
                    "System.Web",
                    "System.Web.Mvc",
                };

                // for normal usage, this will return a System.Diagnostics.Stopwatch to collect times - unit tests can explicitly set how much time elapses
                StopwatchProvider = StopwatchWrapper.StartNew;
            }
예제 #36
0
        private string HashString(string input)
        {
            string result = "";

            using (System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256CryptoServiceProvider())
            {
                byte[] data = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
                StringBuilder stringBuilder = new StringBuilder();

                for (int counter = 0; counter < data.Length; counter++)
                {
                    stringBuilder.Append(data[counter].ToString("x2"));
                }

                result = stringBuilder.ToString();
            }

            return result;
        }