zoukankan      html  css  js  c++  java
  • 【转】如何使php的MD5与C#的MD5一致?

    有c#生成MD5的代码如下:

       class CreateMD5
        {
            static void Main(string[] args)
            {
                string source = "提问指南";
                using (MD5 md5Hash = MD5.Create())
                {
                    string hash = GetMd5Hash(md5Hash, source);
    
                    Console.WriteLine( hash);
                }
            }    
            static string GetMd5Hash(MD5 md5Hash, string input)
            {
                //这里是 Unicode
                byte[] data = md5Hash.ComputeHash(Encoding.Unicode.GetBytes(input));
    
                StringBuilder sBuilder = new StringBuilder();
    
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                return sBuilder.ToString();
            }
        }
    

    上述代码生成的MD5是 f5da53705563c657581a6d0853286fdc 现在问题是,c#生成的MD5 与 PHP 生成的MD5 不一致

    由于业务限制,不能更改c#代码,只能从PHP下手。

    回答:

    md5前操作一步

     
    $tmp = mb_convert_encoding('提问指南', 'utf-16le', 'utf8');










    原文:c#兼容 PHP中的md5

    由于工作需要,需要使用C#去对一个php程序做二次开发.在登录验证的时候,发现一个小问题.

    就是用C#写的md5算法得出的结果和php的md5()得出的结果有时候会不一样. 导致有些账号的密码验证不能通过.后来网上找了一下,在国外一个网站上找到了答案.

    C#常用的MD5算法.

    public static string MD5(string password) {
       byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
       try {
          System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
          cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
          byte[] hash = cryptHandler.ComputeHash (textBytes);
          string ret = "";
          foreach (byte a in hash) {
                ret += a.ToString ("x");
          }
          return ret ;
       }
       catch {
          throw;
       } 

    但是此算法与md5()得出的结果是不一样的.后调整为如下,即可以了.

    public static string MD5(string password) {
       byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
       try {
          System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
          cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
          byte[] hash = cryptHandler.ComputeHash (textBytes);
          string ret = "";
          foreach (byte a in hash) {
             if (a<16)
                ret += "0" + a.ToString ("x");
             else
                ret += a.ToString ("x");
          }
          return ret ;
       }
       catch {
          throw;
       } 

  • 相关阅读:
    伪元素:placeholder-shown&&:focus-within
    伪元素:target
    伪元素:focus-within
    MpVue解析
    ESLint在vue中的使用
    vue动态 设置类名
    Java 文件流操作.
    SpringMVC 与 REST.
    基于Nginx和Zookeeper实现Dubbo的分布式服务
    基于Spring的RPC通讯模型.
  • 原文地址:https://www.cnblogs.com/mimime/p/5990394.html
Copyright © 2011-2022 走看看