前同事,在網上拷貝一個PHP加解密算法(具體出處也不知道在哪裏呢)php
用於微信註冊加密openid,如今這邊一新同事(.net同事)重構微信開發,要傳遞openid過來。要模擬PHP的算法重寫一個。中間主要出現的問題php的chr與c#的chr解析不同,轉換幾回也不行,,md5也要重構一下,最後由.net大牛搞定。記錄一下,方便後面使用算法
PHP加密碼與解密代碼以下:
c#
function _Encrypt($string,$operation,$key='') { $key=md5($key); $key_length=strlen($key); $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string; $string_length=strlen($string); $rndkey=$box=array(); $result=''; for($i=0;$i<=255;$i++) { $rndkey[$i]=ord($key[$i%$key_length]); $box[$i]=$i; } for($j=$i=0;$i<256;$i++) { $j=($j+$box[$i]+$rndkey[$i])%256; $tmp=$box[$i]; $box[$i]=$box[$j]; $box[$j]=$tmp; } for($a=$j=$i=0;$i<$string_length;$i++) { $a=($a+1)%256; $j=($j+$box[$a])%256; $tmp=$box[$a]; $box[$a]=$box[$j]; $box[$j]=$tmp; $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256])); } if($operation=='D') { if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)) { return substr($result,8); } else { return''; } } else { return str_replace('=','',base64_encode($result)); } }
C#代碼以下:微信
public static string Md5(string str) { byte[] b = Encoding.UTF8.GetBytes(str); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = string.Empty; for (int i = 0; i < b.Length; i++) { ret += b[i].ToString("x").PadLeft(2, '0'); } return ret; } public static string Encrypt(string str, char operation, string key) { key = Md5(key); var key_length = key.Length; str = operation == 'D' ? Encoding.UTF8.GetString(Convert.FromBase64String(str)) : Md5(str + key).Substring(0, 8) + str; var string_length = str.Length; var rndkey = new int[256]; var box = new int[256]; var lstResult = new List<byte>(); for (int i = 0; i <= 255; i++) { rndkey[i] = Convert.ToInt32(key[i % key_length]); box[i] = i; } for (int j = 0, i = 0; i < 256; i++) { j = (j + box[i] + rndkey[i]) % 256; var tmp = box[i]; box[i] = box[j]; box[j] = tmp; } for (int a = 0, j = 0, i = 0; i < string_length; i++) { a = (a + 1) % 256; j = (j + box[a]) % 256; var tmp = box[a]; box[a] = box[j]; box[j] = tmp; var ord = Convert.ToInt32(((Convert.ToInt32(str[i])) ^ (box[(box[a] + box[j]) % 256]))); lstResult.Add((byte)ord); } if (operation == 'D') { //if (result.Substring(0, 8) == Md5(result.Substring(8) + key).Substring(0, 8)) //{ // return result.Substring(8); //} //else //{ return "暫不考慮解密"; //} } else { return Convert.ToBase64String(lstResult.ToArray()).Replace("=", ""); } }