Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

php md5 algorithm that gives same result as c#

i have a hashing algorithm in C#, in a nutshell, it is:

string input = "asd";

System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();


byte[] hash = alg.ComputeHash(enc.GetBytes(input));
string output = Convert.ToBase64String(hash);

// outputs:   eBVpbsvxyW5olLd5RW0zDg==
Console.WriteLine(output);

Now I need to replicate this behaviour in php,

$input = "asd";
$output = HashSomething($input);
echo $output;

How can I achieve it?

I checked

  • md5
  • utf8_decode
  • utf8_encode
  • base64_encode
  • base64_decode
  • url_decode

but i noted the php md5 doesn't get the == on the end... what am I missing?

NOTE: I cannot change C# behaviour because it's already implemented and passwords saved in my db with this algorithm.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is PHP's md5() function by default returns the hex variation of the hash where C# is returning the raw byte output that must then be made text safe with base64 encoding. If you are running PHP5 you can use base64_encode(md5('asd', true)). Notice the second parameter to md5() is true which makes md5() return the raw bytes instead of the hex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...