encryption my password

Started by
18 comments, last by Pedro Alves 9 years, 9 months ago

i make my game and i want encrypte my password like this $P$DzZ6dPRg/zHF6G3vRHgskT1.FwoX9k/

but my result it is $H$9tUnBmMHAOlbeljxTdJHG/OBfZhstH1


this is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Security;
using System.Net.Sockets;
using System.IO;
namespace TomShane.Neoforce.Central.Code
{
    class Login
    {
       
        public int id_user;
        String username;
        String password;
        public int tipo;
       public int Id
        {

            get { return id_user; }
            set { id_user = value; }
        }
        public String Username
        {
            get { return username; }
            set { username = value; }
        }
        public String Password
        {
            get { return password; }
            set { password = value; }
        }
        public int Tipo
        {
            get { return tipo; }
            set { tipo = value; }
        }
         private string itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 
        /// <summary>
        /// Compares the password string given with the hash retrieved from your database.
        /// </summary>
        /// <param name="password">Plaintext password.</param>
        /// <param name="hash">Hash from a SQL database</param>
        /// <returns>True if the password is correct, False otherwise.</returns>
        public bool phpbbCheckHash(string password, string hash)
        {
            if (hash.Length == 34) return (hashCryptPrivate(ASCIIEncoding.ASCII.GetBytes(password), hash, itoa64) == hash);
            return false;
        }
 
        /// <summary>
        /// This function will return the resulting hash from the password string you specify.
        /// </summary>
        /// <param name="password">String to hash.</param>
        /// <returns>Encrypted hash.</returns>
        /// <remarks>
        /// Although this will return the md5 for an older password, I have not added
        /// support for older passwords, so they will not work with this class unless
        /// I or someone else updates it.
        /// </remarks>
        public string phpbb_hash(string password)
        {
            // Generate a random string from a random number with the length of 6.
            // You could use a static string instead, doesn't matter. E.g.
            // byte[] random = ASCIIEncoding.ASCII.GetBytes("abc123");
            byte[] random = ASCIIEncoding.ASCII.GetBytes(new Random().Next(100000, 999999).ToString());
 
            string hash = hashCryptPrivate(ASCIIEncoding.ASCII.GetBytes(password), hashGensaltPrivate(random, itoa64), itoa64);
 
            if (hash.Length == 34) return hash;
 
            return sMD5(password);
        }
 
        /// <summary>
        /// The workhorse that encrypts your hash.
        /// </summary>
        /// <param name="password">String to be encrypted. Use: ASCIIEncoding.ASCII.GetBytes();</param>
        /// <param name="genSalt">Generated salt.</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>The encrypted hash ready to be compared.</returns>
        /// <remarks>
        /// password:  Saves conversion inside the function, lazy coding really.
        /// genSalt:   Returns from hashGensaltPrivate(random, itoa64);
        /// return:    Compare with phpbbCheckHash(password, hash)
        /// </remarks>
        private string hashCryptPrivate(byte[] password, string genSalt, string itoa64)
        {
            string output = "*";
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            if (!genSalt.StartsWith("$H$")) return output;
            //   $count_log2 = strpos($itoa64, $setting[3]);
            int count_log2 = itoa64.IndexOf(genSalt[3]);
            if (count_log2 < 7 || count_log2 > 30) return output;
 
            int count = 1 << count_log2;
            byte[] salt = ASCIIEncoding.ASCII.GetBytes(genSalt.Substring(4, 8));
 
            if (salt.Length != 8) return output;
 
            byte[] hash = md5.ComputeHash(Combine(salt, password));
 
            do
            {
                hash = md5.ComputeHash(Combine(hash, password));
            } while (count-- > 1);
 
            output = genSalt.Substring(0, 12);
            output += hashEncode64(hash, 16, itoa64);
 
            return output;
        }
 
        /// <summary>
        /// Private function to concat byte arrays.
        /// </summary>
        /// <param name="b1">Source array.</param>
        /// <param name="b2">Array to add to the source array.</param>
        /// <returns>Combined byte array.</returns>
        private byte[] Combine(byte[] b1, byte[] b2)
        {
            byte[] retVal = new byte[b1.Length + b2.Length];
            Array.Copy(b1, 0, retVal, 0, b1.Length);
            Array.Copy(b2, 0, retVal, b1.Length, b2.Length);
            return retVal;
        }
 
        /// <summary>
        /// Encode the hash.
        /// </summary>
        /// <param name="input">The hash to encode.</param>
        /// <param name="count">[This parameter needs documentation].</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>Encoded hash.</returns>
        private string hashEncode64(byte[] input, int count, string itoa64)
        {
            string output = "";
            int i = 0; int value = 0;
 
            do
            {
                value = input[i++];
                output += itoa64[value & 0x3f];
 
                if (i < count) value |= input[i] << 8;
                output += itoa64[(value >> 6) & 0x3f];
                if (i++ >= count)
                    break;
 
                if (i < count) value |= input[i] << 16;
                output += itoa64[(value >> 12) & 0x3f];
                if (i++ >= count)
                    break;
 
                output += itoa64[(value >> 18) & 0x3f];
 
            } while (i < count);
 
            return output;
        }
 
        /// <summary>
        /// Generate salt for hash generation.
        /// </summary>
        /// <param name="input">Any random information.</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>Generated salt string</returns>
        private string hashGensaltPrivate(byte[] input, string itoa64)
        {
            int iteration_count_log2 = 6;
 
            string output = "$H$";
            output += itoa64[Math.Min(iteration_count_log2 + 5, 30)];
            output += hashEncode64(input, 6, itoa64);
 
            return output;
        }
 
        /// <summary>
        /// Returns a hexadecimal string representation for the encrypted MD5 parameter.
        /// </summary>
        /// <param name="password">String to be encrypted.</param>
        /// <returns>String</returns>
        private string sMD5(string password) { return sMD5(password, false); }
 
        /// <summary>
        /// Returns a hexadecimal string representation for the encrypted MD5 parameter.
        /// </summary>
        /// <param name="password">String to be encrypted.</param>
        /// <param name="raw">Whether or not to produce a raw string.</param>
        /// <returns>String</returns>
        private string sMD5(string password, bool raw)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            if (raw) return Encoding.ASCII.GetString(md5.ComputeHash(Encoding.ASCII.GetBytes(password)));
            else return BitConverter.ToString(md5.ComputeHash(Encoding.ASCII.GetBytes(password))).Replace("-", "");
        }
    
   
     }

Hello

Advertisement

Do you have a question or a problem? I don't understand what kind of replies you're wanting.

Hello to all my stalkers.

sorry i forget put my code with changes

i make my game and i want encrypte my password like this $P$DzZ6dPRg/zHF6G3vRHgskT1.FwoX9k/

but my result it is $H$9tUnBmMHAOlbeljxTdJHG/OBfZhstH1


this is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Security;
using System.Net.Sockets;
using System.IO;
namespace TomShane.Neoforce.Central.Code
{
    class Login
    {
       
        public int id_user;
        String username;
        String password;
        public int tipo;
       public int Id
        {

            get { return id_user; }
            set { id_user = value; }
        }
        public String Username
        {
            get { return username; }
            set { username = value; }
        }
        public String Password
        {
            get { return password; }
            set { password = value; }
        }
        public int Tipo
        {
            get { return tipo; }
            set { tipo = value; }
        }
         private string itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 
        /// <summary>
        /// Compares the password string given with the hash retrieved from your database.
        /// </summary>
        /// <param name="password">Plaintext password.</param>
        /// <param name="hash">Hash from a SQL database</param>
        /// <returns>True if the password is correct, False otherwise.</returns>
        public bool phpbbCheckHash(string password, string hash)
        {
            if (hash.Length == 34) return (hashCryptPrivate(ASCIIEncoding.ASCII.GetBytes(password), hash, itoa64) == hash);
            return false;
        }
 
        /// <summary>
        /// This function will return the resulting hash from the password string you specify.
        /// </summary>
        /// <param name="password">String to hash.</param>
        /// <returns>Encrypted hash.</returns>
        /// <remarks>
        /// Although this will return the md5 for an older password, I have not added
        /// support for older passwords, so they will not work with this class unless
        /// I or someone else updates it.
        /// </remarks>
        public string phpbb_hash(string password)
        {
            // Generate a random string from a random number with the length of 6.
            // You could use a static string instead, doesn't matter. E.g.
            // byte[] random = ASCIIEncoding.ASCII.GetBytes("abc123");
            byte[] random = ASCIIEncoding.ASCII.GetBytes(new Random().Next(100000, 999999).ToString());
 
            string hash = hashCryptPrivate(ASCIIEncoding.ASCII.GetBytes(password), hashGensaltPrivate(random, itoa64), itoa64);
 
            if (hash.Length == 34) return hash;
 
            return sMD5(password);
        }
 
        /// <summary>
        /// The workhorse that encrypts your hash.
        /// </summary>
        /// <param name="password">String to be encrypted. Use: ASCIIEncoding.ASCII.GetBytes();</param>
        /// <param name="genSalt">Generated salt.</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>The encrypted hash ready to be compared.</returns>
        /// <remarks>
        /// password:  Saves conversion inside the function, lazy coding really.
        /// genSalt:   Returns from hashGensaltPrivate(random, itoa64);
        /// return:    Compare with phpbbCheckHash(password, hash)
        /// </remarks>
        private string hashCryptPrivate(byte[] password, string genSalt, string itoa64)
        {
            string output = "*";
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            if (!genSalt.StartsWith("$H$")) return output;
            //   $count_log2 = strpos($itoa64, $setting[3]);
            int count_log2 = itoa64.IndexOf(genSalt[3]);
            if (count_log2 < 7 || count_log2 > 30) return output;
 
            int count = 1 << count_log2;
            byte[] salt = ASCIIEncoding.ASCII.GetBytes(genSalt.Substring(4, 8));
 
            if (salt.Length != 8) return output;
 
            byte[] hash = md5.ComputeHash(Combine(salt, password));
 
            do
            {
                hash = md5.ComputeHash(Combine(hash, password));
            } while (count-- > 1);
 
            output = genSalt.Substring(0, 12);
            output += hashEncode64(hash, 16, itoa64);
 
            return output;
        }
 
        /// <summary>
        /// Private function to concat byte arrays.
        /// </summary>
        /// <param name="b1">Source array.</param>
        /// <param name="b2">Array to add to the source array.</param>
        /// <returns>Combined byte array.</returns>
        private byte[] Combine(byte[] b1, byte[] b2)
        {
            byte[] retVal = new byte[b1.Length + b2.Length];
            Array.Copy(b1, 0, retVal, 0, b1.Length);
            Array.Copy(b2, 0, retVal, b1.Length, b2.Length);
            return retVal;
        }
 
        /// <summary>
        /// Encode the hash.
        /// </summary>
        /// <param name="input">The hash to encode.</param>
        /// <param name="count">[This parameter needs documentation].</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>Encoded hash.</returns>
        private string hashEncode64(byte[] input, int count, string itoa64)
        {
            string output = "";
            int i = 0; int value = 0;
 
            do
            {
                value = input[i++];
                output += itoa64[value & 0x3f];
 
                if (i < count) value |= input[i] << 8;
                output += itoa64[(value >> 6) & 0x3f];
                if (i++ >= count)
                    break;
 
                if (i < count) value |= input[i] << 16;
                output += itoa64[(value >> 12) & 0x3f];
                if (i++ >= count)
                    break;
 
                output += itoa64[(value >> 18) & 0x3f];
 
            } while (i < count);
 
            return output;
        }
 
        /// <summary>
        /// Generate salt for hash generation.
        /// </summary>
        /// <param name="input">Any random information.</param>
        /// <param name="itoa64">The itoa64 string.</param>
        /// <returns>Generated salt string</returns>
        private string hashGensaltPrivate(byte[] input, string itoa64)
        {
            int iteration_count_log2 = 6;
 
            string output = "$H$";
            output += itoa64[Math.Min(iteration_count_log2 + 5, 30)];
            output += hashEncode64(input, 6, itoa64);
 
            return output;
        }
 
        /// <summary>
        /// Returns a hexadecimal string representation for the encrypted MD5 parameter.
        /// </summary>
        /// <param name="password">String to be encrypted.</param>
        /// <returns>String</returns>
        private string sMD5(string password) { return sMD5(password, false); }
 
        /// <summary>
        /// Returns a hexadecimal string representation for the encrypted MD5 parameter.
        /// </summary>
        /// <param name="password">String to be encrypted.</param>
        /// <param name="raw">Whether or not to produce a raw string.</param>
        /// <returns>String</returns>
        private string sMD5(string password, bool raw)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            if (raw) return Encoding.ASCII.GetString(md5.ComputeHash(Encoding.ASCII.GetBytes(password)));
            else return BitConverter.ToString(md5.ComputeHash(Encoding.ASCII.GetBytes(password))).Replace("-", "");
        }
    
   
     }

for the example the maria make login with username maria and password 123456 and the cliente incripte my password and send it to server

but i can´t have the same password everytime change when send to the server

Hello

I don't really understand your question, but I'll explain this in general.

There are two parts to this. First is account setup:
  • User creates an account somehow, or is changing an existing account
  • Username and password are securely submitted via SSL to the server
  • Server generates a large random string called a "salt" for this user
  • The salt and user password are concatenated and hashed using a secure algorithm (e.g. bcrypt)
  • Username, salt and hashed password are saved into the database
I'm ignoring email authentication and other common steps here, and focusing on the credentials.

Then, when a client wants to authenticate:
  • Client uses SSL to securely send credentials to the server
  • Server checks if this username has had many recent failed logins (e.g. > 3 in ten minutes)
  • If so, an error message is displayed
  • Otherwise, server uses the username to lookup the hashed password and "salt" value
  • If this record is not found, a generic "Incorrect username or password" message is displayed
  • Client submitted password and the salt in the database are concatenated and hashed using the secure hashing algorithm
  • If the hash output matches the existing salt in the database, the client is authenticated as that user
  • Otherwise the same generic error message is displayed and the failed login attempt is recorded
An important objective here is to give a potential attacker no information about which usernames are valid.

Other protection mechanisms can be used such as detecting patterns of failed login attempts on different usernames from a particular IP address, and blocking further attempts (e.g. trying a common password such as "password1" on lots of users).

Obviously, the usual precautions against SQL injection are applied at any step that accesses the database.

for now i testing the incrypation in side of server but when is work i gonna put in cliente side and the server confirms if password is correct our wrong but i can put like this

for example i put a password like 123456 and the hash is $P$DzZ6dPRg/zHF6G3vRHgskT1.FwoX9k/

i put the same password and give-me this $H$9tUnBmMHAOlbeljxTdJHG/OBfZhstH1

Hello

So...

first things first:

MD5 is not a cryptographically secure method of hashing passwords. Additionally, using Random() to generate a salt is ALSO not cryptographically secure. I highly recommend you read this.

As for why your hashes aren't matching, are you ensuring that you're passing the same random number each time (i.e. the salt)?

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

how i fix to put my hashes math with my password it is in database

i think send hash my password and send it with ssl connection

Hello

how i fix to put my hashes math with my password it is in database
i think send hash my password and send it with ssl connection


Just send the raw password over SSL.

On the server side, you are either (a) setting up a new password or (b) logging in with an existing password.

For (a), get the new password, generate a salt, hash the salt+password, and store the salt and hash in the database (possibly as two totally separate fields).

For (b), get the incoming password, read the existing salt and hash, hash the salt+password, and compare the newly computed hash with the one from the DB.

That's it.

This is a solved problem. Don't try to invent your own clever changes. You _will_ end up making an insecure and easily-cracked system. Follow existing practice as laid out in articles like http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right, which includes C# sample source.

Sean Middleditch – Game Systems Engineer – Join my team!


This is a solved problem. Don't try to invent your own clever changes. You _will_ end up making an insecure and easily-cracked system. Follow existing practice as laid out in articles like http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right, which includes C# sample source.

The sample code needs to do far more iterations to offer any kind of protection (and the salt is too long, 16 bytes will do just fine). Other than that, decent article, and covers the main points. And, yes, sending the raw password over SSL is probably the right thing to do. You could argue that someone with access to the server could listen in to the passwords, but if they have access to that they can already get all the data they need from the server itself without needing your password. And if you are concerned about the attacker knowing your password beyond the contents stored on that server, it means you're reusing it somewhere else, which you should know by now is a very good thing to do (and since most websites do not do it, there is little advantage of doing it and it's just one more thing that can go wrong).

SSL might not be pretty or confidence-inspiring but it's reasonably secure when used correctly and is still the best there is in terms of browser-supported standards, and as we all know, standards are a good thing, because it's good when things work properly all the time without needing further work. So, until a new improved standard comes along, be industry-standard like everybody else and just use it. Doing that also covers your ass in case your users' credentials are leaked, though this may not be as relevant for a game server.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

the problem i using the database of joomla

i can´t put my password be the same it is in database of joomla 2.5.22

i want hash my password in client side and send to server verify a hash is the same i have in database

Hello

This topic is closed to new replies.

Advertisement