[英]C# sha256 encryption and validating
我需要將其轉換為 c# 代碼。 我們正在嘗試在服務器和客戶端之間安全地發送數據包。 我們使用 PHP 進行了此操作,並嘗試將其轉換為 c#。 我是 C# 的新手,很難隱藏此代碼。
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;
}
我能夠隱藏 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);
}
}
我正在努力將getVerifiedPayload
轉換為 c#。 有人可以幫忙嗎?
您可以使用 System.Security.Cryptography 使用密鑰加密字符串,這是您需要的方法
public static string Encrypt(string plainText, string password)
{
if (plainText == null)
{
return null;
}
if (password == null)
{
password = String.Empty;
}
// Get the bytes of the string
var bytesToBeEncrypted = Encoding.UTF8.GetBytes(plainText);
var passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
var bytesEncrypted = Cipher.Encrypt(bytesToBeEncrypted, passwordBytes);
return Convert.ToBase64String(bytesEncrypted);
}
並用於解密
public static string Decrypt(string encryptedText, string password)
{
if (encryptedText == null)
{
return null;
}
if (password == null)
{
password = String.Empty;
}
// Get the bytes of the string
var bytesToBeDecrypted = Convert.FromBase64String(encryptedText);
var passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
var bytesDecrypted = Cipher.Decrypt(bytesToBeDecrypted, passwordBytes);
return Encoding.UTF8.GetString(bytesDecrypted);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.