static byte[] CreateKeyDigest(String password, byte[] docIdData) { Check16Bytes(docIdData, "docId"); int nChars = Math.Min(password.Length, 16); byte[] passwordData = new byte[nChars * 2]; for (int i = 0; i < nChars; i++) { char ch = password[i]; passwordData[i * 2 + 0] = (byte)((ch << 0) & 0xFF); passwordData[i * 2 + 1] = (byte)((ch << 8) & 0xFF); } byte[] kd; MD5 md5 = new MD5CryptoServiceProvider(); byte[] passwordHash = md5.ComputeHash(passwordData); md5.Clear(); md5.Initialize(); byte[] data=new byte[passwordHash.Length*16 + docIdData.Length*16]; int offset=0; for (int i = 0; i < 16; i++) { Array.Copy(passwordHash, 0, data, offset, PASSWORD_HASH_NUMBER_OF_BYTES_USED); offset+=passwordHash.Length; Array.Copy(docIdData,0,data,offset,docIdData.Length); offset += docIdData.Length; } kd = md5.ComputeHash(data); byte[] result = new byte[KEY_DIGEST_LENGTH]; Array.Copy(kd, 0, result, 0, KEY_DIGEST_LENGTH); return result; }
public static string ToMD5(this Stream stream) { HashAlgorithm hasher = new MD5CryptoServiceProvider(); hasher.Initialize(); stream.Seek(0, System.IO.SeekOrigin.Begin); return BitConverter.ToString(hasher.ComputeHash(stream)).Replace("-", ""); }
public static string Generate(string str) { var md5 = new MD5CryptoServiceProvider(); md5.Initialize(); var buf = Encoding.UTF8.GetBytes(str); var hashArray = md5.ComputeHash(buf); string hash = ""; hashArray.ForEach(x => { hash += x.ToString("x"); }); return hash.Substring(0, 6); }
public static string GetMD5(this Stream sDataIn) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); md5.Initialize(); byte[] bytes = md5.ComputeHash(sDataIn); md5.Clear(); StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { sb.Append(b.ToString("x2")); } return(sb.ToString()); }
/// <summary> /// ���ļ�����MD5���� /// </summary> /// <param name="filePath"></param> public static void MD5File(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // ��������С��1MB byte[] buff = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // ��ȡһ�����ݵ������� if (offset + readSize < fs.Length) // �������һ�� { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // ���һ�� { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } Console.WriteLine(sb.ToString()); Console.ReadLine(); }
/// <summary> /// 获取文件的MD5值 /// </summary> /// <param name="fileName"> 文件名 </param> /// <returns> 32位MD5 </returns> public static string GetFileMd5(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); const int bufferSize = 1024 * 1024; byte[] buffer = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buffer, 0, (int)readSize); if (offset + readSize < fs.Length) { md5.TransformBlock(buffer, 0, (int)readSize, buffer, 0); } else { md5.TransformFinalBlock(buffer, 0, (int)readSize); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); foreach (byte b in result) { sb.Append(b.ToString("X2")); } return sb.ToString(); }
/// <summary> /// Constructor. /// </summary> public Md5Sum() { _md5Sum = new MD5CryptoServiceProvider(); _md5Sum.Initialize(); }
private static byte[] CreateKeyDigest(String password, byte[] docIdData) { Check16Bytes(docIdData, "docId"); var nChars = Math.Min(password.Length, 16); var passwordData = new byte[nChars*2]; for (var i = 0; i < nChars; i++) { var chr = password[i]; passwordData[i*2 + 0] = (byte) ((chr << 0) & 0xFF); passwordData[i*2 + 1] = (byte) ((chr << 8) & 0xFF); } using (MD5 md5 = new MD5CryptoServiceProvider()) { var passwordHash = md5.ComputeHash(passwordData); md5.Initialize(); var data = new byte[PasswordHashNumberOfBytesUsed*16 + docIdData.Length*16]; var offset = 0; for (var i = 0; i < 16; i++) { Array.Copy(passwordHash, 0, data, offset, PasswordHashNumberOfBytesUsed); offset += PasswordHashNumberOfBytesUsed; Array.Copy(docIdData, 0, data, offset, docIdData.Length); offset += docIdData.Length; } var kd = md5.ComputeHash(data); var result = new byte[KeyDigestLength]; Array.Copy(kd, 0, result, 0, KeyDigestLength); md5.Clear(); return result; } }
/// <summary> /// 生成某个文件的MD5 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GenMD5(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // 缓冲区大小,1MB byte[] buff = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区 if (offset + readSize < fs.Length) // 不是最后一块 { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // 最后一块 { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } return sb.ToString(); }
/// <summary> /// 获取本地文件MD5哈希值 /// </summary> /// <param name="FilePath">本地文件完整路径</param> /// <remarks> /// 如果文件不存在则返回字符N/A /// </remarks> public static string GetMD5Hash(string FilePath) { if (!File.Exists(FilePath)) { return "N/A"; } else { System.IO.FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read); System.Security.Cryptography.MD5 md = new MD5CryptoServiceProvider(); md.Initialize(); byte[] b = md.ComputeHash(fs); return ByteArrayToHexStr(b, true); } }
// Parse the contents of a certificate data block. private void Parse(byte[] data) { // Clone the data for internal storage. rawData = (byte[])(data.Clone()); // Parse the ASN.1 data to get the field we are interested in. ASN1Parser parser = new ASN1Parser(rawData); ASN1Parser signed = parser.GetSequence(); ASN1Parser certInfo = signed.GetSequence(); if(certInfo.Type == ASN1Parser.ContextSpecific(0)) { // Skip the version field. certInfo.Skip(); } serialNumber = certInfo.GetContentsAsArray(ASN1Type.Integer); ASN1Parser algId = certInfo.GetSequence(); issuer = ParseName(certInfo); ASN1Parser validity = certInfo.GetSequence(); effectiveDate = validity.GetUTCTime(); expirationDate = validity.GetUTCTime(); name = ParseName(certInfo); ASN1Parser keyInfo = certInfo.GetSequence(); algId = keyInfo.GetSequence(); keyAlgorithm = ToHex(algId.GetObjectIdentifier()); if(algId.IsAtEnd() || algId.IsNull()) { keyAlgorithmParameters = null; } else { keyAlgorithmParameters = algId.GetWholeAsArray(); } publicKey = keyInfo.GetBitString(); #if CONFIG_CRYPTO // Construct an MD5 hash of the certificate. Is this correct? MD5 md5 = new MD5CryptoServiceProvider(); md5.InternalHashCore(rawData, 0, rawData.Length); hash = md5.InternalHashFinal(); md5.Initialize(); #endif }
public static byte[] PassphraseToKey(string passphrase, int length) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] pp = Encoding.UTF8.GetBytes(passphrase); int hashlen = md5.HashSize / 8; byte[] buf = new byte[((length + hashlen) / hashlen) * hashlen]; int offset = 0; while (offset < length) { MemoryStream s = new MemoryStream(); s.Write(pp, 0, pp.Length); if (offset > 0) s.Write(buf, 0, offset); Array.Copy(md5.ComputeHash(s.ToArray()), 0, buf, offset, hashlen); offset += hashlen; md5.Initialize(); } byte[] key = new byte[length]; Array.Copy(buf, 0, key, 0, length); return key; }
public string ComposeRequest() { string nonce = ipAddress + ":" + DateTime.Now.ToUniversalTime().ToString("R"); MD5 md5 = new MD5CryptoServiceProvider(); md5.Initialize(); byte[] h = md5.ComputeHash(Encoding.ASCII.GetBytes(nonce)); nonce = BitConverter.ToString(h).Replace("-", "").ToLower(); string opaque = "nfoiwero8ur0 ofidosfuoewrf oieufo sedoif "; h = md5.ComputeHash(Encoding.ASCII.GetBytes(opaque)); opaque = BitConverter.ToString(h).Replace("-", "").ToLower(); return string.Format("Digest qop=auth, nonce=\"{0}\", realm=\"{1}\", opaque=\"{2}\"", nonce, Realm, opaque); }
public byte[] Encode(byte[] data) { byte[] buffer = new byte[data.Length + 128]; using (MemoryStream stream = new MemoryStream(data)) { int num; MemoryStream stream2 = new MemoryStream(buffer); RSACryptoServiceProvider key = new RSACryptoServiceProvider(1024); byte[] buffer2 = new byte[86]; byte[] outputBuffer = new byte[86]; HashAlgorithm algorithm = new MD5CryptoServiceProvider(); algorithm.Initialize(); while ((num = stream.Read(buffer2, 0, 86)) == 86) { algorithm.TransformBlock(buffer2, 0, 86, outputBuffer, 0); stream2.Write(buffer2, 0, buffer2.Length); } buffer2 = algorithm.TransformFinalBlock(buffer2, 0, num); stream2.Write(buffer2, 0, buffer2.Length); RSAParameters parameters = new RSAParameters(); parameters.D = (byte[])this.rsaParameters.D.Clone(); parameters.DP = (byte[])this.rsaParameters.DP.Clone(); parameters.DQ = (byte[])this.rsaParameters.DQ.Clone(); parameters.Exponent = (byte[])this.rsaParameters.Exponent.Clone(); parameters.InverseQ = (byte[])this.rsaParameters.InverseQ.Clone(); parameters.Modulus = (byte[])this.rsaParameters.Modulus.Clone(); parameters.P = (byte[])this.rsaParameters.P.Clone(); parameters.Q = (byte[])this.rsaParameters.Q.Clone(); key.ImportParameters(parameters); AsymmetricSignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key); formatter.SetHashAlgorithm("MD5"); outputBuffer = formatter.CreateSignature(algorithm.Hash); stream2.Write(outputBuffer, 0, outputBuffer.Length); stream2.Close(); stream.Close(); } return buffer; }
/** * Actual constructor for ImgJBIG2 images. * @param width the width of the image * @param height the height of the image * @param data the raw image data * @param globals JBIG2 globals */ public ImgJBIG2(int width, int height, byte[] data, byte[] globals) : base((Uri)null) { type = Element.JBIG2; originalType = ORIGINAL_JBIG2; scaledHeight = height; this.Top = scaledHeight; scaledWidth = width; this.Right = scaledWidth; bpc = 1; colorspace = 1; rawData = data; plainWidth = this.Width; plainHeight = this.Height; if ( globals != null ) { this.global = globals; try { MD5 md5 = new MD5CryptoServiceProvider(); md5.Initialize(); this.globalHash = md5.ComputeHash(this.global); } catch { //ignore } } }
// Derive a key for a specific cryptographic algorithm. public byte[] CryptDeriveKey(String algname, String alghashname, int keySize, byte[] rgbIV) { if((algname == "DES" || algname == "RC2") && alghashname == "MD5" && keySize == 8) { // Use the older PKCS #5 password generation routine. MD5 md5 = new MD5CryptoServiceProvider(); if(strPassword != null) { byte[] pwd = Encoding.UTF8.GetBytes(strPassword); md5.InternalHashCore(pwd, 0, pwd.Length); Array.Clear(pwd, 0, pwd.Length); } if(rgbSalt != null) { md5.InternalHashCore(rgbSalt, 0, rgbSalt.Length); } byte[] tempHash = md5.InternalHashFinal(); md5.Initialize(); int count = iterations; while(count > 1) { md5.InternalHashCore(tempHash, 0, tempHash.Length); Array.Clear(tempHash, 0, tempHash.Length); tempHash = md5.InternalHashFinal(); md5.Initialize(); --count; } byte[] key = new byte [8]; Array.Copy(tempHash, 0, key, 0, 8); if(rgbIV != null) { Array.Copy(tempHash, 8, rgbIV, 0, 8); } Array.Clear(tempHash, 0, tempHash.Length); return key; } else { // Use the newer PKCS #5 password generation routine. Reset(); if(alghashname != null) { strHashName = alghashname; } byte[] result = GetBytes(keySize); if(rgbIV != null) { byte[] iv = GetBytes(rgbIV.Length); Array.Copy(iv, 0, rgbIV, 0, rgbIV.Length); Array.Clear(iv, 0, iv.Length); } return result; } }
/// <summary> /// Create the next upload message. /// </summary> private void CreateUploadMsg(MD5CryptoServiceProvider md5Hasher, out AnpMsg m, out List<UInt64> CompletedArray) { m = Share.CreateTransferMsg(KAnpType.KANP_CMD_KFS_PHASE_2); CompletedArray = new List<UInt64>(); // Add the number of submessages field. It will be updated later. m.AddUInt32(0); // Count the number of submessages. int nbSub = 0; // Loop until the message is full or we run out of files to upload. while (m.PayloadSize() < MAX_UPLOAD_SIZE && UploadIndex != FileArray.Length) { KfsUploadBatchFile ubf = FileArray[UploadIndex]; // The transfer of the current file was denied by the // server during phase 1. Do not attempt to talk about // it in phase 2. if (ubf.Status == BatchStatus.Error) { UploadNextFile(); continue; } // The transfer of the current file has been cancelled. Add an // abort submessage and pass to the next file. if (ubf.Status == BatchStatus.Cancelled) { m.AddUInt32(2); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_ABORT); nbSub++; UploadNextFile(); continue; } // The current file is closed. Open the file and set the // remaining size. if (UploadedFile == null) { Debug.Assert(ubf.Status == BatchStatus.Queued); ubf.Status = BatchStatus.Started; UploadedFile = new FileStream(ubf.TransferPath, FileMode.Open, FileAccess.Read, FileShare.Read); RemainingSize = UploadedFile.Length; md5Hasher.Initialize(); } // Add a chunk submessage. if (RemainingSize > 0) { Debug.Assert(ubf.Status == BatchStatus.Started); // Compute the chunk size. UInt32 chunkSize = Math.Max(MIN_UPLOAD_CHUNK_SIZE, MAX_UPLOAD_SIZE - m.PayloadSize()); chunkSize = (UInt32)Math.Min((Int64)chunkSize, RemainingSize); RemainingSize -= chunkSize; // Read the chunk. byte[] chunkData = new byte[chunkSize]; UploadedFile.Read(chunkData, 0, (Int32)chunkSize); // Update the hash. md5Hasher.TransformBlock(chunkData, 0, (int)chunkSize, chunkData, 0); // Add the chunk submessage. m.AddUInt32(3); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_CHUNK); m.AddBin(chunkData); nbSub++; } // Add a commit submessage, remember that the transfer of the file // is being completed in this message and pass to the next file. if (RemainingSize == 0) { Debug.Assert(ubf.Status == BatchStatus.Started); ubf.Status = BatchStatus.Done; // Update the hash. This call is required; Microsoft sucks. md5Hasher.TransformFinalBlock(new byte[0], 0, 0); m.AddUInt32(3); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_COMMIT); m.AddBin(md5Hasher.Hash); nbSub++; CompletedArray.Add(ubf.OrderID); UploadNextFile(); } } // Update the number of submessages. m.Elements[0].UInt32 = (UInt32)nbSub; // If there are no submessages, don't bother sending the message. if (nbSub == 0) m = null; }
public static byte[] PassphraseToKey(SecureString passphrase, int length) { var md5 = new MD5CryptoServiceProvider(); int hashlen = md5.HashSize/8; byte[] buf = new byte[((length + hashlen)/hashlen)*hashlen]; int offset = 0; var plen = passphrase.Length; var insecurePassword = new byte[plen]; var key = new byte[length]; var gch = new GCHandle(); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( delegate { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { gch = GCHandle.Alloc(insecurePassword, GCHandleType.Pinned); } var passwordPtr = IntPtr.Zero; RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( delegate { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { passwordPtr = Marshal.SecureStringToBSTR(passphrase); } unsafe { var pPassword = (char*)passwordPtr; var pInsecurePassword = (char*)gch.AddrOfPinnedObject(); for (var index = 0; index < plen; index++) pInsecurePassword[index] = pPassword[index]; } }, delegate { if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeBSTR(passwordPtr); }, null ); //byte[] pp = Encoding.UTF8.GetBytes(passphrase); while (offset < length) { var s = new MemoryStream(); s.Write(insecurePassword, 0, insecurePassword.Length); if (offset > 0) s.Write(buf, 0, offset); Array.Copy(md5.ComputeHash(s.ToArray()), 0, buf, offset, hashlen); offset += hashlen; md5.Initialize(); } Array.Copy(buf, 0, key, 0, length); }, delegate { if (!gch.IsAllocated) return; // Zero the string. unsafe { var pInsecurePassword = (char*)gch.AddrOfPinnedObject(); for (var index = 0; index < length; index++) pInsecurePassword[index] = '\0'; } gch.Free(); }, null ); return key; }
public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity) { CipherSuite ret = new CipherSuite(); SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm); if (definition.BulkIVSize > 0) bulk.Mode = CipherMode.CBC; bulk.Padding = PaddingMode.None; bulk.BlockSize = definition.BulkIVSize * 8; // get the keys and IVs byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv; Ssl3DeriveBytes prf = new Ssl3DeriveBytes(master, clientrnd, serverrnd, false); client_mac = prf.GetBytes(definition.HashSize); server_mac = prf.GetBytes(definition.HashSize); client_key = prf.GetBytes(definition.BulkKeySize); server_key = prf.GetBytes(definition.BulkKeySize); client_iv = prf.GetBytes(definition.BulkIVSize); server_iv = prf.GetBytes(definition.BulkIVSize); prf.Dispose(); if (definition.Exportable) { // make some extra modifications if the keys are exportable MD5 md5 = new MD5CryptoServiceProvider(); md5.TransformBlock(client_key, 0, client_key.Length, client_key, 0); md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0); md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length); client_key = new byte[definition.BulkExpandedSize]; Buffer.BlockCopy(md5.Hash, 0, client_key, 0, client_key.Length); md5.Initialize(); md5.TransformBlock(server_key, 0, server_key.Length, server_key, 0); md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0); md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length); server_key = new byte[definition.BulkExpandedSize]; Buffer.BlockCopy(md5.Hash, 0, server_key, 0, server_key.Length); md5.Initialize(); md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0); md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length); client_iv = new byte[definition.BulkIVSize]; Buffer.BlockCopy(md5.Hash, 0, client_iv, 0, client_iv.Length); md5.Initialize(); md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0); md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length); server_iv = new byte[definition.BulkIVSize]; Buffer.BlockCopy(md5.Hash, 0, server_iv, 0, server_iv.Length); md5.Clear(); } // generate the cipher objects if (entity == ConnectionEnd.Client) { ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv); ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv); ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac); ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac); } else { ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv); ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv); ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac); ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac); } // clear sensitive data Array.Clear(client_mac, 0, client_mac.Length); Array.Clear(server_mac, 0, server_mac.Length); Array.Clear(client_key, 0, client_key.Length); Array.Clear(server_key, 0, server_key.Length); Array.Clear(client_iv, 0, client_iv.Length); Array.Clear(server_iv, 0, server_iv.Length); return ret; }
private static string EncryptBase(string basestring) { InitCode(); basestring = basestring.Replace("'", "").Replace("\\", ""); string codestring = string.Format("{0}{1}", basestring, EncryptCode); MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider(); provider.Initialize(); byte[] hash = provider.ComputeHash(Encoding.UTF8.GetBytes(codestring)); StringBuilder encryptstring = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { encryptstring.AppendFormat("{0:X2}", hash[i]); } return encryptstring.ToString(); }
public bool CheckValid(string password) { string a1 = string.Format("{0}:{1}:{2}", Username, Realm, password); string a2 = string.Format("{0}:{1}", Method, Uri); MD5 md5 = new MD5CryptoServiceProvider(); md5.Initialize(); byte[] ha1 = md5.ComputeHash(Encoding.ASCII.GetBytes(a1)); byte[] ha2 = md5.ComputeHash(Encoding.ASCII.GetBytes(a2)); string r = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", BitConverter.ToString(ha1).Replace("-", "").ToLower(), Nonce, Nc, Cnonce, Qop, BitConverter.ToString(ha2).Replace("-", "").ToLower()); byte[] hr = md5.ComputeHash(Encoding.ASCII.GetBytes(r)); string calculatedResponse = BitConverter.ToString(hr).Replace("-", "").ToLower(); return calculatedResponse == Response; }
private void Decryption_Test(String filename) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string key = "cosmos"; if (test_md5.Length == 0) { using (FileStream infs = new FileStream("../../../../test/cosmos.jpg", FileMode.Open)) { byte[] buffer = new byte[infs.Length]; infs.Read(buffer, 0, buffer.Length); md5.ComputeHash(buffer); test_md5 = md5.Hash; md5.Initialize(); } } using (FileStream infs = new FileStream("../../../../test/" + filename, FileMode.Open)) { AttacheCase.Unlocker unlocker = new AttacheCase.Unlocker(); Assert.AreEqual(unlocker.Open(infs, key), AttacheCase.Result.OK); Assert.AreEqual(unlocker.Entries.Length, 1); AttacheCase.FileEntry entry = unlocker.Entries[0]; MemoryStream extracted = new MemoryStream(); Assert.AreEqual(unlocker.ExtractFileData(extracted, infs, (uint)entry.Size), AttacheCase.Result.OK); byte[] buffer = new byte[entry.Size]; extracted.Position = 0; extracted.Read(buffer, 0, buffer.Length); md5.ComputeHash(buffer); Assert.IsTrue(test_md5.SequenceEqual(md5.Hash)); } }
public static string AnyscMD5(string filepath, ProgressBar pBar, Label lab) { FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // 缓冲区大小,1MB byte[] buff = new byte[bufferSize]; double blockcount = Math.Ceiling(fs.Length / Convert.ToDouble(bufferSize)); if (pBar.InvokeRequired == true) { SetText LSetText = new SetText(DoSetText); SetValue PSetValue = new SetValue(DoSetMax); pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(blockcount) }); lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(0) + "%" }); } int i = 1; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区 if (offset + readSize < fs.Length) // 不是最后一块 { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // 最后一块 { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; if (pBar.InvokeRequired == true) { SetValue PSetValue = new SetValue(DoSetValue); SetText LSetText = new SetText(DoSetText); pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(i) }); lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(Math.Ceiling((double)(i / blockcount) * 100)) + "%" }); i++; Application.DoEvents(); } } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int j = 0; j < result.Length; j++) { sb.Append(result[j].ToString("x2")); } return sb.ToString(); }
internal Metafile(string path, string[] announceUrls, bool privateFlag, bool setDateFlag, string comment, string outputFilename, int threads, double pieceLenght, string creator, CancellationTokenSource cancelToken) { hasher = new Hasher(cancelToken, threads, pieceLenght); metafile = new BencodeDictionary(); BencodeDictionary infoDict = new BencodeDictionary(); infoDict.Add("private", privateFlag ? 1 : 0); infoDict.Add("piece length", (long)pieceLenght); if (setDateFlag) { TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); int timestamp = (int)t.TotalSeconds; metafile.Add("creation date", timestamp); } if(comment != string.Empty) { metafile.Add("comment", comment); } metafile.Add("created by", creator); metafile.Add("announce", announceUrls[0]); metafile.Add("encoding", Encoding.UTF8.WebName); if(announceUrls.Length > 1) { metafile.AddList("announce-list", announceUrls); } try { string targetType = "NOTFOUND"; if (File.Exists(path)) { targetType = "FILE"; } else if (Directory.Exists(path)) { targetType = "DIR"; } if (targetType == "NOTFOUND") { throw new FileNotFoundException(); } if (targetType == "DIR") { DirectoryInfo dir = new DirectoryInfo(path); files.AddRange(dir.GetFiles("*", SearchOption.AllDirectories)); infoDict.Add("name", dir.Name); BencodeList fileList = new BencodeList(); string[] rootPathSegements = dir.FullName.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); foreach(FileInfo file in files) { BencodeDictionary fileDictionary = new BencodeDictionary(); string filePath = file.FullName; hasher.AddFile(filePath); fileDictionary.Add("length", file.Length); Task t = Task.Factory.StartNew(() => { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { md5.Initialize(); FileStream f = File.OpenRead(filePath); byte[] hash = md5.ComputeHash(f); StringBuilder sb = new StringBuilder(); foreach (byte h in hash) { sb.Append(h.ToString("X2")); } fileDictionary.Add("md5sum", sb.ToString()); f.Dispose(); } }); // Pad maken string[] segments = filePath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); BencodeList bencodePath = new BencodeList(); for (int i = 0; i < segments.Length; i++) { if (rootPathSegements.Length > i) { if (segments[i] == rootPathSegements[i]) { continue; } } else { bencodePath.Add(segments[i]); } } fileDictionary.Add("path", bencodePath); t.Wait(); fileList.Add(fileDictionary); } infoDict.Add("files", fileList); hasher.ChunkFiles(); } if (targetType == "FILE") { FileInfo fi = new FileInfo(path); files.Add(fi); hasher.AddFile(path); Task t = Task.Factory.StartNew(hasher.ChunkFiles); infoDict.Add("name", fi.Name); infoDict.Add("length", fi.Length); using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { md5.Initialize(); FileStream f = File.OpenRead(path); byte[] hash = md5.ComputeHash(f); StringBuilder sb = new StringBuilder(); foreach (byte h in hash) { sb.Append(h.ToString("X2")); } infoDict.Add("md5sum", sb.ToString()); f.Dispose(); } t.Wait(); } // hashen hasher.ComputeHashes(); infoDict.Add("pieces", hasher.GetHashes()); //afronden metafile.Add("info", infoDict); Debug.WriteLine("Bencode Dictionary: \n\n" + metafile.ToString()); } catch (DirectoryNotFoundException e) { throw new FatalException(e); } catch (FileNotFoundException e) { throw new FatalException(e); } catch (IOException e) { throw new FatalException(e); } }
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; }
static void Test2(int count) { byte[] bytes = new byte[count]; for (int idx = 0; idx < count; idx += 16) Array.Copy(Guid.NewGuid().ToByteArray(), 0, bytes, idx, Math.Min(16, count - idx)); MD5 md5dotNet = new MD5CryptoServiceProvider(); md5dotNet.Initialize(); MD5Managed md5m = new MD5Managed(); md5m.Initialize(); byte[] result1 = md5dotNet.ComputeHash(bytes); byte[] result2 = md5m.ComputeHash(bytes); if (!CompareBytes(result1, result2)) { count.GetType(); //throw new Exception("Bug in MD5Managed..."); } }