[英]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.