Ejemplo n.º 1
0
        public static string SHA1Hash(Stream input)
        {
            var sha    = SHA1CryptoServiceProvider.Create();
            var hashed = sha.ComputeHash(input);

            return(BitConverter.ToString(hashed));
        }
Ejemplo n.º 2
0
        public static string EncriptarCadenaSHA1(string cadenaAEncriptar)
        {
            string rethash = string.Empty;

            try
            {
                SHA1 hash =
                    SHA1CryptoServiceProvider.Create();
                byte[] dataSHA1 = hash.ComputeHash(Encoding.ASCII.GetBytes(cadenaAEncriptar));

                /*
                 * StringBuilder sb = new StringBuilder();
                 *
                 * for (int i = 0; i < dataSHA1.Length; i++)
                 *
                 *  sb.AppendFormat("{0:x2}", dataSHA1[i]);
                 *
                 * return sb.ToString();
                 */
                rethash = Convert.ToBase64String(hash.Hash);
            }
            catch (Exception ex)
            {
                string strerr = "Error in HashCode : " + ex.Message;
            }
            return(rethash);
        }
Ejemplo n.º 3
0
 /// <summary>建立新的 WebSocketServer 類別,並初始化相關屬性值</summary>
 /// <param name="maxClients">同時可連接的最大連線數</param>
 public WebSocketServer(int maxClients)
 {
     this.UseAsyncCallback = EventCallbackMode.BeginInvoke;
     m_Mutex        = new Mutex();
     m_Services     = new List <string>();
     m_sha          = SHA1CryptoServiceProvider.Create();
     m_IsDisposed   = false;
     m_LocalEndPort = null;
     m_Counters     = new Dictionary <ServerCounterType, PerformanceCounter>();
     m_Pool         = new SocketAsyncEventArgsPool();
     // 預留兩條線程,用於過多的連線數檢查
     m_MaxClients   = new Semaphore(maxClients + 2, maxClients + 2);
     m_Clients      = new ConcurrentDictionary <string, AsyncClient>();
     m_WaitToClean  = new ConcurrentDictionary <EndPoint, int>();
     m_IsShutdown   = false;
     this.IsStarted = false;
     for (int i = 0; i < maxClients; i++)
     {
         SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
         arg.Completed            += new EventHandler <SocketAsyncEventArgs>(this.IO_Completed);
         arg.DisconnectReuseSocket = true;
         arg.SetBuffer(new Byte[BUFFER_SIZE], 0, BUFFER_SIZE);
         m_Pool.Push(arg);
     }
     SetCounterDictionary();
 }
Ejemplo n.º 4
0
        public bool AuthorizeUser(string user_name, string user_pass)
        {
            try
            {
                user_name = MySql.Data.MySqlClient.MySqlHelper.EscapeString(user_name);
                user_pass = MySql.Data.MySqlClient.MySqlHelper.EscapeString(user_pass);

                //source: http://stackoverflow.com/a/9790651
                string user_pass_sha1_hex = BitConverter.ToString(SHA1CryptoServiceProvider.Create().ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(user_pass))).Replace("-", "").ToLower();

                string sql = "SELECT * FROM csharp_accounts " +
                             "WHERE user_name = '" + user_name + "'" +
                             "AND user_pass = '******';";

                mysql.db.execute(sql);
                if (mysql.db.reader.HasRows)
                {
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
            finally
            {
                mysql.db.reader.Close();
            }

            return(false);
        }
Ejemplo n.º 5
0
        public static string SHA1HashBase64(byte[] buffer)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            byte[] hash = sha1.ComputeHash(buffer);
            return(Convert.ToBase64String(hash));
        }
Ejemplo n.º 6
0
        public ActionResult Index(Users user)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            user.password = string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(user.password)).SelectMany(x => x.ToString("x2")));
            var doLogin = rentacar.Users.Where(model => model.register == user.register && model.password == user.password).FirstOrDefault();

            if (doLogin != null)
            {
                FormsAuthentication.SetAuthCookie(doLogin.name, false);

                if (Request.QueryString["ReturnUrl"] == null)
                {
                    return(RedirectToAction("", "Home"));
                }
                else
                {
                    return(RedirectToAction(Request.QueryString["ReturnUrl"].ToString()));
                }
            }
            else
            {
                ModelState.AddModelError("", "Usuário e ou senha inválido!");
            }

            return(View(user));
        }
Ejemplo n.º 7
0
        private string AcceptKey(ref string key)
        {
            string longKey = key + guid;
            SHA1   sha1    = SHA1CryptoServiceProvider.Create();

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 8
0
        private string calculateAcceptKey(string key)
        {
            var longKey   = key + guid;
            var sha1      = SHA1CryptoServiceProvider.Create();
            var hashBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(longKey));

            return(Convert.ToBase64String(hashBytes));
        }
Ejemplo n.º 9
0
    public static string GetStringSHA1(string data)
    {
        using (var shaProvider = SHA1CryptoServiceProvider.Create()) {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            string sha   = BitConverter.ToString(shaProvider.ComputeHash(bytes));
            sha = Hash.hashNormilize(sha);

            return(sha);
        }
    }
Ejemplo n.º 10
0
        /// <summary>
        /// generates the hash code from the string passed
        /// </summary>
        public static string HashCode(string str)
        {
            SHA1 hash = SHA1CryptoServiceProvider.Create();

            byte[] plainTextBytes = Encoding.ASCII.GetBytes(str);
            byte[] hashBytes      = hash.ComputeHash(plainTextBytes);
            string localChecksum  = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();

            return(localChecksum);
        }
 private static byte[] HashData(byte[] buf, int start, int length)
 {
     using (SHA1 sha = SHA1CryptoServiceProvider.Create())
     {
         var r   = new byte[20];
         var res = sha.ComputeHash(buf, start, length);
         Buffer.BlockCopy(res, 0, r, 0, r.Length);
         return(r);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the alogrithm.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="hashName">Name of the hash algorithm.</param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException">
        /// </exception>
        private static HashAlgorithm GetHashAlogrithm(HashMethod method, string hashName = null)
        {
            if (hashName == null)
            {
                switch (method)
                {
                case HashMethod.MD5:
                    return(MD5CryptoServiceProvider.Create());

                case HashMethod.SHA1:
                    return(SHA1CryptoServiceProvider.Create());

                case HashMethod.SHA256:
                    return(SHA256CryptoServiceProvider.Create());

                case HashMethod.SHA384:
                    return(SHA384CryptoServiceProvider.Create());

                case HashMethod.SHA512:
                    return(SHA512CryptoServiceProvider.Create());

                case HashMethod.CRC32:
                    return(new CRC32());

                default:
                    throw new NotSupportedException(
                              string.Format("Method [{0}] is not supported.", method.ToString()));
                }
            }
            else
            {
                switch (method)
                {
                case HashMethod.MD5:
                    return(MD5CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA1:
                    return(SHA1CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA256:
                    return(SHA256CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA384:
                    return(SHA384CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA512:
                    return(SHA512CryptoServiceProvider.Create(hashName));

                default:
                    throw new NotSupportedException(
                              string.Format("Method [{0}] is not supported.", method.ToString()));
                }
            }
        }
Ejemplo n.º 13
0
    public static string GetFileSHA1(string path)
    {
        using (var shaProvider = SHA1CryptoServiceProvider.Create()) {
            using (var stream = File.OpenRead(path)) {
                string sha = BitConverter.ToString(shaProvider.ComputeHash(stream));
                sha = Hash.hashNormilize(sha);

                return(sha);
            }
        }
    }
Ejemplo n.º 14
0
        private String2 ComputeHash(String2 key)
        {
            if (SHA == null)
            {
                SHA = SHA1CryptoServiceProvider.Create();
            }
            String buffer = key.Trim().ToString() + Define.GUID;

            byte[] hash = SHA.ComputeHash(Encoding.ASCII.GetBytes(buffer));
            return(new String2(Convert.ToBase64String(hash), Encoding.UTF8));
        }
Ejemplo n.º 15
0
        public static string Sha1Hash(string data)
        {
            SHA1 hash = SHA1CryptoServiceProvider.Create();

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(data);
            byte[] hashBytes      = hash.ComputeHash(plainTextBytes);
            string localChecksum  = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();

            return(localChecksum);
            //return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(data)).Select(x => x.ToString("X2")) as String[]);
            //return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(data)).Select(x => x.ToString("X2"))).ToLower();
        }
Ejemplo n.º 16
0
            private static string SHA1Hash(byte[] bytes)
            {
                SHA1 sha1 = SHA1CryptoServiceProvider.Create();

                byte[]        dataMd5 = sha1.ComputeHash(bytes);
                StringBuilder sb      = new StringBuilder();

                for (int i = 0; i < dataMd5.Length; i++)
                {
                    sb.AppendFormat("{0:x2}", dataMd5[i]);
                }
                return(sb.ToString());
            }
        public static qPtl_User UserLogon(String user_name, String password)
        {
            string hashed_password = string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("X2"))).ToLower();

            var user = new qPtl_User();

            user.container.Select(user.container.GetSelectColumns(),
                                  "",
                                  "Available = 'Yes' AND AccountStatus <> 'Deleted' AND MarkAsDelete = 0 AND UserName = @UserName AND Password = @Password",
                                  new SqlQueryParameter[] { new SqlQueryParameter("@UserName", user_name), new SqlQueryParameter("@Password", hashed_password) });

            return(user.UserID > 0 ? user : null);
        }
Ejemplo n.º 18
0
        public static string SHA1Hash(byte[] buffer)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            byte[]        hash = sha1.ComputeHash(buffer);
            StringBuilder sb   = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return(sb.ToString());
        }
        public static byte[] ComputeHash(byte[] input, byte[] salt, string algorithm)
        {
            if (input == null || input.Length == 0)
            {
                throw new ArgumentException();
            }

            if (salt == null || salt.Length == 0)
            {
                salt = RandomGenerator.GetBytes(8);
            }

            System.Security.Cryptography.HashAlgorithm hash;
            switch (algorithm.ToUpper())
            {
            case "MD5":
                hash = MD5CryptoServiceProvider.Create();
                break;

            case "SHA":
            case "SHA1":
                hash = SHA1CryptoServiceProvider.Create();
                break;

            case "SHA256":
                hash = SHA256Managed.Create();
                break;

            case "SHA384":
                hash = SHA384Managed.Create();
                break;

            case "SHA512":
                hash = SHA512Managed.Create();
                break;

            default:
                throw new NotSupportedException();
            }
            byte[] buffer = new byte[input.Length + salt.Length];
            Array.Copy(input, 0, buffer, 0, input.Length);
            Array.Copy(salt, 0, buffer, input.Length, salt.Length);
            byte[] result = hash.ComputeHash(buffer);
            return(result);

            buffer = new byte[result.Length + salt.Length];
            Array.Copy(result, 0, buffer, 0, result.Length);
            Array.Copy(salt, 0, buffer, result.Length, salt.Length);
            hash.Clear();
            return(buffer);
        }
Ejemplo n.º 20
0
        public static string GetSHA1(String texto)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            Byte[]        textOriginal = ASCIIEncoding.Default.GetBytes(texto);
            Byte[]        hash         = sha1.ComputeHash(textOriginal);
            StringBuilder cadena       = new StringBuilder();

            foreach (byte i in hash)
            {
                cadena.AppendFormat("{0:x2}", i);
            }
            return(cadena.ToString());
        }
Ejemplo n.º 21
0
        public static string ComputeHash(string plainText, AuthenticationType authenticationType)
        {
            var hashedValue = new StringBuilder();

            var hashedData = authenticationType == AuthenticationType.SHA
                ? SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.Unicode.GetBytes(plainText))
                : MD5CryptoServiceProvider.Create().ComputeHash(Encoding.Unicode.GetBytes(plainText));

            foreach (var item in hashedData)
            {
                hashedValue.Append(String.Format("{0,2:X2}", item));
            }
            return(hashedValue.ToString());
        }
        /// <summary>
        /// Proceso que decodifica la llave primaria y encripta la cadena original para generar el sello
        /// digital.
        /// </summary>
        /// <param name="rutaArchivoLlave">
        /// Ruta del archivo que contiene la llave primaria (.key) en formato DER y encriptada.</param>
        /// <param name="password">
        /// Contraseña o frase secreta que se necesita para decodificar la llave primaria.</param>
        private void GenerarSelloDigital(string rutaArchivoLlave, string password)
        {
            string originalString = _resultado.cadenaOriginal;

            RSACryptoServiceProvider rsa = opensslkey.DecodeDERKey(rutaArchivoLlave, password);
            SHA1 hasher = SHA1CryptoServiceProvider.Create();

            byte[] bytesFirmados = rsa.SignData(System.Text.Encoding.UTF8.GetBytes(originalString), hasher);
            string signature     = Convert.ToBase64String(bytesFirmados);

            _resultado.xml.DocumentElement.Attributes[_attributeSello].InnerText = signature;
            _sello = signature;
            _resultado.selloDigial = signature;
        }
Ejemplo n.º 23
0
        public string GetSha1Id()
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            Byte[]        textOriginal = Encoding.UTF8.GetBytes(this.id);
            Byte[]        hash         = sha1.ComputeHash(textOriginal);
            StringBuilder cadena       = new StringBuilder();

            foreach (byte i in hash)
            {
                cadena.AppendFormat("{0:x2}", i);
            }
            return(cadena.ToString());
        }
Ejemplo n.º 24
0
        public string GetSHA1(String text)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            Byte[]        originalText = ASCIIEncoding.Default.GetBytes(text);
            Byte[]        hash         = sha1.ComputeHash(originalText);
            StringBuilder str          = new StringBuilder();

            foreach (byte i in hash)
            {
                str.AppendFormat("{0:x2}", i);
            }
            return(str.ToString());
        }
Ejemplo n.º 25
0
        private bool TestaTimeStamp(string URL)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            byte[] hash = sha1.ComputeHash(Encoding.ASCII.GetBytes("TESTE DE SELO"));

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetCertReq(true);

            TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100)); byte[] tsData = tsReq.GetEncoded();

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);

            req.Method      = "POST";
            req.ContentType = "application/timestamp-query";
            req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("9024:")));
            req.ContentLength = tsData.Length;

            Stream reqStream = req.GetRequestStream();

            reqStream.Write(tsData, 0, tsData.Length);
            reqStream.Close();

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            if (res == null)
            {
                return(false);
            }
            else
            {
                Stream resStream = new BufferedStream(res.GetResponseStream());

                TimeStampResponse tsRes = new TimeStampResponse(resStream); resStream.Close();

                try
                {
                    tsRes.Validate(tsReq);
                    resStream.Close();
                    return(true);
                }
                catch (TspException e)
                {
                    resStream.Close();
                    return(false);
                }
                //saveresponse
            }
        }
        public void SHA1Hash()
        {
            byte[] plaintext = new byte[] { 0, 2, 3, 4 };
            HashAlgorithmProvider provider = new HashAlgorithmProvider(SHA1CryptoServiceProvider.Create());

            byte[] hash = provider.Hash(plaintext);

            Assert.IsFalse(CommonUtil.CompareBytes(plaintext, hash));

            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            byte[] hash2 = sha1.ComputeHash(plaintext);

            Assert.IsTrue(CommonUtil.CompareBytes(hash, hash2));
        }
Ejemplo n.º 27
0
        public String ObtenerSHA1(String contraseña)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();

            sha1 = SHA1CryptoServiceProvider.Create();
            byte[] datasha1 = sha1.ComputeHash(
                Encoding.Default.GetBytes(contraseña));
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < datasha1.Length; i++)
            {
                sb.AppendFormat("{0:x2}", datasha1[i]);
            }
            return(sb.ToString().ToUpper());
        }
Ejemplo n.º 28
0
        private string obtenersha1(string texto)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            Byte[] textOriginal = ASCIIEncoding.Default.GetBytes(texto);
            Byte[] hash         = sha1.ComputeHash(textOriginal);

            StringBuilder str = new StringBuilder();

            foreach (byte i in hash)
            {
                str.AppendFormat("{0:x2}", i);
            }
            return(str.ToString());
        }
Ejemplo n.º 29
0
        private void Convert(object sender, EventArgs e)
        {
            output.Clear();
            byte[] to;
            switch ((Conversions)convertTo.SelectedValue)
            {
            case Conversions.Base64Decode:
                try
                {
                    to = System.Convert.FromBase64String(input.TextValue);
                }
                catch (FormatException ex)
                {
                    MessageBox.Show(this, ex.Message, this.Text);
                    return;
                }
                break;

            case Conversions.Base64Encode:
                to = Encoding.UTF8.GetBytes(System.Convert
                                            .ToBase64String(input.BinaryValue));
                break;

            case Conversions.XmlDecode:
                to = Encoding.UTF8.GetBytes(HttpUtility.HtmlDecode(input.TextValue));
                break;

            case Conversions.XmlEncode:
                to = Encoding.UTF8.GetBytes(HttpUtility.HtmlEncode(input.TextValue));
                break;

            case Conversions.UrlDecode:
                to = Encoding.UTF8.GetBytes(Uri.UnescapeDataString(input.TextValue));
                break;

            case Conversions.UrlEncode:
                to = Encoding.UTF8.GetBytes(Uri.EscapeDataString(input.TextValue));
                break;

            case Conversions.Sha1Hash:
                to = SHA1CryptoServiceProvider.Create().ComputeHash(input.BinaryValue);
                break;

            default:
                return;
            }
            output.AppendBinary(to, to.Length);
        }
Ejemplo n.º 30
0
        public static string Encriptar(string cadena)
        {
            cadena += ""; //A esto se le llama token, semilla
            SHA1 encriptar = SHA1CryptoServiceProvider.Create();

            Byte[]        texto_original   = ASCIIEncoding.Default.GetBytes(cadena);
            Byte[]        texto_encriptado = encriptar.ComputeHash(texto_original);
            StringBuilder stream           = new StringBuilder();

            foreach (byte i in texto_encriptado)
            {
                stream.AppendFormat("{0:x2}", i);
            }

            return(stream.ToString());
        }