Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type string to byte[]

I have a class that encrypts a password with a salted hash.

But If I want to pass a null to the class I get the following error: Cannot implicitly convert type string to byte[]

Here is the class code:

public class MyHash
{
    public static string ComputeHash(string plainText, 
                            string hashAlgorithm, byte[] saltBytes)
    {
        Hash Code
    }
}

When I use the class I get the error: "Cannot implicitly convert type string to byte[]"

//Encrypt Password
byte[] NoHash = null;
byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash);
like image 415
MataHari Avatar asked May 29 '12 02:05

MataHari


People also ask

Can not convert from string to byte in C#?

You can't convert a string to a byte array directly, because a string is (normally) made of unicode characters, which don't "map" directly to single bytes - they are variable length values. string s = ... byte[] bytes = System. Text. Encoding.

Can convert string to byte array C#?

The Encoding. GetBytes() method converts a string into a bytes array. The example below converts a string into a byte array in Ascii format and prints the converted bytes to the console.


1 Answers

This is because your 'ComputeHash' method returns a string, and you are trying to assign this return value to a byte array with;

byte[] encds = MyHash.ComputeHash(Password, "SHA256", NoHash);

There is no implicit converstion for string to byte[] because there exist a number of different encodings to represent a string as bytes, such as ASCII or UTF8.

You need to explicitly convert the bytes using an appropriate encoding class like so;

string x = "somestring";
byte[] y = System.Text.Encoding.UTF8.GetBytes(x);
like image 186
RJ Lohan Avatar answered Sep 27 '22 20:09

RJ Lohan