我有一个 C# 示例,必须用 PHP 编写。
request = request.Replace(sign, string.Empty);
byte[] sha1Request;
using (var shaM = new SHA1Managed())
{
sha1Request = shaM.ComputeHash(Encoding.UTF8.GetBytes(request));
}
log.InfoFormat($"request={request}. sha1Request={Convert.ToBase64String(sha1Request)}. Sign={sign}", request, Convert.ToBase64String(sha1Request));
var pubKey = (RSACryptoServiceProvider)FrontInterface.GetCertificate(checkFrontCertificateCod.Value).PublicKey.Key;
var isValid = pubKey.VerifyData(Encoding.UTF8.GetBytes(Convert.ToBase64String(sha1Request)), new SHA1CryptoServiceProvider(), Convert.FromBase64String(sign));
if (!isValid)
{
throw new Exception("Wrong digital sign");
}
因此,我可能不会在 php 和行 sha1Request = shaM.ComputeHash(Encoding.UTF8.GetBytes(request));
中将字符串转换为字节
将在 PHP 中:sha1Request =sha1(request, true);
我说得对吗?如果没有,请帮我在 PHP 中转换这一行。
非常感谢。
最佳答案
请注意,sha1 不应再用于与安全相关的应用程序,它已经过时了。
C#版本:
string text = "<Hällo World>";
byte[] sha1;
using (var shaM = new SHA1Managed())
{
sha1 = shaM.ComputeHash(Encoding.UTF8.GetBytes(text));
}
string encoded = Convert.ToBase64String(sha1);
Console.Write(encoded);
PHP 版本:
$text = "<Hällo World>";
// Encode as UTF8 if necessary (May not be necessary if string is already utf-8)
$text = utf8_encode($text);
// Calculate SHA1
$sha1 = sha1($text, TRUE);
// Convert to Base64
$encoded = base64_encode($sha1);
echo($encoded);
两个版本都应该输出
1nSiStZRa/quRru7Sqe+ejupqfs=
请注意,仅当您使用的字符串实际上尚未以 utf8 编码时,才应调用 utf8_encode
。
如果字符串是 *.php 文件中的文字,这取决于文件在磁盘上的存储方式。 (它使用什么字符集)。
如果字符串是从网络请求、数据库或读取文件中检索到的,这还取决于网络表单、数据库或外部文件使用的字符集。
关于c# - 等同于 PHP 中的 C# Encoding.UTF8.GetBytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52309060/