Connell.O'Donnell
Connell.O'Donnell

Reputation: 3723

Password hashing in UWP

I have the following code in .net framework.

public string GetHashedPassword(string password, string salt)
    {
        byte[] saltArray = Convert.FromBase64String(salt);
        byte[] passArray = Convert.FromBase64String(password);
        byte[] salted = new byte[saltArray.Length + passArray.Length];
        byte[] hashed = null;

        saltArray.CopyTo(salted, 0);
        passArray.CopyTo(salted, saltArray.Length);

        using (var hash = new SHA256Managed())
        {
            hashed = hash.ComputeHash(salted);
        }

        return Convert.ToBase64String(hashed);
    }

I'm trying to create an equivalent in .net core for a UWP application. Here's what I have so far.

public string GetHashedPassword(string password, string salt)
  {
        IBuffer input = CryptographicBuffer.ConvertStringToBinary(password + salt, BinaryStringEncoding.Utf8);
        var hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
        var hash = hashAlgorithm.HashData(input);

        //return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hash);
    }

The last line, converting the buffer back to a string doesn't work. I get this exception:

No mapping for the Unicode character exists in the target multi-byte code page.

How can I convert the buffer back into a string?

Upvotes: 0

Views: 580

Answers (1)

TheTanic
TheTanic

Reputation: 1638

I am assuming, that you want to get the hashed password in a base64-format, because you did that in your .net example.
To get this, change:

CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, hash);

to:

CryptographicBuffer.EncodeToBase64String(hash);

So the complete method looks like this:

public string GetHashedPassword(string password, string salt)
        {

            IBuffer input = CryptographicBuffer.ConvertStringToBinary(password + salt, BinaryStringEncoding.Utf8);
            var hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            var hash = hashAlgorithm.HashData(input);

            return CryptographicBuffer.EncodeToBase64String(hash);
        }

Upvotes: 1

Related Questions