public static MvcHtmlString Gravatar( this HtmlHelper htmlHelper, string email, int size = 80, string defaultImage = "mm", object htmlAttributes = null) { var img = new TagBuilder("img"); if (htmlAttributes != null) { // Get the attributes IDictionary <string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); // set the attributes img.MergeAttributes(attributes); } img.AddCssClass("gravatar"); var hash = MD5Utils.GetMd5Hash(email.ToLower()); var encodedSize = htmlHelper.Encode(size); var encodedDefaultImage = htmlHelper.Encode(defaultImage); var url = $"//gravatar.com/avatar/{hash}.jpg?s={encodedSize}&d={encodedDefaultImage}"; img.MergeAttribute("src", url); return(MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing))); }
private static string _getConfigFieldMD5(object obj) { if (obj == null) { return(MD5Utils.GetMD5("null")); } Type t = obj.GetType(); string md5 = ""; if (t.IsArray || (t.IsGenericType && typeof(IEnumerable).IsAssignableFrom(t))) { IEnumerable arr = (IEnumerable)obj; StringBuilder sb = new StringBuilder(); foreach (object o in arr) { sb.Append(_getConfigFieldMD5(o)); } md5 = MD5Utils.GetMD5(sb.ToString()); } else if (t.IsSubclassOf(typeof(Config))) { md5 = ((Config)obj)._getMD5(); } else { md5 = MD5Utils.GetMD5(obj.ToString()); } return(md5); }
protected override void OnRequest(request_login request, object userdata) { LoginActionParam param = userdata as LoginActionParam; if (param == null) { return; } string md5_value = MD5Utils.Encrypt(param.Passwd); request.clientversion = param.ClientVer; request.tencentlogin = param.TencentLogin; request.usrname = param.UserName; request.passwd = HMACUtils.HMacSha1Encrypt(md5_value, Net.Instance.GetSessionKey()); request.openId = param.OpenId; request.platform = param.Platform; request.accesstoken = param.AccessToken; request.paytoken = param.PayToken; request.pf = param.Pf; request.pfkey = param.PfKey; request.regchannel = param.RegChannel; request.setupchannel = param.SetupChannel; request.clientsystem = param.ClientSystem; request.txplat = param.TXPlat; }
public static byte[] MD5(Span <byte> input) { var output = new byte[16]; MD5Utils.Default(input, output); return(output); }
static void AddBundleInfo(string bundleName, ref FileList filelist) { if (string.IsNullOrEmpty(bundleName)) { return; } string bundlePath = string.Format("{0}/{1}", PackAssetBundle.bundleBuildFolder, bundleName); uint crc = 0; if (!BuildPipeline.GetCRCForAssetBundle(bundlePath, out crc)) { return; } FileInfo fileInfo = new FileInfo(bundlePath); UInt32 size = (UInt32)fileInfo.Length; string md5 = ""; if (string.Equals(bundleName, ResourceConst.PkgBundleFolder)) { md5 = MD5Utils.GetMD5(bundlePath); } else { md5 = FileDepencies.GetBundleMD5(bundlePath); } filelist.AddBundleInfo(bundleName, crc, size, md5); }
public static byte[] MD5(byte[] b) { var hash = new byte[CryptoBase.MD5Length]; MD5Utils.Default(b, hash); return(hash); }
public int StringArrayToInt(string[] arr) { Array.Sort(arr); string tempS = string.Join("&", arr); return(MD5Utils.GetStringToHash(tempS)); }
/// <summary> /// 生成AB资源文件列表 /// </summary> public static void CreateAssetBundleFileInfo() { string abRootPath = GetExportPath(); string abFilesPath = abRootPath + "/" + AppSetting.ABFiles; if (File.Exists(abFilesPath)) { File.Delete(abFilesPath); } var abFileList = new List <string>(Directory.GetFiles(abRootPath, "*" + AppSetting.ExtName, SearchOption.AllDirectories)); abFileList.Add(abRootPath + Utility.GetPlatformName()); FileStream fs = new FileStream(abFilesPath, FileMode.CreateNew); StreamWriter sw = new StreamWriter(fs); DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(2018, 1, 1)); int ver = ((int)((DateTime.Now - startTime).TotalMinutes)); sw.WriteLine(ver + "|" + DateTime.Now.ToString("u")); for (int i = 0; i < abFileList.Count; i++) { string file = abFileList[i]; long size = 0; string md5 = MD5Utils.MD5File(file, out size); string value = file.Replace(abRootPath, string.Empty).Replace("\\", "/"); sw.WriteLine(value + "|" + md5 + "|" + size); } sw.Close(); fs.Close(); Debug.LogError("资源版本Version:" + ver + " 已复制到剪切板"); Debug.LogError("ABFiles文件生成完成"); MyEditorTools.CopyString(ver.ToString()); }
static void AddConfInfo(FileList filelist) { if (filelist == null) { return; } string confFolder = string.Format("{0}/{1}", PackAssetBundle.bundleBuildFolder, ResourceConst.ConfFolder); string[] files = Directory.GetFiles(confFolder); foreach (string file in files) { string fileName = Path.GetFileName(file); string bundleName = string.Format("{0}/{1}", ResourceConst.ConfFolder, fileName); uint crc = FileToCRC32.GetFileCRC32Int(file); FileInfo fileInfo = new FileInfo(file); UInt32 size = (UInt32)fileInfo.Length; string md5 = MD5Utils.GetMD5(file); filelist.AddBundleInfo(bundleName, crc, size, md5); } }
protected override void InitCipher(byte[] iv, bool isEncrypt) { base.InitCipher(iv, isEncrypt); _crypto?.Dispose(); if (cipherFamily == CipherFamily.Rc4Md5) { Span <byte> temp = stackalloc byte[keyLen + ivLen]; var realKey = new byte[MD5Length]; key.CopyTo(temp); iv.CopyTo(temp.Slice(keyLen)); MD5Utils.Fast440(temp, realKey); _crypto = StreamCryptoCreate.Rc4(realKey); return; } _crypto = cipherFamily switch { CipherFamily.AesCfb => StreamCryptoCreate.AesCfb(isEncrypt, key, iv), CipherFamily.Chacha20 => StreamCryptoCreate.ChaCha20(key, iv), CipherFamily.Rc4 => StreamCryptoCreate.Rc4(key), _ => throw new NotSupportedException() }; }
private void OnConnectedCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { return; } Socket socket = sender as Socket; OnLogEvent("服务器连接成功。。。"); //开启新的接受消息异步操作事件 var receiveSaea = new SocketAsyncEventArgs(); var receiveBuffer = new byte[1024 * 4]; receiveSaea.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); //设置消息的缓冲区大小 receiveSaea.Completed += OnReceiveCompleted; //绑定回调事件 receiveSaea.RemoteEndPoint = _endPoint; _socket.ReceiveAsync(receiveSaea); string timestamp = MD5Utils.ConvertDateTimeInt(DateTime.Now) + ""; string uuid = Guid.NewGuid().ToString().Replace("-", "").ToUpper(); string vk = MD5Utils.GetMD5(timestamp + "7oE9nPEG9xXV69phU31FYCLUagKeYtsF" + uuid); SendMsg(Request.gid(rid, uuid, timestamp, vk)); }
/// <summary> /// 极速达取消订单 /// </summary> /// <param name="param"></param> /// <returns></returns> public async Task <ResultData <string> > CancelOrder(HttpCancelOrderParameter param) { Dictionary <string, string> dirList = new Dictionary <string, string>(); dirList.Add("OrderCode", param.OrderCode); dirList.Add("cancelBy", param.cancelBy); dirList.Add("app_id", "jsd"); dirList.Add("timestamp", StaticFunction.GetTimestamp(0).ToString() + "000"); dirList.Add("ecOrderNumber", param.OrderCode); var str = StaticFunction.GetEcoParamSrc(dirList); var sign = MD5Utils.MD5Encrypt(eco_app_token + str + eco_app_token).ToUpper(); dirList.Add("sign", sign); var returnStr = await WebAPIHelper.HttpPostAsync(ECOUrl + "/api/order/cancelOrder", JsonConvert.SerializeObject(dirList)); var result = JsonConvert.DeserializeObject <HttpCancelOrderResult>(returnStr); if (result.success) { this._logger.LogInformation("订单号为:" + param.OrderCode + "取消成功"); return(ResultData <string> .CreateResultDataSuccess("成功")); } this._logger.LogWarning("订单号为:" + param.OrderCode + "取消失败,原因:" + (result.errorMsg ?? "调用极速达取消接口失败")); return(ResultData <string> .CreateResultDataFail(result.errorMsg ?? "调用极速达取消接口失败")); }
private static string GetSign(string url, out Dictionary <string, string> querydic, out string host) { querydic = new Dictionary <string, string>(); Uri uri = new Uri(url); host = uri.GetLeftPart(UriPartial.Path); string[] Queryurl = uri.Query.Replace("?", "").Split('&'); SortedDictionary <string, string> dic = new SortedDictionary <string, string>(); foreach (string query in Queryurl) { int index = query.IndexOf('='); string name = query.Substring(0, index); string param = query.Substring(index + 1, query.Length - index - 1); dic.Add(name, param); } string paramStr = ""; foreach (string key in dic.Keys) { paramStr += dic[key]; querydic.Add(key, dic[key]); } paramStr += scretkey; paramStr = MD5Utils.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(paramStr)); //paramStr = Base64Encode(paramStr); return(paramStr); }
static void GetMD5(DirectoryInfo info, Dictionary <string, string> dict) { if (!info.Exists) { return; } var files = info.GetFileSystemInfos(); foreach (var item in files) { EditorUtility.DisplayProgressBar("Make MD5, Hold on!", item.FullName, 1); if (item is DirectoryInfo) { GetMD5(item as DirectoryInfo, dict); } else { string rootPath = Application.dataPath + "/"; string key = item.FullName.Replace("\\", "/").Replace(rootPath, string.Empty); string error = string.Empty; dict[key] = MD5Utils.GetFileHash(item.FullName, out error); if (!string.IsNullOrEmpty(error)) { Log.Error(error); } } } }
public static string GetMd5Hash(string str) { using (System.Security.Cryptography.MD5 md5hash = System.Security.Cryptography.MD5.Create()) { string hashstr = MD5Utils.GetMd5Hash(md5hash, str); return(hashstr); } }
private static void SaveFilesText(BuildTarget target) { string streamingPath = bundlePath + "StreamingAssets"; AssetBundle asset = AssetBundle.LoadFromFile(streamingPath); AssetBundleManifest bundleManifest = asset.LoadAsset("AssetBundleManifest") as AssetBundleManifest; asset.Unload(false); Hashtable bundleDatas = new Hashtable(); string[] bundleList = bundleManifest.GetAllAssetBundles(); foreach (string bundleName in bundleList) { ArrayList fileInfo = new ArrayList(); string abPath = bundlePath + bundleName; // TODO 查找依赖 // SortList<string> deps = GetBundleDependencies(obj); // byte[] buffer = GetFilesBuffer(deps); byte[] fileBytes = FileUtils.ReadBytes(abPath); long fileSize = fileBytes.Length; string fileMD5 = MD5Utils.GetMD5(fileBytes); fileInfo.Add(fileSize); fileInfo.Add(fileMD5); bundleDatas.Add(bundleName, fileInfo); } // 保存到 files.txt string tmpPath = "Assets/tmp/"; // 一定要写绝对的路径 string filePath = tmpPath + "files.txt"; string jsonStr = MiniJSON.jsonEncode(bundleDatas); byte[] bytes = Encoding.UTF8.GetBytes(jsonStr); FileUtils.WriteBytes(filePath, bytes); AssetDatabase.Refresh(); // 生成 assetbundle AssetBundleBuild[] buildMap = new AssetBundleBuild[1]; string[] assetNames = new string[1]; BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression; //LZ4压缩 assetNames[0] = filePath; buildMap[0].assetNames = assetNames; buildMap[0].assetBundleName = "files"; BuildPipeline.BuildAssetBundles(tmpPath, buildMap, options, target); // copy FileUtils.CopyFile(tmpPath + "files", bundlePath + "files"); FileUtils.CopyFile(filePath, bundlePath + "files.txt"); Directory.Delete(tmpPath, true); AssetDatabase.Refresh(); }
public static void MD5Test() { string s1 = MD5Utils.CalculateMD5path("C:\\TestRep\\ALPHA\\ALPHA.c_package.bdy"); Console.WriteLine(s1); string s2 = MD5Utils.CalculateMD5path("C:\\TestRep\\ALPHA\\ALPHA.c_package.spc"); Console.WriteLine(s2); }
public void Compute() { if (Assets.Count <= 1) { md5 = value; return; } md5 = MD5Utils.GetMD5FromValue(value); }
public static string GetAddressHash(AddressDTO address) { return(MD5Utils.GetMD5HashAsString(address.FinalCountry + "-" + address.FinalCity + "-" + address.FinalState + "-" + address.FinalZip + "-" + address.FinalZipAddon + "-" + address.FinalAddress1 + "-" + address.FinalAddress2)); }
public void MD5DigestTest(string str, string md5Str) { MD5DigestTest(new DefaultMD5Digest(), str, md5Str); MD5DigestTest(new BcMD5Digest(), str, md5Str); MD5DigestTest(new MD5Digest(), str, md5Str); Span <byte> hash = stackalloc byte[HashConstants.Md5Length]; MD5Utils.Fast440(Encoding.UTF8.GetBytes(str), hash); Assert.AreEqual(md5Str, hash.ToHex()); }
public void Save2File(string fileName, string ss) { byte[] dataByte = Encoding.GetEncoding("UTF-8").GetBytes(ss); string md5 = MD5Utils.GetMD5Base64(dataByte); //Debug.Log("Save2File:" + fileName + " md5:" + md5 + "\n" + ss); string length = md5.Length.ToString().PadLeft(4, '0'); ss = length + md5 + ss; //Debug.Log("Save File:" + fileName + " md5:" + md5 + "\n" + ss); FileUtils.CreateTextFile(GetFilePath(fileName), ss); }
public static FileListCompareAll Compare(string newPath, string oldPath) { if (string.IsNullOrEmpty(newPath) || string.IsNullOrEmpty(oldPath)) { return(null); } if (!File.Exists(newPath) || !File.Exists(oldPath)) { return(null); } FileList newFileList = ReadFileList(newPath); FileList oldFileList = ReadFileList(oldPath); //FileList newFileList = BuildCommon.ReadJsonFromFile<FileList>(newPath); //FileList oldFileList = BuildCommon.ReadJsonFromFile<FileList>(oldPath); if (newFileList == null) { Debug.LogErrorFormat("{0} Load Failed!", newPath); return(null); } if (oldFileList == null) { Debug.LogErrorFormat("{0} Load Failed!", oldPath); return(null); } FileListCompareAll compareall = new FileListCompareAll(); compareall.time = System.DateTime.Now.ToString(); compareall.newFileList = string.Format("{0} : {1}", newPath, MD5Utils.GetMD5(newPath)); compareall.oldFileList = string.Format("{0} : {1}", oldPath, MD5Utils.GetMD5(oldPath)); for (int i = 1; i < (int)BundleUpdateMode.Update_End; i++) { BundleUpdateMode mode = (BundleUpdateMode)i; FileListCompareData comData = FileList.Compare(newFileList, oldFileList, true, mode); if (comData == null) { continue; } FileListCompareInfo info = new FileListCompareInfo(); info.mode = mode.ToString(); info.data = comData; compareall.infoList.Add(info); } return(compareall); }
private void work() { Console.WriteLine("心跳包线程启动"); while (IsRunning) { Thread.Sleep(40000); string message = Request.keepLive(MD5Utils.ConvertDateTimeInt(DateTime.Now)); if (IsRunning) { socket.SendMsg(message); } } }
/// <summary> /// 检查保存文件的完整性 /// </summary> /// <returns></returns> public bool CheckSaveFileMD5() { Debug.Log("开始检查保存文件的完整性"); if (Directory.Exists(GetFileDir())) { string[] filePaths = PathUtils.GetDirectoryFilePath(GetFileDir()); foreach (var path in filePaths) { string fileName = Path.GetFileNameWithoutExtension(path); string md5 = null; string text = GetFileTextData(fileName, out md5); //Debug.Log("fileName:" + fileName + " md5:" + md5 + "\n" + text); Dictionary <string, string> fileContent = null; if (allRecords.ContainsKey(fileName)) { fileContent = allRecords[fileName]; } else { fileContent = converter.String2Object <Dictionary <string, string> >(text); if (fileContent == null) { fileContent = new Dictionary <string, string>(); } allRecords.Add(fileName, fileContent); } if (!string.IsNullOrEmpty(md5)) { byte[] dataByte = Encoding.GetEncoding("UTF-8").GetBytes(text); //Debug.Log("dataByte.lenth:" + dataByte.Length); string md5New = MD5Utils.GetMD5Base64(dataByte); // string md5New = MD5Utils.GetObjectMD5(text); if (md5New != md5) { Debug.LogError("文件:" + fileName + " md5不正确:" + md5 + " md5New:" + md5New + "\n" + text); return(false); } } else { if (text != null && text.Length < 3) { return(false); } } } } return(true); }
/// <summary> /// 登录 /// </summary> /// <param name="loginPlatform"></param> /// <param name="accountID"></param> /// <param name="pw"></param> public static void Login(LoginPlatform loginPlatform, string accountID = "", string pw = "", string custom = "") { SDKManager.LoginCallBack += SDKLoginCallBack; string tag = ""; accountID = accountID.Trim(); pw = pw.Trim(); string pwMd5 = MD5Utils.GetObjectMD5(pw); tag = accountID + "|" + pwMd5 + "|" + custom; SDKManager.LoginByPlatform(loginPlatform, tag); }
private void DownloadFinishWithMd5(DownloadTask task) { #if UNITY_IPHONE //ios下如果封装该方法在一个函数中,调用该函数来产生文件的MD5的时候,就会抛JIT异常。 //如果直接把这个产生MD5的方法体放在直接执行,就可以正常执行,这个原因还不清楚。 string md5Compute = null; using (System.IO.FileStream fileStream = System.IO.File.OpenRead(task.FileName)) { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] fileMD5Bytes = md5.ComputeHash(fileStream); md5Compute = System.BitConverter.ToString(fileMD5Bytes).Replace("-", "").ToLower(); } #else var md5Compute = MD5Utils.BuildFileMd5(task.FileName); #endif if (task.hasMD5 && md5Compute.Trim() != task.MD5.Trim()) { task.tryTimes++; if (task.tryTimes > MaxTryTime) { Debug.unityLogger.Log("重试" + MaxTryTime + "无效, 停止重试"); task.bDownloadAgain = false; task.bFineshed = true; task.OnError(new Exception("md5验证失败,下载失败")); task.OnFinished(false); } else { if (File.Exists(task.FileName)) { File.Delete(task.FileName); } Debug.Log("断点MD5验证失败,第" + task.tryTimes + "次重试,从新下载:" + task.FileName + "--" + md5Compute + " vs " + task.MD5); task.bDownloadAgain = true; task.bFineshed = false; } } else { task.bDownloadAgain = false; task.bFineshed = true; task.OnFinished(true); } CheckDownLoadList(finishedAct, progressAct); }
private void OnGUI() { GUILayout.FlexibleSpace(); GUILayout.Space(5); GUILayout.BeginHorizontal(); inputText = EditorDrawGUIUtil.DrawBaseValue("输入字符串:", inputText).ToString(); if (GUILayout.Button("转换")) { resText = MD5Utils.GetObjectMD5(inputText); } GUILayout.EndHorizontal(); EditorDrawGUIUtil.DrawBaseValue("MD5:", resText); GUILayout.FlexibleSpace(); }
public static byte[] SSKDF(string password, int keylen) { const int md5Length = 16; var pwMaxSize = Encoding.UTF8.GetMaxByteCount(password.Length); var key = new byte[keylen]; var pwBuffer = ArrayPool <byte> .Shared.Rent(pwMaxSize); var resultBuffer = ArrayPool <byte> .Shared.Rent(pwMaxSize + md5Length); try { var pwLength = Encoding.UTF8.GetBytes(password, pwBuffer); var pw = pwBuffer.AsSpan(0, pwLength); Span <byte> md5Sum = stackalloc byte[md5Length]; var result = resultBuffer.AsSpan(0, pwLength + md5Length); var i = 0; while (i < keylen) { if (i == 0) { MD5Utils.Default(pw, md5Sum); } else { md5Sum.CopyTo(result); pw.CopyTo(result.Slice(md5Length)); MD5Utils.Default(result, md5Sum); } var length = Math.Min(16, keylen - i); md5Sum.Slice(0, length).CopyTo(key.AsSpan(i, length)); i += md5Length; } return(key); } finally { ArrayPool <byte> .Shared.Return(pwBuffer); ArrayPool <byte> .Shared.Return(resultBuffer); } }
static AssetBundleMD5Info GetMD5FromAssets(List <string> assets, string bundlePath) { AssetBundleMD5Info info = new AssetBundleMD5Info(); info.bundleName = bundlePath; if (assets == null || assets.Count < 1) { return(info); } for (int i = 0; i < assets.Count; i++) { string md5 = MD5Utils.GetMD5FromFile(assets[i]); info.AddAssets(assets[i], md5); } return(info); }
/// <summary> /// 获取极速达订单 /// </summary> /// <returns></returns> public async Task <HttpGetJsdOrderPayedDetailResult> GetJsdOrderPayedDetailAsync(DateTime datetime) { var intertfeceUrl = "/orders/web/ecoSync/orders/getJsdOrderPayedDetail"; var headurl = JsdUpdateOrderUrl.Trim('/'); var dateStr = datetime.ToString("yyyy-MM-dd"); var requestObj = new { appid = "3", start_date = dateStr + " 00:00:00", end_date = dateStr + " 23:59:59", sign = MD5Utils.MD5Encrypt(headurl + intertfeceUrl + JsdUpdateOrderAppSecret) }; var returnStr = await WebAPIHelper.HttpPostAsync(headurl + intertfeceUrl, JsonConvert.SerializeObject(requestObj)); var result = JsonConvert.DeserializeObject <HttpGetJsdOrderPayedDetailResult>(returnStr); return(result); }