SHA1 с солью на Windows Phone 7 - PullRequest
3 голосов
/ 26 июня 2011

У меня есть время, чтобы узнать, как кодировать пароль для SHA1 с помощью соли.

Это код, который я использовал в своей части веб-приложения, но он не будет работать в телефонной среде.

public class Password
{
    private string _password;
    private int _salt;

    public Password(string strPassword, int nSalt)
    {
        _password = strPassword;
        _salt = nSalt;
    }

    public string ComputeSaltedHash()
    {
        // Create Byte array of password string
        ASCIIEncoding encoder = new ASCIIEncoding();
        Byte[] _secretBytes = encoder.GetBytes(_password);

        // Create a new salt
        Byte[] _saltBytes = new Byte[4];
        _saltBytes[0] = (byte)(_salt >> 24);
        _saltBytes[1] = (byte)(_salt >> 16);
        _saltBytes[2] = (byte)(_salt >> 8);
        _saltBytes[3] = (byte)(_salt);

        // append the two arrays
        Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
        Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
        Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

        SHA1 sha1 = SHA1.Create();
        Byte[] computedHash = sha1.ComputeHash(toHash);

        return encoder.GetString(computedHash);
    }

    public static int CreateRandomSalt()
    {
        Byte[] _saltBytes = new Byte[4];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(_saltBytes);

        return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
            (((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
    }

    public static string CreateRandomPassword(int PasswordLength)
    {
        String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!\"#¤%&/()=?$+-_.,;'*";
        Byte[] randomBytes = new Byte[PasswordLength];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
        }

        return new string(chars);
    }
}

1 Ответ

3 голосов
/ 26 июня 2011

Silverlight и Windows Phone 7 не имеют ASCIIEncoding.Я предлагаю вам использовать UTF8Encoding вместо.Если вы уверены, что ваши пароли всегда находятся в диапазоне ASCII, то эта кодировка будет работать так же, как если бы она присутствовала ASCIIEncoding.

Если, с другой стороны, вы не можете гарантировать, что пароли всегдав пределах диапазона ASCII вам необходимо убедиться, что оба конца хэша, используя UTF8Encoding, гарантируют, что сгенерированные хэши совпадают.

...