/// <summary> /// 通过HashAlgorithm的TransformBlock方法对流进行叠加运算获得MD5 /// 实现稍微复杂,但可使用与传输文件或接收文件时同步计算MD5值 /// 可自定义缓冲区大小,计算速度较快 /// </summary> /// <param name="path">文件地址</param> /// <returns>MD5Hash</returns> public static string getMD5ByHashAlgorithm(string path, byte[] buffer) { if (!File.Exists(path)) { throw new ArgumentException(string.Format("<{0}>, 不存在", path)); } int bufferSize = buffer.Length; string md5 = string.Empty; using (Stream inputStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize * 2)) { HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0;//每次读取长度 //var output = new byte[bufferSize]; while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, buffer, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); md5 = BitConverter.ToString(hashAlgorithm.Hash).Replace("-", ""); hashAlgorithm.Clear(); } return(md5); }
public static string md5Hash(this Bitmap bitmap) { try { if (bitmap.isNull()) { return(null); } //based on code snippets from http://dotnet.itags.org/dotnet-c-sharp/85838/ using (MemoryStream strm = new MemoryStream()) { var image = new Bitmap(bitmap); bitmap.Save(strm, System.Drawing.Imaging.ImageFormat.Bmp); strm.Seek(0, 0); byte[] bytes = strm.ToArray(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashed = md5.TransformFinalBlock(bytes, 0, bytes.Length); string hash = BitConverter.ToString(hashed).ToLower(); md5.Clear(); image.Dispose(); return(hash); } } catch (Exception ex) { ex.log("in bitmap.md5Hash"); return(""); } }
static String _Md5Asset( String filePath, MD5CryptoServiceProvider md5Service, byte[] buffer, StringBuilder sb ) { try { int bytesRead = 0; using ( var file = FileOpenRead( filePath ) ) { while ( ( bytesRead = file.Read( buffer, 0, buffer.Length ) ) > 0 ) { md5Service.TransformBlock( buffer, 0, bytesRead, buffer, 0 ); } } var meta = filePath + ".meta"; if ( File.Exists( meta ) ) { var lines = ReadFileLines( meta ); var idx = lines.FindIndex( "timeCreated:", ( name, tag ) => name.StartsWith( tag ) ); if ( idx != -1 ) { var _lines = lines.ToList(); _lines.RemoveAt( idx ); lines = _lines.ToArray(); } var content = String.Join( "\n", lines ); var bytes = Encoding.ASCII.GetBytes( content ); md5Service.TransformBlock( bytes, 0, bytes.Length, bytes, 0 ); } md5Service.TransformFinalBlock( buffer, 0, 0 ); var hashBytes = md5Service.Hash; for ( int i = 0; i < hashBytes.Length; i++ ) { sb.Append( hashBytes[ i ].ToString( "x2" ) ); } return sb.ToString(); } catch ( Exception e ) { Debug.LogException( e ); } return String.Empty; }
public bool Check(Action <int> AddBytes) { byte[] otherHash; using (MD5 md5 = new MD5CryptoServiceProvider()) using (Stream stream = this.Info.OpenRead()) { int readLen; while ((readLen = stream.Read(buffer, 0, BufferSize)) > 0) { md5.TransformBlock(buffer, 0, readLen, buffer, 0); AddBytes(readLen); } md5.TransformFinalBlock(buffer, 0, 0); otherHash = md5.Hash; } for (int i = 0; i < 16; i++) { if (otherHash[i] != this.hash[i]) { return(true); } } return(false); }
public string ComputeMD5() { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hash = null; if (NumberOfFrames == 1) { byte[] frame = GetFrameDataU8(0); hash = md5.ComputeHash(frame); } else { for (int i = 0; i < NumberOfFrames; i++) { byte[] frame = GetFrameDataU8(i); if (i < (NumberOfFrames - 1)) { md5.TransformBlock(frame, 0, frame.Length, frame, 0); } else { md5.TransformFinalBlock(frame, 0, frame.Length); } } hash = md5.Hash; } return(BitConverter.ToString(hash).Replace("-", "")); }
/// <summary> /// 通过HashAlgorithm的TransformBlock方法对流进行叠加运算获得MD5 /// 实现稍微复杂,但可使用与传输文件或接收文件时同步计算MD5值 /// 可自定义缓冲区大小,计算速度较快 /// </summary> /// <param name="stream">字节流</param> /// <returns>MD5Hash</returns> public static string GetMd5ByStream2(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } int bufferSize = 1024 * 16;//自定义缓冲区大小16K byte[] buffer = new byte[bufferSize]; HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0; //每次读取长度 stream.Position = 0; //从头开始读 var output = new byte[bufferSize]; while ((readLength = stream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); md5 = md5.Replace("-", ""); return(md5); }
/// <summary> /// Hashes the values. /// </summary> /// <param name="arrays">The arrays.</param> /// <returns></returns> private static byte[] HashValues(params byte[] [] arrays) { if (arrays == null || arrays.Length <= 0) { return(null); } byte[] [] input = arrays.Where(array => array != null).ToArray( ); if (input.Length <= 0) { return(null); } MD5 md5 = new MD5CryptoServiceProvider( ); for (int i = 0; i < input.Length - 1; i++) { md5.TransformBlock(input [i], 0, input [i].Length, input [i], 0); } md5.TransformFinalBlock(input [input.Length - 1], 0, input [input.Length - 1].Length); return(md5.Hash); }
private string ComputeValidator(string strURL, string strUserAgent) { string strRandom = String.Format("{0:X8}", new Random().Next()); byte [] abRandom = Encoding.ASCII.GetBytes(strRandom); byte [] abStatic = Convert.FromBase64String("ROkjAaKid4EUF5kGtTNn3Q=="); int p = 0; for (int i = 0; i < 3 && p != -1; i++) { p = strURL.IndexOf('/', p + 1); } byte [] abURL = Encoding.ASCII.GetBytes(strURL.Substring(p)); byte [] abUA = Encoding.ASCII.GetBytes(strUserAgent); MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); MD5.TransformBlock(abURL, 0, abURL.Length, abURL, 0); MD5.TransformBlock(abUA, 0, abUA.Length, abUA, 0); MD5.TransformBlock(abStatic, 0, abStatic.Length, abStatic, 0); MD5.TransformFinalBlock(abRandom, 0, abRandom.Length); return(String.Format("{0}-{1}", strRandom, BitConverter.ToString(MD5.Hash).Replace("-", ""))); }
private static string GetMD5HashFromFile(string path) { if (!File.Exists(path)) { throw new ArgumentException(string.Format("<{0}>, 不存在", path)); } int bufferSize = 1024 * 1024;//自定义缓冲区大小16K byte[] buffer = new byte[bufferSize]; Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0;//每次读取长度 var output = new byte[bufferSize]; while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); inputStream.Close(); inputStream.Dispose(); md5 = md5.Replace("-", ""); return(md5); }
private static byte[] OpenSSHPassphraseToKey(string passphrase, byte[] iv, int length) { const int HASH_SIZE = 16; const int SALT_SIZE = 8; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] pp = Encoding.UTF8.GetBytes(passphrase); byte[] buf = new byte[((length + HASH_SIZE - 1) / HASH_SIZE) * HASH_SIZE]; int offset = 0; while (offset < length) { if (offset > 0) { md5.TransformBlock(buf, 0, offset, null, 0); } md5.TransformBlock(pp, 0, pp.Length, null, 0); md5.TransformFinalBlock(iv, 0, SALT_SIZE); Buffer.BlockCopy(md5.Hash, 0, buf, offset, HASH_SIZE); offset += HASH_SIZE; md5.Initialize(); } md5.Clear(); byte[] key = new byte[length]; Buffer.BlockCopy(buf, 0, key, 0, length); return(key); }
/// <summary> /// Hashes data from a stream. /// </summary> /// <param name="es">The input stream.</param> /// <param name="length">The number of bytes to hash.</param> /// <returns>The hashed digest.</returns> /// <remarks> /// The method will hash length bytes of the stream from the current position /// and the stream position will be restored before the method /// returns. /// </remarks> public static byte[] Compute(EnhancedStream es, long length) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); long streamPos; byte[] buf; int cb; streamPos = es.Position; buf = new byte[8192]; while (length > 0) { cb = (int)(length > buf.Length ? buf.Length : length); if (es.Read(buf, 0, cb) < cb) { throw new InvalidOperationException("Read past end of stream."); } md5.TransformBlock(buf, 0, cb, buf, 0); length -= cb; } md5.TransformFinalBlock(buf, 0, 0); es.Seek(streamPos, SeekOrigin.Begin); return(md5.Hash); }
/// <summary> /// Computes a MD5 hash /// </summary> /// <param name="text">String or filename of file hash</param> /// <returns>Hexadecimal MD5 hash string</returns> public static string MD5(string s) { if (System.IO.File.Exists(s)) { int offset = 0; byte[] block = new byte[ZefieLib.Data.BlockSize]; byte[] hash; using (BufferedStream f = new BufferedStream(new FileStream(s, FileMode.Open, FileAccess.Read))) { using (MD5 md5 = new MD5CryptoServiceProvider()) { // For each block: while (offset + block.Length < f.Length) { f.Position = offset; f.Read(block, 0, ZefieLib.Data.BlockSize); offset += md5.TransformBlock(block, 0, block.Length, null, 0); } int remain = (int)(f.Length - (long)offset); block = new byte[remain]; f.Position = offset; _ = f.Read(block, 0, remain); _ = md5.TransformFinalBlock(block, 0, block.Length); hash = md5.Hash; } } return(ZefieLib.Data.BytesToHex(hash)); } else { return(MD5(Encoding.UTF8.GetBytes(s))); } }
/* * read 0 * read 1 2 4 8 ... until over the size */ private string one_pass(string fname, long file_size) { MD5 md5 = new MD5CryptoServiceProvider(); FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read); byte[] dat = new byte[BlockSize]; int len = fs.Read(dat, 0, BlockSize); md5.TransformBlock(dat, 0, len, dat, 0); long block = 1; while (block * BlockSize < file_size) { fs.Seek(block * BlockSize, SeekOrigin.Begin); len = fs.Read(dat, 0, BlockSize); md5.TransformBlock(dat, 0, len, dat, 0); block = block * 2; } fs.Close(); md5.TransformFinalBlock(dat, 0, 0); byte[] hash = md5.Hash; return(md5hex(hash)); }
/* * 1 pass and 1 pass reverse */ private string two_pass(string fname, long file_size) { long n = (long)Math.Ceiling((double)file_size / BlockSize); List <long> blocks = new List <long>(); blocks.Add(0); blocks.Add(n - 1); long i = 1; while (i < n) { blocks.Add(i); blocks.Add(n - 1 - i); i = i * 2; } long[] unique_blocks = blocks.Distinct().ToArray <long>(); Array.Sort(unique_blocks); MD5 md5 = new MD5CryptoServiceProvider(); FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read); byte[] dat = new byte[BlockSize]; for (long block = 0; block < unique_blocks.Length; block++) { fs.Seek(unique_blocks[block] * BlockSize, SeekOrigin.Begin); int len = fs.Read(dat, 0, BlockSize); md5.TransformBlock(dat, 0, len, dat, 0); } fs.Close(); md5.TransformFinalBlock(dat, 0, 0); byte[] hash = md5.Hash; return(md5hex(hash)); }
public static string CreateQRY(string strProductID, string strProductKey, string strCHLData) { // First generate an MD5 hash object MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); byte[] bMD5Bytes = Encoding.Default.GetBytes(strCHLData + strProductKey); MD5.TransformFinalBlock(bMD5Bytes, 0, bMD5Bytes.Length); // Once we are done with that we should create 4 integers from the MD5 hash string strMD5Hash = To_Hex(MD5.Hash); ulong[] uMD5Ints = MD5_To_Int(strMD5Hash); // Create a new string from the ProdID and CHLData and padd with zero's, then convert it to ulongs :-) string strCHLID = strCHLData + strProductID; strCHLID = strCHLID.PadRight(strCHLID.Length + (8 - (strCHLID.Length % 8)), '0'); ulong[] uCHLIDInts = CHLID_To_Int(strCHLID); // Then fetch the key from the two arrays ulong uKey = Create_Key(uMD5Ints, uCHLIDInts); // And finally create the new hash :-) ulong uPartOne = ulong.Parse(strMD5Hash.Substring(0, 16), NumberStyles.HexNumber); ulong uPartTwo = ulong.Parse(strMD5Hash.Substring(16, 16), NumberStyles.HexNumber); return(String.Format("{0:x16}{1:x16}", uPartOne ^ uKey, uPartTwo ^ uKey)); }
/// <summary> /// 计算文件的md5 /// </summary> /// <param name="path">文件路径</param> private string GetMD5(string path) { if (!File.Exists(path)) { throw new ArgumentException(string.Format("<{0}>,不存在", path)); } int bufferSize = 1024 * 16; //自定义缓冲区大小 byte[] buffer = new byte[bufferSize]; Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0;//每次读取长度 var output = new byte[bufferSize]; while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); inputStream.Close(); md5 = md5.Replace("-", ""); md5 = md5.ToLower(); Debug.Log(md5); return(md5); }
public static string MD5Decrypt(string strText) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.TransformFinalBlock(System.Text.Encoding.Default.GetBytes(strText), 0, strText.Length); return(System.Text.Encoding.UTF8.GetString(result)); }
/// <summary> /// SSH1 RSA challenge /// </summary> /// <param name="e">public exponent</param> /// <param name="n">public modulus</param> /// <param name="encryptedChallenge">encrypted challenge</param> /// <param name="sessionId">session id</param> /// <param name="responseType">response type</param> private void SSH1IRSAChallenge(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId, uint responseType) { if (responseType != 1) { SendFailure(); return; } SSH1UserAuthKey key = SSH1FindKey(e, n); if (key == null) { SendFailure(); return; } BigInteger challenge = key.decryptChallenge(encryptedChallenge); byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes(); byte[] hash; using (var md5 = new MD5CryptoServiceProvider()) { md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0); md5.TransformFinalBlock(sessionId, 0, sessionId.Length); hash = md5.Hash; } Send( new OpenSSHAgentForwardingMessage(OpenSSHAgentForwardingMessageType.SSH_AGENT_RSA_RESPONSE) .Write(hash) ); }
private void SampleFrameSyncData() { if ((Singleton <FrameSynchr> .instance.bActive && ((Singleton <FrameSynchr> .instance.CurFrameNum % 500) == 0)) && Singleton <BattleLogic> .instance.isFighting) { List <PoolObjHandle <ActorRoot> > heroActors = Singleton <GameObjMgr> .instance.HeroActors; int num = 1 + (heroActors.Count * 5); int[] src = new int[num]; int num2 = 0; src[num2++] = (int)Singleton <FrameSynchr> .instance.CurFrameNum; for (int i = 0; i < heroActors.Count; i++) { PoolObjHandle <ActorRoot> handle = heroActors[i]; ActorRoot root = handle.handle; src[num2++] = (int)root.ObjID; src[num2++] = root.location.x; src[num2++] = root.location.y; src[num2++] = root.location.z; src[num2++] = (int)root.ActorControl.myBehavior; } byte[] dst = new byte[num * 4]; Buffer.BlockCopy(src, 0, dst, 0, dst.Length); MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); provider.Initialize(); provider.TransformFinalBlock(dst, 0, dst.Length); ulong num4 = (ulong)BitConverter.ToInt64(provider.get_Hash(), 0); ulong num5 = (ulong)BitConverter.ToInt64(provider.get_Hash(), 8); ulong num6 = num4 ^ num5; CSPkg msg = NetworkModule.CreateDefaultCSPKG(0x500); msg.stPkgData.stRelayHashChk.dwKFrapsNo = Singleton <FrameSynchr> .instance.CurFrameNum; msg.stPkgData.stRelayHashChk.ullHashToChk = num6; Singleton <NetworkModule> .instance.SendGameMsg(ref msg, 0); } }
public static string Check_Stream(string path) { try { int bufferSize = 1024 * 256;//自定义缓冲区大小256K var buffer = new byte[bufferSize]; Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0;//每次读取长度 var output = new byte[bufferSize]; while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); inputStream.Close(); md5 = md5.Replace("-", ""); return(md5); } catch (ArgumentException aex) { throw new ArgumentException(string.Format("<{0}>, 不存在: {1}", path, aex.Message)); } catch (Exception ex) { throw new Exception(string.Format("读取文件 {0} , MD5失败: {1}", path, ex.Message)); } }
private void GenerateStaticContent() { resources.Clear(); var random = new Random(); var root = "/tmp/hyena-download-test-server"; try { Directory.Delete(root, true); } catch { } Directory.CreateDirectory(root); for (int i = 0; i < ResourceCount; i++) { var md5 = new MD5CryptoServiceProvider(); var resource = new Resource() { Path = Path.Combine(root, i.ToString()), Length = random.Next(MinResourceSize, MaxResourceSize + 1) }; if (Debug) { Console.WriteLine(); } using (var stream = File.OpenWrite(resource.Path)) { var buffer = new byte[32 << 10]; long written = 0; long remaining; while ((remaining = resource.Length - written) > 0) { var buffer_length = remaining > buffer.Length ? (int)buffer.Length : (int)remaining; random.NextBytes(buffer); stream.Write(buffer, 0, buffer_length); written += buffer_length; md5.TransformBlock(buffer, 0, buffer_length, null, 0); if (Debug) { Console.Write("\rCreating resource: {0} ({1:0.00} MB): [{2}/{3}] {4:0.0}% ", resource.Path, resource.Length / 1024.0 / 1024.0, i + 1, ResourceCount, written / (double)resource.Length * 100.0); } } md5.TransformFinalBlock(buffer, 0, 0); resource.Checksum = BitConverter.ToString(md5.Hash).Replace("-", String.Empty).ToLower(); } resources.Add(resource); } }
private void SampleFrameSyncData() { if (Singleton <FrameSynchr> .get_instance().bActive&& Singleton <FrameSynchr> .get_instance().CurFrameNum % this.HashCheckFreq == 0u && Singleton <BattleLogic> .get_instance().isFighting&& !Singleton <WatchController> .GetInstance().IsWatching) { List <PoolObjHandle <ActorRoot> > heroActors = Singleton <GameObjMgr> .get_instance().HeroActors; int num = 1 + heroActors.get_Count() * 7 + 1; int[] array = new int[num]; int num2 = 0; array[num2++] = (int)Singleton <FrameSynchr> .get_instance().CurFrameNum; for (int i = 0; i < heroActors.get_Count(); i++) { ActorRoot handle = heroActors.get_Item(i).get_handle(); array[num2++] = (int)handle.ObjID; array[num2++] = handle.location.x; array[num2++] = handle.location.y; array[num2++] = handle.location.z; array[num2++] = handle.ValueComponent.actorHp; array[num2++] = handle.ValueComponent.actorHpTotal; array[num2++] = (int)(handle.ActorControl.myBehavior | (ObjBehaviMode)(((!handle.HorizonMarker.IsVisibleFor(1)) ? 0 : 1) << 5) | (ObjBehaviMode)(((!handle.HorizonMarker.IsVisibleFor(2)) ? 0 : 1) << 6)); } array[num2++] = Singleton <GameObjMgr> .GetInstance().GameActors.get_Count(); byte[] array2 = new byte[num * 4]; Buffer.BlockCopy(array, 0, array2, 0, array2.Length); MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider(); mD5CryptoServiceProvider.Initialize(); mD5CryptoServiceProvider.TransformFinalBlock(array2, 0, array2.Length); ulong num3 = (ulong)BitConverter.ToInt64(mD5CryptoServiceProvider.get_Hash(), 0); ulong num4 = (ulong)BitConverter.ToInt64(mD5CryptoServiceProvider.get_Hash(), 8); ulong ullHashToChk = num3 ^ num4; CSPkg cSPkg = NetworkModule.CreateDefaultCSPKG(1280u); cSPkg.stPkgData.get_stRelayHashChk().dwKFrapsNo = Singleton <FrameSynchr> .get_instance().CurFrameNum; cSPkg.stPkgData.get_stRelayHashChk().ullHashToChk = ullHashToChk; if (Singleton <GamePlayerCenter> .get_instance().GetHostPlayer() != null) { CampInfo campInfoByCamp = Singleton <BattleStatistic> .GetInstance().GetCampInfoByCamp(Singleton <GamePlayerCenter> .get_instance().GetHostPlayer().PlayerCamp); int headPoints = campInfoByCamp.HeadPoints; COM_PLAYERCAMP campType; if (campInfoByCamp.campType == 1) { campType = 2; } else { campType = 1; } CampInfo campInfoByCamp2 = Singleton <BattleStatistic> .GetInstance().GetCampInfoByCamp(campType); int headPoints2 = campInfoByCamp2.HeadPoints; int iCampKillCntDiff = headPoints - headPoints2; cSPkg.stPkgData.get_stRelayHashChk().iCampKillCntDiff = iCampKillCntDiff; } Singleton <NetworkModule> .get_instance().SendGameMsg(ref cSPkg, 0u); } }
public byte[] MAC(byte[] plain) { MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); provider.Initialize(); provider.TransformFinalBlock(plain, 0, plain.Length); return(provider.Hash); }
public static SqlString BuildHash(SqlString path) { byte[] buffer = new byte[4096]; using (var MD5 = new MD5CryptoServiceProvider()) { try { DirectoryInfo di = new DirectoryInfo(path.Value); var FileList = di.EnumerateFiles("*", SearchOption.AllDirectories).ToList(); FileList.Sort((x, y) => { if (x == null && y == null) { return(0); } else if ((x == null) || (x.Length < y.Length)) { return(-1); } else if ((y == null) || (x.Length > y.Length)) { return(1); } else { return(x.Name.CompareTo(y.Name)); } }); foreach (var file in FileList) { int length; using (var fs = File.OpenRead(file.FullName)) { do { length = fs.Read(buffer, 0, buffer.Length); MD5.TransformBlock(buffer, 0, length, buffer, 0); }while (length > 0); } Console.WriteLine(file); } MD5.TransformFinalBlock(buffer, 0, 0); } catch (DirectoryNotFoundException) { return((SqlString)"Path not found"); //dnf.ToString(); } catch (Exception) { return(SqlString.Null); // String.Empty; } return((SqlString)BitConverter.ToString(MD5.Hash).Replace("-", String.Empty)); } }
public static byte[] EncodePapPassword(byte[] userPassBytes, byte[] requestAuthenticator, string sharedSecret) { if (userPassBytes.Length > 128) { throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes..."); } byte[] encryptedPass = userPassBytes.Length % 16 == 0 ? new byte[userPassBytes.Length] : new byte[((userPassBytes.Length / 16) * 16) + 16]; Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length); for (int i = userPassBytes.Length; i < encryptedPass.Length; i++) { encryptedPass[i] = 0; } byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret); for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++) { MD5 md5 = new MD5CryptoServiceProvider(); md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0); if (chunk == 0) { md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length); } else { md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16); } byte[] hash = md5.Hash; for (int i = 0; i < 16; i++) { int j = i + chunk * 16; encryptedPass[j] = (byte)(hash[i] ^ encryptedPass[j]); } } return(encryptedPass); }
internal static string HashAccount(Account account) { using (HashAlgorithm hasher = new MD5CryptoServiceProvider()) { hasher.Initialize(); Hash(hasher, account.UniqueNick); hasher.TransformFinalBlock(Empty, 0, 0); byte[] finalHash = GetHexidecimalHash(hasher); return(Encoding.ASCII.GetString(finalHash)); } }
protected override string cal_hash(string path, int option = 2) { string[] filters = new string[] { @"$RECYCLE\.BIN", "System Volume Information", "Recovery", "Thumbs.db", @"wasteland\.fdd" }; string filter = String.Join("|", filters); var files = Directory.EnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly); List <string> names = new List <string>(); foreach (string file in files) { if (!Regex.Match(file, $@"[A-Z]\:\\\{filter}").Success) { names.Add(file); } } names.Sort(); MD5 md5 = new MD5CryptoServiceProvider(); for (int i = 0; i < names.Count; i++) { string p = (string)names[i]; FileInfo fi = new FileInfo(p); if (fi.Attributes.HasFlag(FileAttributes.Directory)) { Folder fd = new Folder(p); folders_count += fd.Folders; files_count += fd.Files; size = size + fd.Size; byte[] hash_bytes = Encoding.ASCII.GetBytes(fd.Hash); md5.TransformBlock(hash_bytes, 0, hash_bytes.Length, hash_bytes, 0); folders_count++; } else { long file_size = fi.Length; if (file_size > 0) { Doc doc = new Doc(p); size = size + file_size; byte[] hash_bytes = Encoding.ASCII.GetBytes(doc.Hash); md5.TransformBlock(hash_bytes, 0, hash_bytes.Length, hash_bytes, 0); files_count++; } } } byte[] bytes = new byte[0]; md5.TransformFinalBlock(bytes, 0, 0); hash = Doc.md5hex(md5.Hash); return(hash); }
public override void UpdateHash(byte[] data, int offset, bool bIsLastBlock) { if (bIsLastBlock) { m_md5.TransformFinalBlock(data, 0, offset); } else { m_md5.TransformBlock(data, 0, offset, data, 0); } }
private static string GetChecksum(string filePath) { using (var fs = File.OpenRead(filePath)) { var buff = new byte[4096]; if (fs.Read(buff, 0, 20) != 20) { return(null); } if ( buff[0] == 'I' && buff[1] == 'D' && buff[2] == '3') { if (!SkipID3Data(fs)) { return(null); } } else { fs.Position = 0; } using (var md5 = new MD5CryptoServiceProvider()) { int remain = 163840; int read; while (remain > 0) { read = fs.Read(buff, 0, Math.Min(remain, 4096)); if (read == 0) { break; } remain -= read; md5.TransformBlock(buff, 0, read, buff, 0); } md5.TransformFinalBlock(buff, 0, 0); var sb = new StringBuilder(); foreach (byte b in md5.Hash) { sb.Append($"{b:x2}"); } return(sb.ToString()); } } }
private void SampleFrameSyncData() { if ((Singleton <FrameSynchr> .instance.bActive && !Singleton <WatchController> .GetInstance().IsWatching) && (((Singleton <FrameSynchr> .instance.CurFrameNum % this.HashCheckFreq) == 0) && Singleton <BattleLogic> .instance.isFighting)) { COM_PLAYERCAMP com_playercamp; List <PoolObjHandle <ActorRoot> > heroActors = Singleton <GameObjMgr> .instance.HeroActors; int num = (1 + (heroActors.Count * 6)) + 1; int[] src = new int[num]; int num2 = 0; src[num2++] = (int)Singleton <FrameSynchr> .instance.CurFrameNum; for (int i = 0; i < heroActors.Count; i++) { PoolObjHandle <ActorRoot> handle = heroActors[i]; ActorRoot root = handle.handle; src[num2++] = (int)root.ObjID; src[num2++] = root.location.x; src[num2++] = root.location.y; src[num2++] = root.location.z; src[num2++] = (int)root.ActorControl.myBehavior; src[num2++] = root.ValueComponent.actorHp; } src[num2++] = MonoSingleton <ActionManager> .GetInstance().ActionUpdatingCount; byte[] dst = new byte[num * 4]; Buffer.BlockCopy(src, 0, dst, 0, dst.Length); MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); provider.Initialize(); provider.TransformFinalBlock(dst, 0, dst.Length); ulong num4 = (ulong)BitConverter.ToInt64(provider.Hash, 0); ulong num5 = (ulong)BitConverter.ToInt64(provider.Hash, 8); ulong num6 = num4 ^ num5; CSPkg msg = NetworkModule.CreateDefaultCSPKG(0x500); msg.stPkgData.stRelayHashChk.dwKFrapsNo = Singleton <FrameSynchr> .instance.CurFrameNum; msg.stPkgData.stRelayHashChk.ullHashToChk = num6; CampInfo campInfoByCamp = null; campInfoByCamp = Singleton <BattleStatistic> .GetInstance().GetCampInfoByCamp(Singleton <GamePlayerCenter> .instance.GetHostPlayer().PlayerCamp); int headPoints = campInfoByCamp.HeadPoints; int num8 = 0; if (campInfoByCamp.campType == COM_PLAYERCAMP.COM_PLAYERCAMP_1) { com_playercamp = COM_PLAYERCAMP.COM_PLAYERCAMP_2; } else { com_playercamp = COM_PLAYERCAMP.COM_PLAYERCAMP_1; } num8 = Singleton <BattleStatistic> .GetInstance().GetCampInfoByCamp(com_playercamp).HeadPoints; int num9 = headPoints - num8; msg.stPkgData.stRelayHashChk.iCampKillCntDiff = num9; Singleton <NetworkModule> .instance.SendGameMsg(ref msg, 0); } }
private string ComputeValidator( string strURL, string strUserAgent ) { string strRandom = String.Format( "{0:X8}", new Random().Next() ); byte [] abRandom = Encoding.ASCII.GetBytes( strRandom ); byte [] abStatic = Convert.FromBase64String( "ROkjAaKid4EUF5kGtTNn3Q==" ); int p = 0; for( int i = 0; i < 3 && p != -1; i++ ) p = strURL.IndexOf( '/', p + 1 ); byte [] abURL = Encoding.ASCII.GetBytes( strURL.Substring( p ) ); byte [] abUA = Encoding.ASCII.GetBytes( strUserAgent ); MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); MD5.TransformBlock( abURL, 0, abURL.Length, abURL, 0 ); MD5.TransformBlock( abUA, 0, abUA.Length, abUA, 0 ); MD5.TransformBlock( abStatic, 0, abStatic.Length, abStatic, 0 ); MD5.TransformFinalBlock( abRandom, 0, abRandom.Length ); return String.Format( "{0}-{1}", strRandom, BitConverter.ToString( MD5.Hash ).Replace( "-", "" ) ); }
byte[] IHashAlgorithm.GetRunningHash () { var copy = new MD5CryptoServiceProvider (this); copy.TransformFinalBlock (empty, 0, 0); return copy.Hash; }