我有一个 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");
}
Run Code Online (Sandbox Code Playgroud)
所以,我可能不会在 php 中将字符串转换为字节,而sha1Request = shaM.ComputeHash(Encoding.UTF8.GetBytes(request));
行将在 PHP 中:sha1Request =sha1(request, true);
我说得对吗?如果没有,请帮我将这一行转换为 PHP。多谢。
请注意,sha1 不应该再用于安全相关的应用程序,它已经过时了。
\n\nC# 版本:
\n\nstring text = "<H\xc3\xa4llo World>";\n\nbyte[] sha1;\nusing (var shaM = new SHA1Managed())\n{\n sha1 = shaM.ComputeHash(Encoding.UTF8.GetBytes(text));\n}\nstring encoded = Convert.ToBase64String(sha1);\n\nConsole.Write(encoded);\nRun Code Online (Sandbox Code Playgroud)\n\nPHP 版本:
\n\n$text = "<H\xc3\xa4llo World>";\n\n// Encode as UTF8 if necessary (May not be necessary if string is already utf-8)\n$text = utf8_encode($text);\n\n// Calculate SHA1 \n$sha1 = sha1($text, TRUE);\n\n// Convert to Base64\n$encoded = base64_encode($sha1);\n\necho($encoded);\nRun Code Online (Sandbox Code Playgroud)\n\n两个版本都应该输出
\n\n\n\n\n1nSiStZRa/quRru7Sqe+ejupqfs=
\n
请注意,utf8_encode仅当您使用的字符串实际上尚未以 utf8 编码时,才应进行调用。
如果字符串是 *.php 文件中的文字,则这取决于文件在磁盘上的存储方式。(它使用什么字符集)。
\n\n如果字符串是从 Web 请求、数据库或读取文件中检索的,则这还取决于 Web 表单、数据库或外部文件使用的字符集。
\n