[英]Equivalent of C# Encoding.UTF8.GetBytes in php
我在 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 和 line sha1Request = shaM.ComputeHash(Encoding.UTF8.GetBytes(request));
字符串转换为字节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 文件中的文字,这取决于文件在磁盘上的存储方式。 (它使用什么字符集)。
如果字符串是从 Web 请求、数据库或读取文件中检索的,这还取决于 Web 表单、数据库或外部文件使用的字符集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.