Converted some PHP functions to c# but getting different results

Posted by Tom Beech on Stack Overflow See other posts from Stack Overflow or by Tom Beech
Published on 2013-06-27T16:07:10Z Indexed on 2013/06/27 16:21 UTC
Read the original article Hit count: 242

Filed under:
|

With a bit of help from people on here, i've converted the following PHP functions to C# - But I get very different results between the two and can't work out where i've gone wrong:

PHP:

  function randomKey($amount)
        {
                $keyset  = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                $randkey = "";
                for ($i=0; $i<$amount; $i++)
                        $randkey .= substr($keyset, rand(0, strlen($keyset)-1), 1);
                return $randkey;       
        }

        public static function hashPassword($password)
        {
                $salt = self::randomKey(self::SALTLEN);
                $site = new Sites();
                $s = $site->get();
                return self::hashSHA1($s->siteseed.$password.$salt.$s->siteseed).$salt;
        }

c#

public static string randomKey(int amount)
        {
            string keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string randkey = string.Empty;
            Random random = new Random();

            for (int i = 0; i < amount; i++)
            {
                randkey += keyset.Substring(0, random.Next(2, keyset.Length - 2));
            }

            return randkey;
        }

        static string hashPassword(string password)
        {
            string salt = randomKey(4);
            string siteSeed = "6facef08253c4e3a709e17d9ff4ba197";
            return CalculateSHA1(siteSeed + password + salt + siteSeed) + siteSeed;
        }


        static string CalculateSHA1(string ipString)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] ipBytes = Encoding.Default.GetBytes(ipString.ToCharArray());
            byte[] opBytes = sha1.ComputeHash(ipBytes);

            StringBuilder stringBuilder = new StringBuilder(40);
            for (int i = 0; i < opBytes.Length; i++)
            {
                stringBuilder.Append(opBytes[i].ToString("x2"));
            }

            return stringBuilder.ToString();
        }

EDIT The string 'password' in the PHP function comes out as

"d899d91adf31e0b37e7b99c5d2316ed3f6a999443OZl" 

in the c# it comes out as:

"905d25819d950cf73f629fc346c485c819a3094a6facef08253c4e3a709e17d9ff4ba197"

© Stack Overflow or respective owner

Related posts about c#

Related posts about php