如何在C#中输出任意二进制数据作为字符表示?

时间:2015-08-11 16:09:47

标签: c# perl

我正在尝试重新创建

的功能

slappasswd -h {md5}

<。p> on .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 # result : b89845d7eb5f8388e090fcc151d618c8

使用MSDN示例

参与C#
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 + ".");


        }

输出:The MD5 hash of fredy is: b89845d7eb5f8388e090fcc151d618c8.

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

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

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

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:2)

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

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

现在你需要做些什么来获得C#中的输出,它看起来像Perl在执行此操作时打印的字符串

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

...是将C#byte[] data转换为字符串。

之前已经回答过这个问题,例如: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请不要存储使用它来存储用户密码!

相关问题