2

I'm trying to replicate a php login in c# - but my php is failing me, i'm just not good enough to work out how to do the equivalent in c#.

My php classes are:

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; 
}

I had a good crack at the first with:

public static string randomKey(string amount)
    {
        string keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        string randKey = "";
          for (int i=0; i < amount; i++)
                {
                    randKey = randKey + 
                }

    }

But I can't work out what the equivalent functions are. Any help really will be appreciated.

Edit: You guys have been absolutely amazing. I have one more if you don't mind. Sorry if i'm asking too much:

public static function checkPassword($password, $hash)
    {
        $salt = substr($hash, -self::SALTLEN);
        $site = new Sites();
        $s = $site->get();
        return self::hashSHA1($s->siteseed.$password.$salt.$s->siteseed) === substr($hash, 0, self::SHA1LEN);
    }
4

2 回答 2

1
static string Sha1(string password)
{
    SHA1 sha1 = new SHA1CryptoServiceProvider();
    byte[] data = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
    StringBuilder sb = new StringBuilder();
    foreach (byte b in data)
        sb.Append(b.ToString("x2"));
    return sb.ToString();
}


static string RandomKey(uint amaunt)
{
    const string keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    StringBuilder sb = new StringBuilder((int)amaunt, (int)amaunt);
    Random rnd = new Random();
    for (uint i = 0; i < amaunt; i++)
        sb.Append(keyset[rnd.Next(keyset.Length)]);
    return sb.ToString();
}
于 2013-06-27T13:56:32.277 回答
0
    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;
    }
于 2013-06-27T14:02:12.743 回答