I need to covert this into c# code. We are trying to securely send packets between servers and clients. We did it using PHP and we tried to covert it into c#. I am new to C# and hard to covert this code.
function createHashedPayload(string $packet, string $secret, string $hash = 'sha256'): string
{
return base64_encode(hash_hmac('sha256', $packet, $secret, true) . $packet);
}
function getVerifiedPayload(string $payload, string $secret, string $hash = 'sha256'): ?string
{
$decoded = base64_decode($payload);
$hashlen = strlen(hash($hash, "test", true)); // Quick method to get hash length
$hmac = substr($decoded, 0, $hashlen); // Get HMAC from start of string
$content = substr($decoded, $hashlen); // Rest of the string is content
// Verify HMAC
$calcmac = hash_hmac($hash, $content, $secret, true);
if (hash_equals($hmac, $calcmac)) {
return $content;
}
return null;
}
I was able to covert the createHashedPayload
static string createHashedPayload(string text, string key)
{
key = key ?? "";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
return Convert.ToBase64String(hash);
}
}
I am trying hard to convert getVerifiedPayload into c#. Can someone help?