与PHP的sha1()相比,sha1函数 [英] sha1 function compared to php's sha1()

查看:128
本文介绍了与PHP的sha1()相比,sha1函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

C#中是否有任何方法可以输出与php sha1()相同的结果.

http://se2.php.net/manual/en/function.sha1.php [ ^ ]

我正在使用以下代码,但哈希值与使用php's sha1()创建的代码不同.

Hey guys,

Is there any method in c# that would output the same result as the php sha1().

http://se2.php.net/manual/en/function.sha1.php[^]

I am using the follwing code but the hash differs with the one created with php''s sha1().

namespace sha1
{
    class toSha1
    {
        public string Sha1Sum(string strToEncrypt)
        {
            UTF8Encoding ue = new UTF8Encoding();
            byte[] bytes = ue.GetBytes(strToEncrypt);

            // encrypt bytes
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] hashBytes = sha.ComputeHash(bytes);

            // Convert the encrypted bytes back to a string (base 16)
            string hashString = "";

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
            }

            return hashString.PadLeft(32, '0');
        }
    }
}

推荐答案

要做的第一件事是检查您提供的输入是否完全相同: C#通过UTF8设置了一个已知字节值的数组,并将其提供给两个系统.

如果输出仍然不同,则比较它们的长度.如果它们不相同,则您需要查看实际输出并确定每个函数实际生成的内容,因为SHA1哈希值是非常特定的位数,长度为160,但是有更长的变体,最高为1024位在管道中,我通常将512位SHA值用于安全系统.

您可能会发现一个输出打包为20个字节,另一个输出编码为40个十六进制字符的字符串.
The first thing to do is to check that you are providing exactly the same input: Instead of doing a string-to-bytes conversion in C#, via UTF8, set up an array of known byte values and feed it to both systems.

If the outputs are still different, compare them for length. If they are not the same, them you need to look at the actual output and decide what each function is actually generating, as the SHA1 hash value is a very specific number of bits long - 160 - but there are longer variants up to 1024 bits in the pipeline and I generally use 512 bit SHA values for secure systems.

You will probably find that one output is packed into 20 bytes, and the other is encoded as a string of 40 hexadecimal characters.


这篇关于与PHP的sha1()相比,sha1函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆