将两个PHP函数转换为c#

时间:2013-06-27 13:49:53

标签: c# php

我正在尝试在c#中复制一个php登录 - 但是我的php让我失望了,我还不够好,不知道如何在c#中做同等的事情。

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

我在第一次接受了很好的破解:

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

    }

但我无法弄清楚等效功能是什么。任何帮助真的将不胜感激。

编辑:你们真是太棒了。如果你不介意,我还有一个。对不起,如果我问得太多了:

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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;
    }