请帮忙。我需要将3个值传递给Web服务:
RptDate(string)
,UserID(string)
,PassHash(base64Binary)
这个PassHash
正是给我带来问题的,因为 PassHash应该是UserID和Password连接在一起(UserIDPassword
),然后计算这个值的二进制MD5哈希,然后将此哈希值转换为Base64解码字符串。下面的我的C#代码显示了我到目前为止所拥有的一个示例。
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();
}
这是构建超链接的the result。
当我提交此链接时,它声明我有一个“无效密码哈希值”。是不是应该有PassHash
而不是System.Byte[]
的值?我在这里做错了什么?
答案 0 :(得分:1)
您需要获取字节数组并将其转换为base64字符串,因为字节数组不具有.ToString()
方法给出的有效表示。
您可以使用以下方法执行此操作:
var passwordHashInBase64 = System.Convert.ToBase64String(ph1);
然后只需将passwordHashInBase64
传递给您的字符串构建器,而不是ph1
。
编辑:
仔细查看您的代码,似乎您在这里采取了额外的步骤。在你的getMd5Hash2函数中,在这一行之后:
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
添加
return System.Convert.ToBase64String(data);
并删除stringbuilder /十六进制表示。
然后,在提交事件中,不要担心从hashed
获取字节,只需将该字符串作为哈希值传递。
sb.AppendFormat("https://ExampleService/GetRptLength?ReportDate={0}&UserID={1}&PassHash={2}", ReportDate, UnameVal, hashed);