Search code examples
asp.netasp.net-mvcasp.net-webpageswebmatrix-2webmatrix-3

How to convert request querystring to HMACSHA256 in webmatrix


The below code doesnt work in webmatrix... (Only the kvps part is not working)

@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Web;
@using System.Configuration;
@using System.Text.RegularExpressions;
@using System.Collections.Specialized;
@using System.Security.Cryptography;
@using System.Text;
@using Newtonsoft.Json;

@{
    Func<string, bool, string> replaceChars = (string s, bool isKey) =>
    {
        string output = (s.Replace("%", "%25").Replace("&", "%26")) ?? "";

        if (isKey)
        {
            output = output.Replace("=", "%3D");
        }

        return output;
    };
//This part is not working...
    var kvps = Request.QueryString.Cast<string>()
    .Select(s => new { Key = replaceChars(s, true), Value = replaceChars(Request.QueryString[s], false) })
    .Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
    .OrderBy(kvp => kvp.Key)
    .Select(kvp => "{kvp.Key}={kvp.Value}");

var hmacHasher = new HMACSHA256(Encoding.UTF8.GetBytes((string)AppState["secretKey"]));
var hash = hmacHasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("&", kvps)));
var calculatedSignature = BitConverter.ToString(hash).Replace("-", "");

}

the same code works well in visual studio mvc app. the only change is the "$" sign in the kvps variable... when $ is added in webmatrix, it gives a squiggly red color underline

var kvps = Request.QueryString.Cast<string>()
.Select(s => new { Key = replaceChars(s, true), Value = replaceChars(Request.QueryString[s], false) })
.Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
.OrderBy(kvp => kvp.Key)
.Select(kvp => $"{kvp.Key}={kvp.Value}");

Solution

  • The $ is new in C# 6.0. It's an operator for string interpolation. So, something like:

    $"{kvp.Key}={kvp.Value}"
    

    Means to literally replace kvp.Key and kvp.Value with the values of those identifiers within the string. In lesser versions of C#, you'd need to do:

    String.Format("{0}={1}", kvp.Key, kvp.Value)