简体   繁体   English

在C#中生成Unix风格的MD5密码哈希

[英]Generate Unix-Style MD5 Password Hash in C#

I am trying to generate a Unix-Style password hash using MD5. 我正在尝试使用MD5生成Unix样式的密码哈希。 I undestand that I need it to look like $1$<salt>$<hash> , but the <hash> part does not look the same, no matter what I do. 我不知道我需要它看起来像$1$<salt>$<hash> ,但无论我做什么, <hash>部分看起来都不一样。 Here is how I generate the hash: 以下是我生成哈希的方法:

            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(pass);
            byte[] hash = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append((char) hash[i]);
            }

            String calchash = sb.ToString();

I am pretty sure that it is now I am using the StringBuilder to make a string from the hashed bytes. 我很确定现在我正在使用StringBuilder从散列字节中创建一个字符串。 But I don't know what the right settings would be. 但我不知道正确的设置是什么。

Unix md5 crypt doesn't use plain md5. Unix md5 crypt不使用plain md5。 That would be insecure, because plain md5 is fast, and password hashes should be slow. 这将是不安全的,因为普通的md5很快,密码哈希应该很慢。

I found a relevant code-project article: http://www.codeproject.com/KB/recipes/Unix_md5crypt.aspx 我找到了相关的代码项目文章: http//www.codeproject.com/KB/recipes/Unix_md5crypt.aspx

It's about formatting. 这是关于格式化。 The Unix password hash is in hex format, while you're writing it down in binary. Unix密码哈希是十六进制格式,而你用二进制文件写下来。 Replace the loop body with: 用以下方法替换环体:

sb.Append(hash[i].ToString("x").PadLeft(2,'0'));

I think you should use hash[i].ToString("X") instead of just converting to char. 我认为你应该使用hash [i] .ToString(“X”)而不是转换为char。 Because hash bytes may be in any range from 0 to 255, which is not like md5 hash is looking. 因为散列字节可以在0到255的任何范围内,这与md5散列不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM