C# SHA-1 与 PHP SHA-1...结果不同?

发布于 2024-07-18 04:47:39 字数 891 浏览 9 评论 0原文

我正在尝试从字符串计算 SHA-1 哈希值,但是当我使用 php 的 sha1 函数计算字符串时,我得到的结果与在 C# 中尝试时不同。 我需要 C# 来计算与 PHP 相同的字符串(因为来自 php 的字符串是由我无法修改的第 3 方计算的)。 如何让 C# 生成与 PHP 相同的哈希值? 谢谢!!!

String = [email protected]

C# 代码(生成 d32954053ee93985f5c3ca2583145668bb7 ade86)

        string encode = secretkey + email;
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] HashValue, MessageBytes = UE.GetBytes(encode);
        SHA1Managed SHhash = new SHA1Managed();
        string strHex = "";

        HashValue = SHhash.ComputeHash(MessageBytes);
        foreach(byte b in HashValue) {
            strHex += String.Format("{0:x2}", b);
        }

PHP 代码(生成a9410edeaf75222d7b576c1b23ca0a9af0dffa98)

sha1();

I am trying to calculate a SHA-1 Hash from a string, but when I calculate the string using php's sha1 function I get something different than when I try it in C#. I need C# to calculate the same string as PHP (since the string from php is calculated by a 3rd party that I cannot modify). How can I get C# to generate the same hash as PHP? Thanks!!!

String = [email protected]

C# Code (Generates d32954053ee93985f5c3ca2583145668bb7ade86)

        string encode = secretkey + email;
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] HashValue, MessageBytes = UE.GetBytes(encode);
        SHA1Managed SHhash = new SHA1Managed();
        string strHex = "";

        HashValue = SHhash.ComputeHash(MessageBytes);
        foreach(byte b in HashValue) {
            strHex += String.Format("{0:x2}", b);
        }

PHP Code (Generates a9410edeaf75222d7b576c1b23ca0a9af0dffa98)

sha1();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

终陌 2024-07-25 04:47:39

使用 ASCIIEncoding 而不是 UnicodeEncoding。 PHP 使用 ASCII 字符集进行哈希计算。

Use ASCIIEncoding instead of UnicodeEncoding. PHP uses ASCII charset for hash calculations.

灼痛 2024-07-25 04:47:39

.NET中的这个方法相当于php中的sha1:

string sha1Hash(string password)
{
    return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}

This method in .NET is equivalent to sha1 in php:

string sha1Hash(string password)
{
    return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}
千纸鹤带着心事 2024-07-25 04:47:39

我也有这个问题。 以下代码将起作用。

string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();

I had this problem also. The following code will work.

string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();
夜还是长夜 2024-07-25 04:47:39

有同样的问题。 这段代码对我有用:

string encode = secretkey + email;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] encodeBytes = Encoding.ASCII.GetBytes(encode);
byte[] encodeHashedBytes = sha1.ComputeHash(passwordBytes);
string pencodeHashed = BitConverter.
ToString(encode HashedBytes).Replace("-", "").ToLowerInvariant();

Had the same problem. This code worked for me:

string encode = secretkey + email;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] encodeBytes = Encoding.ASCII.GetBytes(encode);
byte[] encodeHashedBytes = sha1.ComputeHash(passwordBytes);
string pencodeHashed = BitConverter.
ToString(encode HashedBytes).Replace("-", "").ToLowerInvariant();
梦魇绽荼蘼 2024-07-25 04:47:39

FWIW,我在 Java 中遇到了类似的问题。 事实证明,我必须使用“UTF-8”编码在 Java 中生成与 PHP 5.3.1(在 XAMPP Vista 上运行)中生成的 sha1 函数相同的 SHA1 哈希值。

    private static String SHA1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("UTF-8"));
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(md.digest()));
    }

FWIW, I had a similar issue in Java. It turned out that I had to use "UTF-8" encoding to produce the same SHA1 hashes in Java as the sha1 function produces in PHP 5.3.1 (running on XAMPP Vista).

    private static String SHA1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("UTF-8"));
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(md.digest()));
    }
入怼 2024-07-25 04:47:39

尝试以下方法! 我认为它会很好用:

public static string SHA1Encodeb64(string toEncrypt)
    {
        //Produce an array of bytes which is the SHA1 hash
        byte[] sha1Signature = new byte[40];

        byte[] sha = System.Text.Encoding.Default.GetBytes(toEncrypt);
        SHA1 sha1 = SHA1Managed.Create();
        sha1Signature = sha1.ComputeHash(sha);


        /**
        * The BASE64 encoding standard's 6-bit alphabet, from RFC 1521,
        * plus the padding character at the end.
        */
        char[] Base64Chars = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/',
            '='
            };
        //Algorithm to encode the SHA1 hash using Base64
        StringBuilder sb = new StringBuilder();
        int len = sha1Signature.Length;
        int i = 0;
        int ival;
        while (len >= 3)
        {
            ival = ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            len -= 3;
            sb.Append(Base64Chars[(ival >> 18) & 63]);
            sb.Append(Base64Chars[(ival >> 12) & 63]);
            sb.Append(Base64Chars[(ival >> 6) & 63]);
            sb.Append(Base64Chars[ival & 63]);
        }
        switch (len)
        {
            case 0: // No pads needed.
                break;
            case 1: // Two more output bytes and two pads.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 16;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[64]);
                sb.Append(Base64Chars[64]);
                break;
            case 2: // Three more output bytes and one pad.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 8;
                ival += ((int)sha1Signature[i] + 256) & 0xff;
                ival <<= 8;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[(ival >> 6) & 63]);
                sb.Append(Base64Chars[64]);
                break;
        }
        //Encode the signature using Base64
        string base64Sha1Signature = sb.ToString();
        return base64Sha1Signature;
    }

Try The following! I think it will work great:

public static string SHA1Encodeb64(string toEncrypt)
    {
        //Produce an array of bytes which is the SHA1 hash
        byte[] sha1Signature = new byte[40];

        byte[] sha = System.Text.Encoding.Default.GetBytes(toEncrypt);
        SHA1 sha1 = SHA1Managed.Create();
        sha1Signature = sha1.ComputeHash(sha);


        /**
        * The BASE64 encoding standard's 6-bit alphabet, from RFC 1521,
        * plus the padding character at the end.
        */
        char[] Base64Chars = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/',
            '='
            };
        //Algorithm to encode the SHA1 hash using Base64
        StringBuilder sb = new StringBuilder();
        int len = sha1Signature.Length;
        int i = 0;
        int ival;
        while (len >= 3)
        {
            ival = ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            len -= 3;
            sb.Append(Base64Chars[(ival >> 18) & 63]);
            sb.Append(Base64Chars[(ival >> 12) & 63]);
            sb.Append(Base64Chars[(ival >> 6) & 63]);
            sb.Append(Base64Chars[ival & 63]);
        }
        switch (len)
        {
            case 0: // No pads needed.
                break;
            case 1: // Two more output bytes and two pads.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 16;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[64]);
                sb.Append(Base64Chars[64]);
                break;
            case 2: // Three more output bytes and one pad.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 8;
                ival += ((int)sha1Signature[i] + 256) & 0xff;
                ival <<= 8;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[(ival >> 6) & 63]);
                sb.Append(Base64Chars[64]);
                break;
        }
        //Encode the signature using Base64
        string base64Sha1Signature = sb.ToString();
        return base64Sha1Signature;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文