public static string GetSha1Hash(this string value)
 {
     var encoding = new UTF8Encoding();
     var hash = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     var hashed = hash.ComputeHash(encoding.GetBytes(value));
     return encoding.GetString(hashed);
 }
Exemple #2
0
 public string SHA1Encrypt(string strIN)
 {
     byte[] data = System.Text.Encoding.Default.GetBytes(strIN);    //以字节方式存储
     System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] result = sha1.ComputeHash(data);                        //得到哈希值
     return(System.BitConverter.ToString(result).Replace("-", "")); //转换成为字符串的显示
 }
Exemple #3
0
 public static Guid ToGuid(this string src) //Do not edit this function!
 {
     byte[] stringbytes = Encoding.UTF8.GetBytes(src);
     byte[] hashedBytes = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(stringbytes);
     Array.Resize(ref hashedBytes, 16);
     return(new Guid(hashedBytes));
 }
Exemple #4
0
 public static string GetSha1Hash(Stream s)
 {
     using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         return(Convert.ToBase64String(sha1.ComputeHash(s)));
     }
 }
Exemple #5
0
        public String JsSign(string url, string noncestr, string timestamp)
        {
            var api2 = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={GetAccessToken()}&type=jsapi", "GET");

            try
            {
                var josn2 = api2.CreateRequestReturnJson();

                var str = $"jsapi_ticket={josn2["ticket"].Value<string>()}&noncestr={noncestr}&timestamp={timestamp}&url={url}";
                //Comm.WriteLog("JsSign", $"accessToken:{_config.AccessToken} \r\n Url:{str}", Enums.DebugLogLevel.Normal);
                byte[] StrRes = Encoding.Default.GetBytes(str);
                System.Security.Cryptography.HashAlgorithm iSHA = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                StrRes = iSHA.ComputeHash(StrRes);
                StringBuilder EnText = new StringBuilder();
                foreach (byte iByte in StrRes)
                {
                    EnText.AppendFormat("{0:x2}", iByte);
                }
                //Comm.WriteLog("JsSign", EnText.ToString(), Enums.DebugLogLevel.Normal);
                return(EnText.ToString());
            }
            catch (Exception ex)
            {
                Comm.WriteLog("JsSignError", ex.Message, Enums.DebugLogLevel.Error);
                throw new Exception(ex.Message);
            }
        }
Exemple #6
0
 public string GetHashSHA1(byte[] data)
 {
     using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         return(string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2"))));
     }
 }
Exemple #7
0
        public static string GetSHA1Hash(string pathName)
        {
            string strResult = "";
            string strHashData = "";

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

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                       new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(pathName);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception)
            {
            }

            return (strResult);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            string path = @"d:\temp\test.txt";

            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            byte[] data             = new byte[(int)fs.Length];
            fs.Read(data, 0, (int)fs.Length);
            fs.Close();
            fs.Dispose();

            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] theHash = sha1.ComputeHash(data);

            Console.Write("the hash is ");

            foreach (byte b in theHash)
            {
                Console.Write(string.Format("{0:x2} ", b));
            }

            Console.WriteLine();

            UnicodeEncoding u = new UnicodeEncoding();

            Console.WriteLine("hash in string form is " + Convert.ToBase64String(theHash));

            Console.ReadLine();
            return; //another test
            //local dev change
        }
Exemple #9
0
        public static bool CheckSHA1(string path, string?compareHash)
        {
            if (string.IsNullOrEmpty(compareHash))
            {
                return(true);
            }

            try
            {
                string fileHash;

                using (var file = File.OpenRead(path))
                    using (var hasher = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                    {
                        var binaryHash = hasher.ComputeHash(file);
                        fileHash = BitConverter.ToString(binaryHash).Replace("-", "").ToLowerInvariant();
                    }

                return(fileHash == compareHash);
            }
            catch
            {
                return(false);
            }
        }
Exemple #10
0
 public string ToGuid(string pString)
 {
     byte[] bString = Encoding.UTF8.GetBytes(pString.ToUpper());
     byte[] bHash   = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(bString);
     Array.Resize(ref bHash, 16);
     return(new Guid(bHash).ToString().ToUpper());
 }
Exemple #11
0
        /// <summary>
        /// SHA-1
        /// </summary>
        /// <param name="str"></param>
        public static string SHA_1(string str)
        {
            var sha1Csp = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash  = sha1Csp.ComputeHash(bytValue);
            sha1Csp.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);
        }
Exemple #12
0
        internal string CreateHash(string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            Encoder enc = Encoding.Unicode.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] unicodeText = new byte[str.Length * 2];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

            //Change to be FIPS compliant
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] result = sha1.ComputeHash(unicodeText);


            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            StringBuilder sb = new StringBuilder();

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

            // And return it
            return(sb.ToString());
        }
Exemple #13
0
        public string EncodeText(string text)
        {
            string encodeStr = "";

            System.Security.Cryptography.SHA1CryptoServiceProvider serviceProvider =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] buf = new byte[text.Count()];
            int    i   = 0;

            foreach (char c in text.ToCharArray())
            {
                byte b = (byte)c;
                buf[i] = b;
                i++;
            }

            byte[]      withHash   = serviceProvider.ComputeHash(buf, 0, buf.Length);
            List <char> encodeList = new List <char>();

            foreach (byte b in withHash)
            {
                encodeList.Add((char)b);
                encodeStr = encodeStr + ((char)b).ToString();
            }


            return(encodeStr);
        }
Exemple #14
0
        // GET: IsBankasi
        public ActionResult Index()
        {
            IsBankasiVm model = new IsBankasiVm();

            model.clientId  = "700655000100";
            model.amount    = "9.95";
            model.oid       = "";
            model.okUrl     = "http://<SonucAdresi>/Isbank/Sonuc"; //Bankasnın dönüş Urlsi
            model.failUrl   = "http://<SonucAdresi>/Isbank/Sonuc";
            model.rnd       = DateTime.Now.ToString();
            model.storekey  = "TRPS1234";
            model.storetype = "3d";
            String hashstr = model.clientId + model.oid + model.amount + model.okUrl + model.failUrl + model.rnd + model.storekey;

            System.Security.Cryptography.SHA1 sha = new
                                                    System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hashbytes  = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashstr);
            byte[] inputbytes = sha.ComputeHash(hashbytes);
            model.hash = Convert.ToBase64String(inputbytes);
            String description = "";
            String xid         = "";
            String lang        = "";
            String email       = "";
            String userid      = "";


            return(View(model));
        }
 public void init()
 {
     //    signature=java.security.Signature.getInstance("SHA1withRSA");
     //    keyFactory=KeyFactory.getInstance("RSA");
     sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write);
 }
Exemple #16
0
        }                                                            /*}}}*/

        public static string sha1_string(string sData, Encoding Enc) /*{{{
                                                                      */
        {
            byte[] bSource = Enc.GetBytes(sData);
            byte[] bHash   = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(bSource);
            return(BitConverter.ToString(bHash).ToLower().Replace("-", ""));
        }                                              /*}}}*/
Exemple #17
0
        private Boolean GenerarSelloSHA1(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 = null;
            System.Security.Cryptography.SHA1CryptoServiceProvider EncriptaSHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            Byte[] CadenaOriginalEnBytes = EncriptaSHA1.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("SHA1");
                    CadenaOriginalEnBytes = RSAFormatter.CreateSignature(CadenaOriginalEnBytes);
                    SelloDigital          = Convert.ToBase64String(CadenaOriginalEnBytes);
                    Resultado             = SelloDigital;
                    Devolver = true;
                }
                else
                {
                    ErrorSellado.Add(ErrorSellador);
                }
            }

            return(Devolver);
        }
Exemple #18
0
        /// <summary>
        /// 加密验证
        /// </summary>
        /// <param name="signature">源</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">nonce</param>
        /// <param name="token">自定义Token</param>
        /// <returns></returns>
        public static bool CheckSignature(string signature, string timestamp, string nonce)
        {
            List <string> list = new List <string>();

            list.Add(Token);
            list.Add(timestamp);
            list.Add(nonce);
            list.Sort();
            StringBuilder sb = new StringBuilder();

            foreach (var item in list)
            {
                sb.Append(item);
            }
            System.Security.Cryptography.HashAlgorithm SHA_1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] str = Encoding.UTF8.GetBytes(sb.ToString());
            str = SHA_1.ComputeHash(str);
            StringBuilder strSB = new StringBuilder();

            foreach (var item in str)
            {
                strSB.AppendFormat("{0:x2}", item);
            }
            return(strSB.ToString() == signature);
        }
Exemple #19
0
        /// <summary>
        /// calculate sha-1 of the audio data
        /// </summary>
        public override byte[] CalculateAudioSHA1()
        {
            using (Stream stream = OpenAudioStream())
            {
                // This is one implementation of the abstract class SHA1.
                System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

                uint numLeft = _payloadNumBytes;

                const int size  = 4096;
                byte[]    bytes = new byte[4096];
                int       numBytes;

                while (numLeft > 0)
                {
                    // read a whole block, or to the end of the file
                    numBytes = stream.Read(bytes, 0, size);

                    // audio ends on or before end of this read; exit loop and checksum what we have.
                    if (numLeft <= numBytes)
                    {
                        break;
                    }

                    sha.TransformBlock(bytes, 0, size, bytes, 0);
                    numLeft -= (uint)numBytes;
                }

                sha.TransformFinalBlock(bytes, 0, (int)numLeft);

                byte[] result = sha.Hash;
                return(result);
            }
        }
Exemple #20
0
 public static string SHA1(string value)
 {
     System.Security.Cryptography.SHA1 sha1     = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Text.ASCIIEncoding         encoding = new System.Text.ASCIIEncoding();
     sha1.ComputeHash(encoding.GetBytes(value));
     return(BitConverter.ToString(sha1.Hash).Replace("-", ""));
 }
Exemple #21
0
        public static System.Security.Cryptography.SHA1 GetGen3RuntimeDataHasher()
        {
            var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            sha1.TransformBlock(kSha1Salt, 0, kSha1Salt.Length, null, 0);
            return(sha1);
        }
Exemple #22
0
        public static string Generate()
        {
            // Generate random
            var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var entropy = new byte[bytes - 4];
            try {
                rnd.GetBytes(entropy);
            } finally {
                rnd.Dispose();
            }

            // Hash
            var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hash;
            try {
                hash = sha.ComputeHash(entropy);
            } finally {
                sha.Dispose();
            }

            // Compute output
            var raw = new byte[bytes];
            Array.Copy(entropy, 0, raw, 0, bytes - 4);
            Array.Copy(hash, 0, raw, bytes - 4, 4);

            // Convert to Base64
            return Convert.ToBase64String(raw).Replace('+', '!').Replace('/', '~');
        }
Exemple #23
0
 public void init()
 {
     //    signature=java.security.Signature.getInstance("SHA1withRSA");
     //    keyFactory=KeyFactory.getInstance("RSA");
     sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     cs   = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write);
 }
Exemple #24
0
        private bool CheckSHA1(string path, string compareHash)
        {
            try
            {
                if (!CheckHash)
                {
                    return(true);
                }

                if (compareHash == null || compareHash == "")
                {
                    return(true);
                }

                var fileHash = "";

                using (var file = File.OpenRead(path))
                    using (var hasher = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                    {
                        var binaryHash = hasher.ComputeHash(file);
                        fileHash = BitConverter.ToString(binaryHash).Replace("-", "").ToLower();
                    }

                return(fileHash == compareHash);
            }
            catch
            {
                return(false);
            }
        }
Exemple #25
0
 public static bool VerifySha1Data(this System.Security.Cryptography.RSACryptoServiceProvider RSAalg, byte[] unsignedData, byte[] encryptedData)
 {
     using (var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         return(RSAalg.VerifyData(unsignedData, sha, encryptedData));
     }
 }
 private string GetSelloFromDerKey(string cadenaOriginal)
 {
     if ("3.3".Equals(cadenaOriginal.Substring(2, 3)))
     {
         System.Security.Cryptography.SHA256CryptoServiceProvider sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); // this.GetSHA256CryptoServiceProvider();
         System.Security.SecureString passwordSeguro = new System.Security.SecureString();
         passwordSeguro.Clear();
         foreach (char c in this.PrivateKeyContrasena.ToCharArray())
         {
             passwordSeguro.AppendChar(c);
         }
         var rsaCryptoIPT = JavaScience.opensslkey.DecodeEncryptedPrivateKeyInfo(this.PrivateKeyDER, passwordSeguro);
         System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
         byte[] binData      = encoder.GetBytes(cadenaOriginal);
         byte[] binSignature = rsaCryptoIPT.SignData(binData, sha256);
         string sello        = Convert.ToBase64String(binSignature);
         return(sello);
     }
     else
     {
         System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
         System.Security.SecureString passwordSeguro = new System.Security.SecureString();
         passwordSeguro.Clear();
         foreach (char c in this.PrivateKeyContrasena.ToCharArray())
         {
             passwordSeguro.AppendChar(c);
         }
         var rsaCryptoIPT = JavaScience.opensslkey.DecodeEncryptedPrivateKeyInfo(this.PrivateKeyDER, passwordSeguro);
         System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
         byte[] binData      = encoder.GetBytes(cadenaOriginal);
         byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
         string sello        = Convert.ToBase64String(binSignature);
         return(sello);
     }
 }
Exemple #27
0
        public static IFileInfo SaveUserProfilePic(int portalId, int userId, string image, int editedByUserId)
        {
            byte[] imgData     = System.Convert.FromBase64String(image.Replace("data:image/png;base64,", string.Empty));
            var    ha          = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            var    hashData    = ha.ComputeHash(imgData);
            var    hash        = System.BitConverter.ToString(hashData).Replace("-", "").Substring(0, 10).ToLower();
            var    fileName    = hash + ".png";
            var    contentType = "image/png";
            var    user        = DotNetNuke.Entities.Users.UserController.GetUserById(portalId, userId);

            SaveText("Retrieved user", Newtonsoft.Json.JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented));
            var       userFolder = FolderManager.Instance.GetUserFolder(user);
            IFileInfo file       = null;

            using (var memStream = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(memStream))
                {
                    bw.Write(imgData);
                    memStream.Seek(0, SeekOrigin.Begin);
                    file = FileManager.Instance.AddFile(userFolder, fileName, memStream, true, false, contentType, editedByUserId);
                    bw.Close();
                    CreateThumbnails(file.FileId);
                }
            }
            FixDnnController.SetUserProfileProperty(portalId, user.UserID, "Photo", file.FileId.ToString());
            ImageController.ClearUserImageCache(portalId, user.UserID);
            return(file);
        }
Exemple #28
0
        public static string GetSHA1Hash(string pathName)
        {
            string strResult   = "";
            string strHashData = "";

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

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream     = GetFileStream(pathName);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult   = strHashData;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception in GetSHA1Hash(string pathName)");
                Trace.WriteLine("Exception is: " + ex.ToString());
            }

            return(strResult.ToLower());
        }
Exemple #29
0
        ////Ghi lỗi vào File
        //public static String = "D:\\Logs\\Inside\\";
        //public void WriteLog(string FunctionPage, string ErrDesc)
        //{
        //    System.DateTime DateNow = new System.DateTime();
        //    //Dim FileName As String = LOGPATH & DateTime.Now.Year.ToString() & DateTime.Now.Month.ToString("00") & ".txt"
        //    string FileName = LOGPATH + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00") + ".txt";
        //    System.IO.StreamWriter objStreamWriter = null;
        //    //Try
        //    if (!System.IO.File.Exists(FileName))
        //    {
        //        objStreamWriter = System.IO.File.CreateText(FileName);
        //        objStreamWriter.Close();
        //    }

        //    objStreamWriter = System.IO.File.AppendText(FileName);
        //    objStreamWriter.WriteLine(DateTime.Now.ToString() + "," + FunctionPage + "," + ErrDesc);
        //    objStreamWriter.Close();
        //    //Catch ex As Exception

        //    //Finally

        //    //End Try
        //}



        protected string TienIchGetSHA1Hash(params string[] arrParams)
        {
            string Input = "";
            int    i;

            for (i = 0; i <= (arrParams.Length - 1); i++)
            {
                Input = Input + " " + arrParams[i];
            }


            System.Security.Cryptography.SHA1CryptoServiceProvider x = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] bs = System.Text.Encoding.UTF8.GetBytes(Input);

            bs = x.ComputeHash(bs);

            System.Text.StringBuilder s = new System.Text.StringBuilder();

            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string md5String = (string)(s.ToString());

            return(md5String);
        }
 private string GetSelloFromPFX(string cadenaOriginal)
 {
     if ("3.3".Equals(cadenaOriginal.Substring(2, 3)))
     {
         System.Security.Cryptography.SHA256CryptoServiceProvider       sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider(); // this.GetSHA256CryptoServiceProvider();
         System.Security.Cryptography.X509Certificates.X509Certificate2 cert   = new System.Security.Cryptography.X509Certificates.X509Certificate2(this.PFXArchivo,
                                                                                                                                                    this.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
         System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
         System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
         byte[] binData      = encoder.GetBytes(cadenaOriginal);
         byte[] binSignature = rsaCryptoIPT.SignData(binData, sha256);
         string sello        = Convert.ToBase64String(binSignature);
         return(sello);
     }
     else
     {
         System.Security.Cryptography.SHA1CryptoServiceProvider         sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
         System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(this.PFXArchivo,
                                                                                                                                                  this.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
         System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
         System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
         byte[] binData      = encoder.GetBytes(cadenaOriginal);
         byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
         string sello        = Convert.ToBase64String(binSignature);
         return(sello);
     }
 }
Exemple #31
0
 /// <summary>
 /// Metodo che trasforma la stringa in una stringa crittografata
 /// </summary>
 /// <param name="Stringa">stringa da crittografare</param>
 /// <returns><c>string</c> stringa crittografata</returns>
 private static String PlainToSHA1(string Stringa)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
     byte[] pwHashed = sha.ComputeHash(objEncoding.GetBytes(Stringa));
     return(System.Convert.ToBase64String(pwHashed));
 }
Exemple #32
0
        public static string GetSHA1Hash(string pathName)
        {
            string strResult   = "";
            string strHashData = "";

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

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream     = GetFileStream(pathName);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult   = strHashData;
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",
                                                     System.Windows.Forms.MessageBoxButtons.OK,
                                                     System.Windows.Forms.MessageBoxIcon.Error,
                                                     System.Windows.Forms.MessageBoxDefaultButton.Button1);
            }

            return(strResult);
        }
Exemple #33
0
        public static string GetSHA1Hash(string pathName)
        {
            string strResult = "";
            string strHashData = "";

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

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                       new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(pathName);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",
                         System.Windows.Forms.MessageBoxButtons.OK,
                         System.Windows.Forms.MessageBoxIcon.Error,
                         System.Windows.Forms.MessageBoxDefaultButton.Button1);
            }

            return (strResult);
        }
        private static string Encrypt(string hashKey, string strQueryStringParameter)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider hash_func = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] key = hash_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));
            byte[] IV  = new byte[hashKey.Length];

            System.Security.Cryptography.SHA1CryptoServiceProvider sha_func = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] temp = sha_func.ComputeHash(Encoding.ASCII.GetBytes(hashKey));

            for (int i = 0; i < hashKey.Length; i++)
            {
                IV[i] = temp[hashKey.Length];
            }

            byte[] toenc = System.Text.Encoding.UTF8.GetBytes(strQueryStringParameter);

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.KeySize = 128;
            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                ms,
                des.CreateEncryptor(key, IV),
                System.Security.Cryptography.CryptoStreamMode.Write
                );
            cs.Write(toenc, 0, toenc.Length);
            cs.FlushFinalBlock();

            return(Convert.ToBase64String(ms.ToArray()));
        }
        internal static byte[] ComputeSignatureDigest(System.IO.Stream chunksStream
                                                      , long chunksOffset
                                                      , long chunksLength
                                                      , ECF.EcfHeader header)
        {
            Contract.Requires(chunksStream != null);
            Contract.Requires(chunksStream.CanSeek && chunksStream.CanRead);
            Contract.Requires(chunksOffset >= 0);
            Contract.Requires(chunksLength > 0);

            using (var sha = new SHA1CryptoServiceProvider())
            {
                PhxHash.UInt32(sha, kSha1Salt);
                PhxHash.UInt32(sha, (uint)header.HeaderSize);
                PhxHash.UInt32(sha, (uint)header.ChunkCount);
                PhxHash.UInt32(sha, (uint)header.ExtraDataSize);
                PhxHash.UInt32(sha, (uint)header.TotalSize);

                PhxHash.Stream(sha,
                               chunksStream, chunksOffset, chunksLength,
                               isFinal: true);

                return(sha.Hash);
            }
        }
        public static Guid GetFeatureOfHuman(byte[] humanDescriptionBytes)
        {
            byte[] hashedBytes = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(humanDescriptionBytes);

            Array.Resize(ref hashedBytes, 16);

            return new Guid(hashedBytes);
        }
 private static string GenerateAuthorizationToken(string passTypeIdentifier, string serialNumber)
 {
     using (System.Security.Cryptography.SHA1CryptoServiceProvider hasher = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         byte[] data = Encoding.UTF8.GetBytes(passTypeIdentifier.ToLower() + serialNumber.ToLower() + mAuthorizationKey);
         return System.BitConverter.ToString(hasher.ComputeHash(data)).Replace("-", string.Empty).ToLower();
     }
 }
Exemple #38
0
        /// <summary>
        /// Retorna el hash SHA1 de la cadena de texto que recibe como parámetro.
        /// </summary>
        /// <param name="unHashed">Cadena de texto a encriptar.</param>
        /// <returns>Hash de la cadena de texto. SHA1.</returns>
        public static string createHash(string unHashed)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider x = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed);
            data = x.ComputeHash(data);

            return Convert.ToBase64String(data);
        }
Exemple #39
0
        private static string GetCryptographyString(string strSource)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytes = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(strSource));
            string result = BitConverter.ToString(bytes, 4, 8).Replace("-","");

            return result;
        }
 private static string Hash(string toHash)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider x = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] data = System.Text.Encoding.ASCII.GetBytes(toHash);
     data = x.ComputeHash(data);
     string o = BitConverter.ToString(data).Replace("-", "").ToUpper();
     return o;
 }
Exemple #41
0
        public static string root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // string root points to MyDocuments

        #endregion Fields

        #region Methods

        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0] == "-v")
                {
                    Console.WriteLine("asdasd");
                    if (File.Exists(prefs + "/gkey"))
                    {
                            using (System.IO.StreamReader sr = new System.IO.StreamReader(prefs + "/gkey"))
                            {
                                string data = sr.ReadToEnd();
                                string[] f = data.Split('\n');
                                sr.Dispose();
                                if (f[0] == "accepted")
                                {
                                    string HASH = f[1].ToString();
                                    using (System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                                    {
                                        string hashsum = string.Empty;                  // Empty storage allocator
                                        byte[] da = sha1.ComputeHash(Encoding.Unicode.GetBytes(prefs + "/gkey"));       // byte array
                                        foreach (byte by in data)
                                        {
                                            hashsum += String.Format("{0,2:X2}", by);        // :-)
                                        }

                                        if (hashsum.ToString() != HASH.ToString())
                                        {
                                            Console.ForegroundColor = ConsoleColor.Red;
                                            Console.Write("SECURITY COMPROMISED!\n\nSHA1 HASH MODIFIED!\nRECORD DOES NOT MATCH G_KEY!\n\nCACHE WILL BE DELETED FOR SECURITY.");
                                            Console.Read();

                                        }

                                        else ;
                                        sha1.Dispose();

                                        try
                                        {
                                            Directory.Delete(prefs);
                                        }

                                        catch { ; }
                                    }
                                }

                            }

                    }
                }

            }

            else
            {
                Console.Write("This is not a standalone application.");
            }
        }
Exemple #42
0
 public static string GetSHA1(string pwdata_s)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     ASCIIEncoding enc = new ASCIIEncoding();
     byte[] pwdata_b = enc.GetBytes(pwdata_s);//password(string) to byte[]
     byte[] pwsha1_b = osha1.ComputeHash(pwdata_b);//ToHash
     string pwsha1_s = BitConverter.ToString(pwsha1_b).Replace("-", "");//hash to string
     return pwsha1_s;
 }
Exemple #43
0
 public string sha1(string input)
 {
     byte[] hash;
     using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
         hash = sha1.ComputeHash(Encoding.Unicode.GetBytes(input));
     var sb = new StringBuilder();
     foreach (byte b in hash) sb.AppendFormat("{0:x2}", b);
     return sb.ToString();
 }
Exemple #44
0
 public string EncryptToSHA1(string str)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str);
     byte[] str2 = sha1.ComputeHash(str1);
     sha1.Clear();
     (sha1 as IDisposable).Dispose();
     return Convert.ToBase64String(str2);
 }
        /// <summary>
        /// Método para encriptar un string. En este caso se usa para el Pass.
        /// </summary>
        /// <param name="password">Contraseña a encriptar</param>
        /// <returns>Cadena encriptada</returns>
        private static string encrypt(string password)
        {
            System.Security.Cryptography.HashAlgorithm hashValue = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(password);
            byte[] byteHash = hashValue.ComputeHash(bytes);

            hashValue.Clear();

            return (Convert.ToBase64String(byteHash));
        }
Exemple #46
0
 public static string Encriptar(string valor)
 {
     string clave;
     System.Security.Cryptography.SHA1CryptoServiceProvider provider = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(valor);
     byte[] inArray = provider.ComputeHash(bytes);
     provider.Clear();
     clave = Convert.ToBase64String(inArray);
     return clave;
 }
Exemple #47
0
 public string ComputeSHA1Hash(string input)
 {
     var encrypter = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     using (var sw = new StringWriter())
     {
         foreach (byte b in encrypter.ComputeHash(Encoding.UTF8.GetBytes(input)))
             sw.Write(b.ToString("x2"));
         return sw.ToString();
     }
 }
Exemple #48
0
 public static string HashString(string Value)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider x = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] data = System.Text.Encoding.ASCII.GetBytes(Value);
     data = x.ComputeHash(data);
     string ret = "";
     for (int i = 0; i < data.Length; i++)
         ret += data[i].ToString("x2").ToLower();
     return ret;
 }
 private string GetSelloFromPFX(string cadenaOriginal) {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(this.PFXArchivo,
          this.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
     System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     byte[] binData = encoder.GetBytes(cadenaOriginal);
     byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
     string sello = Convert.ToBase64String(binSignature);
     return sello;
 }
Exemple #50
0
 public static string getHash(Object input)
 {
     // generate a unique id for an arbitrairy object
     MemoryStream memoryStream = new MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     binaryFormatter.Serialize(memoryStream, input);
     System.Security.Cryptography.SHA1CryptoServiceProvider sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] hash = sha.ComputeHash(memoryStream.ToArray());
     string str = Convert.ToBase64String(sha.Hash);
     return str;
 }
        protected string to_SHA1(string s)
        {
            byte[] data = new byte[256];
            byte[] result;

            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            // This is one implementation of the abstract class SHA1.
            result = sha.ComputeHash(data);

            return BitConverter.ToString(result);
        }
        // used by?
        public static byte[] FileNameToSHA1Bytes(this string Input)
        {
            var SourceHash = default(byte[]);

            var h = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            using (var f = File.OpenRead(Input))
                SourceHash = h.ComputeHash(f);

            return SourceHash;
        }
  public override void init(){
    try
	{ 
		//md=MessageDigest.getInstance("SHA-1");
		md=new System.Security.Cryptography.SHA1CryptoServiceProvider();
		cs = new System.Security.Cryptography.CryptoStream( System.IO.Stream.Null, md, System.Security.Cryptography.CryptoStreamMode.Write);
	}
    catch(Exception e){
      Console.WriteLine(e);
    }
  }
Exemple #54
0
        public static string ToHash(this string str)
        {
            var bytes = Encoding.UTF8.GetBytes(str);
            var shaProvider = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            var hashBytes = shaProvider.ComputeHash(bytes);

            var sb = new StringBuilder();
            foreach (var b in hashBytes)
                sb.Append(b.ToString("X2"));

            return sb.ToString();
        }
Exemple #55
0
        public static string ComputeHash(string path)
        {
            Image myThumbnail = GetThumb(path);

            using (System.IO.MemoryStream streamout = new System.IO.MemoryStream())
            {
                myThumbnail.Save(streamout, System.Drawing.Imaging.ImageFormat.Bmp);
                streamout.Position = 0;
                System.Security.Cryptography.SHA1 x = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                return BitConverter.ToString(x.ComputeHash(streamout)).Replace("-", "");
            }            
        }
 private string GetSelloFromDerKey(string cadenaOriginal) {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Security.SecureString passwordSeguro = new System.Security.SecureString();
     passwordSeguro.Clear();
     foreach (char c in this.PrivateKeyContrasena.ToCharArray())
         passwordSeguro.AppendChar(c);
     var rsaCryptoIPT = JavaScience.opensslkey.DecodeEncryptedPrivateKeyInfo(this.PrivateKeyDER, passwordSeguro);
     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     byte[] binData = encoder.GetBytes(cadenaOriginal);
     byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
     string sello = Convert.ToBase64String(binSignature);
     return sello;
 }
 public override bool ChangePassword(string username, string newPassword)
 {
     var item = data.MemberInfos.SingleOrDefault(t => t.Username.ToLower() == username.ToLower());
     if (item == null)
         return false;
     Random rnd = new Random();
     item.Salt= new byte[6];
     rnd.NextBytes(item.Salt);
     using (var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider())
         item.Password = sha.ComputeHash(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(newPassword)).Concat(item.Salt).ToArray());
     data.SaveChanges();
     return true;
 }
Exemple #58
0
 public string Criptografar(string text)
 {
     try
     {
         byte[] buffer = Encoding.Default.GetBytes(text);
         System.Security.Cryptography.SHA1CryptoServiceProvider cryptoTransformSHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
         string hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
         return hash;
     }
     catch (Exception x)
     {
         throw new Exception(x.Message);
     }
 }
Exemple #59
0
        public static string SHA1HashBase64(string ClearText)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider Hasher =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] bClear = new byte[ClearText.Length*2];
            for (int i = 0;i<ClearText.Length*2;++i)
                bClear[i] = Convert.ToByte((((i&1)==0)?Convert.ToUInt16(ClearText[i/2])&0xFF:Convert.ToUInt16(ClearText[i/2])>>8));

            Hasher.ComputeHash(bClear);
            byte[] bHash = Hasher.Hash;

            return Convert.ToBase64String(bHash);
        }
 public override bool Verify(string username, string password)
 {
     var item = data.MemberInfos.SingleOrDefault(t => t.Username == username.ToLower());
     if (item == null)
         return false;
     using (var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         var pwd = sha.ComputeHash(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)).Concat(item.Salt).ToArray());
         for (int i = 0; i < 20; i++)
             if (pwd[i] != item.Password[i])
                 return false;
         return true;
     }
 }