SHA1 with salt on windows phone 7

偶尔善良 提交于 2019-12-12 13:18:23

问题


I have some some time now reshearchd how to encode a password to SHA1 with a salt.

The is the code i used on my web application part, but it will not work on a phone environment.

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:


Silverlight and Windows Phone 7 do not have an ASCIIEncoding. I suggest you use the UTF8Encoding instead. If you are certain that your passwords are always within the ASCII range then this encoding will work the same as the ASCIIEncoding would of had it been present.

If on the other hand you cannot guarantee that passwords are always within the ASCII range then you would need to make sure both ends hash using the UTF8Encoding to ensure generated hashs are the same.



来源:https://stackoverflow.com/questions/6485758/sha1-with-salt-on-windows-phone-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!