C#SHA-1与PHP SHA-1 ...不同的结果? [英] C# SHA-1 vs. PHP SHA-1...Different Results?

查看:237
本文介绍了C#SHA-1与PHP SHA-1 ...不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串计算SHA-1散列,但是当我使用PHP的SHA1函数计算字符串我得到的东西比我尝试在C#中的不同。我需要C#来计算相同的字符串作为PHP(因为从PHP字符串是由我不​​能修改第三方计算)。我怎样才能获得C#生成相同的散列为PHP?谢谢!

字符串= s934kladfklada@a.com

C#code(生成d32954053ee93985f5c3ca2583145668bb7ade86)

 字符串连接code = SecretKey的电子邮件+;
        UNI codeEncoding UE =新的Uni codeEncoding();
        字节[]散列值,MessageBytes = UE.GetBytes(EN code);
        SHA1Managed SHhash =新SHA1Managed();
        字符串strHex =;        散列值= SHhash.ComputeHash(MessageBytes);
        的foreach(在散列值BYTE B){
            strHex + =的String.Format({0:X2},B);
        }

PHP code(生成a9410edeaf75222d7b576c1b23ca0a9af0dffa98)

  SHA1();


解决方案

使用ASCIIEncoding,而不是统一codeEncoding。 PHP使用ASCII字符的哈希计算。

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 = s934kladfklada@a.com

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();

解决方案

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

这篇关于C#SHA-1与PHP SHA-1 ...不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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