gpt4 book ai didi

c# - 如何在 C# 中将任意二进制数据输出为字符表示形式?

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:56 29 4
gpt4 key购买 nike

我正在尝试重新创建的功能

slappasswd -h {md5}

在 .Net 上

我在 Perl 上有这段代码

use Digest::MD5;
use MIME::Base64;
$ctx = Digest::MD5->new;
$ctx->add('fredy');
print "Line $.: ", $ctx->clone->hexdigest, "\n";
print "Line $.: ", $ctx->digest, "\n";
$hashedPasswd = '{MD5}' . encode_base64($ctx->digest,'');
print $hashedPasswd . "\n";

我尝试在 VB.Net、C# 等上做同样的事情,但只适用于

$ctx->clone->hexdigest # 结果:b89845d7eb5f8388e090fcc151d618c8

C# 部分使用 MSDN 示例

static string GetMd5Hash(MD5 md5Hash, string input)
{

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}

在控制台应用程序中使用此代码:

 string source = "fredy";
using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, source);

Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");


}

输出:fredy 的 MD5 散列是:b89845d7eb5f8388e090fcc151d618c8。

但是我需要实现$ctx->digest函数,它输出一些二进制数据,比如

¸∼E×ë_ƒˆàüÁQÖÈ

此输出发生在使用 Perl 的 Linux 和 Windows 上。

有什么想法吗?

谢谢

最佳答案

正如我在上面的评论中所说,您混淆了一些东西。 Perl 中的digest 创建的是一组字节。当这些被打印时,Perl 会自动将它们转换为字符串表示形式,因为(简化)它认为如果您打印东西,它会进入屏幕并且您希望能够阅读它。 C# 不会这样做。这并不意味着 Perl 摘要和 C# 摘要不一样。只是他们的表现形式不同。

如果将它们都转换为十六进制表示,则已经确定它们相等。

现在您需要做些什么才能在 C# 中获得类似于 Perl 在执行此操作时打印的 string 的输出:

print $ctx->digest; # output: ¸˜E×ë_ƒˆàüÁQÖÈ

...就是将C#的byte[]数据转换成字符串。

之前已经回答过,f 或这里的例子:How to convert byte[] to string?

使用该技术,我相信您获取它的函数将如下所示。 请注意,我是一名 Perl 开发人员,我无法对此进行测试。将其视为类似于 C# 的伪代码。

static string GetMd5PerlishString(MD5 md5Hash, string input)
{

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

string result = System.Text.Encoding.UTF8.GetString(data);

return result;
}

现在看起来应该是一样的。


另请注意 MD5 is not a secure hashing algorithm for passwords any more . 请不要存储用它来存储用户密码!

关于c# - 如何在 C# 中将任意二进制数据输出为字符表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31953646/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com