Reputation: 43
Please help. I need to pass 3 values to a webservice:
RptDate(string)
,UserID(string)
,PassHash(base64Binary)
This PassHash
is what's giving me the problem, because PassHash is supposed to be the UserID and Password concatenated together(UserIDPassword
), then calculating a binary MD5 hash of this value, then converting this hash value to a Base64 decoded string. My C# code below shows an example of what I have so far.
protected void btnSubmit_Click(object sender, EventArgs e) {
string UnameVal = "BSimpson";
string PwordVal = "Springfield";
string ReportDate = "2015-12-25";
string source = string.Concat(UnameVal, PwordVal);
string hashed = getMd5Hash2(source);
byte[] ph1 = System.Text.Encoding.UTF8.GetBytes(hashed);
//Build Hyperlink...
var sb = new StringBuilder();
sb.AppendFormat("https://ExampleService/GetRptLength?ReportDate={0}&UserID={1}&PassHash={2}", ReportDate, UnameVal, ph1);
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = sb.ToString();
}
static string getMd5Hash2(string input) {
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
Here is the result of building the hyperlink.
When I submit this link, it states that I have an "Invalid Password Hash Value". Isn't there supposed to be a value for PassHash
instead of just System.Byte[]
? What am I doing wrong here?
Upvotes: 2
Views: 661
Reputation: 9704
You'll need to take your byte array and convert it to a base64 string, as a byte array won't have a valid representation given by it's .ToString()
method.
You can do this with the following:
var passwordHashInBase64 = System.Convert.ToBase64String(ph1);
Then just pass the passwordHashInBase64
to your string builder instead of ph1
.
Edit:
Looking more closely at your code, it seems like you're taking an extra step in general here. In your getMd5Hash2 function, after this line:
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
add
return System.Convert.ToBase64String(data);
and remove the stringbuilder/hexadecimal representation.
Then, in your submit event, don't worry about getting the bytes from hashed
and just pass in that string as your hash value.
sb.AppendFormat("https://ExampleService/GetRptLength?ReportDate={0}&UserID={1}&PassHash={2}", ReportDate, UnameVal, hashed);
Upvotes: 1