public static SHA1 CreateSHA1() { return(SHA1.Create(CryptoConfig.AllowOnlyFipsAlgorithms ? _SHA1CryptoServiceProvider : _SHA1Cng)); }
public static byte[] GetSHA1Hash(byte[] key) { var sha1Hasher = SHA1.Create(); return(sha1Hasher.ComputeHash(key)); }
/// <summary> /// 验证 SHA1 值 /// </summary> /// <param name="input"> 未加密的字符串 </param> /// <param name="encoding"> 字符编码 </param> /// <returns></returns> public static bool VerifySHA1Value(string input, Encoding encoding) { return(VerifyHashValue(SHA1.Create(), input, SHA1Encrypt(input, encoding), encoding)); }
private void btnsave_Click(object sender, EventArgs e) { errorProvider1.Clear(); if (combo_usertype.Text.Length <= 0) { errorProvider1.SetError(combo_usertype, "This field cannot be empty"); } else if (txtusername.Text.Length <= 0) { errorProvider1.SetError(txtusername, "This field cannot be empty"); } else if (txtpassword.Text.Length <= 0) { errorProvider1.SetError(txtpassword, "This field cannot be empty"); } else if (txtcon_password.Text.Length <= 0) { errorProvider1.SetError(txtcon_password, "This field cannot be empty"); } else if (txtpassword.Text != txtcon_password.Text) { errorProvider1.SetError(txtcon_password, "Password Mismatch"); } else { try { String password = txtpassword.Text; // byte[] hash = null; using (SHA1 sha1 = SHA1.Create()) { // sha1.Initialize(); byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; ++i) { sb.Append(hash[i].ToString("x2")); } password = sb.ToString(); } conn.Open(); String InsertQuery = "INSERT INTO New_User VALUES('" + combo_usertype.Text + "','" + txtusername.Text + "', '" + password + "', '" + label11.Text + "')"; SqlDataAdapter execute = new SqlDataAdapter(InsertQuery, conn); execute.SelectCommand.ExecuteNonQuery(); MessageBox.Show("You've inserted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information); conn.Close(); SqlDataAdapter data = new SqlDataAdapter("Select ID,User_Type,User_Name,Create_Date from New_User", conn); DataTable dt = new DataTable(); data.Fill(dt); dataGridView1.DataSource = dt; combo_usertype.Text = ""; txtusername.Text = ""; txtpassword.Text = ""; txtcon_password.Text = ""; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } conn.Close(); }
string CalculateShaPassHash(string name, string password) { SHA1 sha = SHA1.Create(); return(sha.ComputeHash(Encoding.UTF8.GetBytes(name + ":" + password)).ToHexString()); }
/// <summary> /// </summary> /// <param name="pass"> /// </param> /// <returns> /// </returns> public static byte[] Sha1HashBytes(string pass) { SHA1 sha = SHA1.Create(); return(sha.ComputeHash(Encoding.UTF8.GetBytes(pass))); }
private void InitializeNetwork() { lock (m_initializeLock) { m_configuration.Lock(); if (m_status == NetPeerStatus.Running) { return; } if (m_configuration.m_enableUPnP) { m_upnp = new NetUPnP(this); } InitializePools(); m_releasedIncomingMessages.Clear(); m_unsentUnconnectedMessages.Clear(); m_handshakes.Clear(); // bind to socket IPEndPoint iep = null; iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port); EndPoint ep = (EndPoint)iep; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize; m_socket.SendBufferSize = m_configuration.SendBufferSize; m_socket.Blocking = false; m_socket.Bind(ep); IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint; LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound); m_listenPort = boundEp.Port; m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize]; m_sendBuffer = new byte[m_configuration.SendBufferSize]; m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error); m_readHelperMessage.m_data = m_receiveBuffer; byte[] macBytes = new byte[8]; NetRandom.Instance.NextBytes(macBytes); #if IS_MAC_AVAILABLE try { System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress(); if (pa != null) { macBytes = pa.GetAddressBytes(); LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes)); } else { LogWarning("Failed to get Mac address"); } } catch (NotSupportedException) { // not supported; lets just kee the random bytes set above } #endif byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode()); byte[] combined = new byte[epBytes.Length + macBytes.Length]; Array.Copy(epBytes, 0, combined, 0, epBytes.Length); Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length); m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0); m_status = NetPeerStatus.Running; } }
/// <summary> /// Computes the SHA1 hash /// </summary> /// <param name="data"></param> /// <returns></returns> private byte[] ComputeSHA1(byte[] data) { var sha1 = SHA1.Create(); return(sha1.ComputeHash(data)); }
private Md5SingletonHelper() { this.md5 = MD5.Create(); this.sha1 = SHA1.Create(); this.sha256 = SHA256.Create(); }
private string EncryptPassword(string password) { return(Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(password)))); }
// FIXME: use timeout Message ProcessClientKeyExchange(Message request, TimeSpan timeout) { // FIXME: use correct buffer size MessageBuffer buffer = request.CreateBufferedCopy(0x10000); WSTrustRequestSecurityTokenResponseReader reader = new WSTrustRequestSecurityTokenResponseReader(Constants.WstTlsnegoProofTokenType, buffer.CreateMessage().GetReaderAtBodyContents(), SecurityTokenSerializer, null); reader.Read(); TlsServerSessionInfo tlsInfo; if (!sessions.TryGetValue(reader.Value.Context, out tlsInfo)) { throw new SecurityNegotiationException(String.Format("The context '{0}' does not exist in this SSL negotiation manager", reader.Value.Context)); } TlsServerSession tls = tlsInfo.Tls; AppendNegotiationMessageXml(buffer.CreateMessage().GetReaderAtBodyContents(), tlsInfo); //Console.WriteLine (System.Text.Encoding.UTF8.GetString (tlsInfo.Messages.ToArray ())); tls.ProcessClientKeyExchange(reader.Value.BinaryExchange.Value); byte [] serverFinished = tls.ProcessServerFinished(); // The shared key is computed as recommended in WS-Trust: // P_SHA1(encrypted_key,SHA1(exc14n(RST..RSTRs))+"CK-HASH") byte [] hash = SHA1.Create().ComputeHash(tlsInfo.Messages.ToArray()); byte [] key = tls.CreateHash(tls.MasterSecret, hash, "CK-HASH"); byte [] keyTlsApplied = tls.ProcessApplicationData(key); foreach (byte b in hash) { Console.Write("{0:X02} ", b); } Console.WriteLine(); foreach (byte b in key) { Console.Write("{0:X02} ", b); } Console.WriteLine(); WstRequestSecurityTokenResponseCollection col = new WstRequestSecurityTokenResponseCollection(); WstRequestSecurityTokenResponse rstr = new WstRequestSecurityTokenResponse(SecurityTokenSerializer); rstr.Context = reader.Value.Context; rstr.TokenType = Constants.WsscContextToken; DateTime from = DateTime.Now; // FIXME: not sure if arbitrary key is used here. SecurityContextSecurityToken sct = SecurityContextSecurityToken.CreateCookieSecurityContextToken( // Create a new context. // (do not use sslnego context here.) new UniqueId(), "uuid-" + Guid.NewGuid(), key, from, // FIXME: use LocalServiceSecuritySettings.NegotiationTimeout from.AddHours(8), null, owner.Manager.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder); rstr.RequestedSecurityToken = sct; // without this ProcessApplicationData(), .NET seems // to fail recovering the key. rstr.RequestedProofToken = keyTlsApplied; rstr.RequestedAttachedReference = new LocalIdKeyIdentifierClause(sct.Id); rstr.RequestedUnattachedReference = new SecurityContextKeyIdentifierClause(sct.ContextId, null); WstLifetime lt = new WstLifetime(); lt.Created = from; lt.Expires = from.Add(SecurityBindingElement.LocalServiceSettings.IssuedCookieLifetime); rstr.Lifetime = lt; rstr.BinaryExchange = new WstBinaryExchange(Constants.WstBinaryExchangeValueTls); rstr.BinaryExchange.Value = serverFinished; col.Responses.Add(rstr); // Authenticator is mandatory for MS sslnego. rstr = new WstRequestSecurityTokenResponse(SecurityTokenSerializer); rstr.Context = reader.Value.Context; rstr.Authenticator = tls.CreateHash(key, hash, "AUTH-HASH"); col.Responses.Add(rstr); sessions.Remove(reader.Value.Context); // FIXME: get correct tokenRequestor address (probably identity authorized?) if (owner.IssuedSecurityTokenHandler != null) { owner.IssuedSecurityTokenHandler(sct, request.Headers.ReplyTo); } return(Message.CreateMessage(request.Version, Constants.WstIssueReplyAction, col)); }
// This Function returns: // Good : Everything Worked Correctly // RescanNeeded : Something unexpectidly changed in the files, so Stop prompt user to rescan. // LogicError : This Should never happen and is a logic problem in the code // FileSystemError : Something is wrong with the files /// <summary> /// Performs the ROMVault File Copy, with the source and destination being files or zipped files /// </summary> /// <param name="fileIn">This is the file being copied, it may be a zipped file or a regular file system file</param> /// <param name="zipFileOut">This is the zip file that is being writen to, if it is null a new zip file will be made if we are coping to a zip</param> /// <param name="zipFilenameOut">This is the name of the .zip file to be made that will be created in zipFileOut</param> /// <param name="fileOut">This is the actual output filename</param> /// <param name="forceRaw">if true then we will do a raw copy, this is so that we can copy corrupt zips</param> /// <param name="error">This is the returned error message if this copy fails</param> /// <param name="foundFile">If we are SHA1/MD5 checking the source file for the first time, and it is different from what we expected the correct values for this file are returned in foundFile</param> /// <returns>ReturnCode.Good is the valid return code otherwire we have an error</returns> public static ReturnCode CopyFile(RvFile fileIn, ref ZipFile zipFileOut, string zipFilenameOut, RvFile fileOut, bool forceRaw, out string error, out RvFile foundFile) { foundFile = null; error = ""; if (_buffer == null) { _buffer = new byte[BufferSize]; } bool rawCopy = RawCopy(fileIn, fileOut, forceRaw); ulong streamSize = 0; ushort compressionMethod = 8; bool sourceTrrntzip = false; ZipFile zipFileIn = null; System.IO.Stream readStream = null; bool isZeroLengthFile = DBHelper.IsZeroLengthFile(fileOut); if (!isZeroLengthFile) { #region check that the in and out file match if (fileOut.FileStatusIs(FileStatus.SizeFromDAT) && fileOut.Size != null && fileIn.Size != fileOut.Size) { error = "Source and destination Size does not match. Logic Error."; return(ReturnCode.LogicError); } if (fileOut.FileStatusIs(FileStatus.CRCFromDAT) && fileOut.CRC != null && !ArrByte.bCompare(fileIn.CRC, fileOut.CRC)) { error = "Source and destination CRC does not match. Logic Error."; return(ReturnCode.LogicError); } if (fileOut.FileStatusIs(FileStatus.SHA1FromDAT) && fileIn.FileStatusIs(FileStatus.SHA1Verified)) { if (fileIn.SHA1 != null && fileOut.SHA1 != null && !ArrByte.bCompare(fileIn.SHA1, fileOut.SHA1)) { error = "Source and destination SHA1 does not match. Logic Error."; return(ReturnCode.LogicError); } } if (fileOut.FileStatusIs(FileStatus.MD5CHDFromDAT) && fileIn.FileStatusIs(FileStatus.MD5Verified)) { if (fileIn.MD5 != null && fileOut.MD5 != null && !ArrByte.bCompare(fileIn.MD5, fileOut.MD5)) { error = "Source and destination SHA1 does not match. Logic Error."; return(ReturnCode.LogicError); } } #endregion #region Find and Check/Open Input Files if (fileIn.FileType == FileType.ZipFile) // Input is a ZipFile { RvDir zZipFileIn = fileIn.Parent; if (zZipFileIn.FileType != FileType.Zip) { error = "Zip File Open but Source File is not a zip, Logic Error."; return(ReturnCode.LogicError); } string fileNameIn = zZipFileIn.FullName; sourceTrrntzip = (zZipFileIn.ZipStatus & ZipStatus.TrrntZip) == ZipStatus.TrrntZip; //if (zZipFileIn.ZipFileType == RvZip.ZipType.Zip) //{ zipFileIn = new ZipFile(); ZipReturn zr1; if (fileIn.ZipFileHeaderPosition != null) { zr1 = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.TimeStamp, false); } else { zr1 = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.TimeStamp, true); } switch (zr1) { case ZipReturn.ZipGood: break; case ZipReturn.ZipErrorFileNotFound: error = "File not found, Rescan required before fixing " + fileIn.Name; return(ReturnCode.FileSystemError); case ZipReturn.ZipErrorTimeStamp: error = "File has changed, Rescan required before fixing " + fileIn.Name; return(ReturnCode.FileSystemError); default: error = "Error Open Zip" + zr1 + ", with File " + fileIn.DatFullName; return(ReturnCode.FileSystemError); } if (fileIn.ZipFileHeaderPosition != null) { zipFileIn.ZipFileOpenReadStreamQuick((ulong)fileIn.ZipFileHeaderPosition, rawCopy, out readStream, out streamSize, out compressionMethod); } else { zipFileIn.ZipFileOpenReadStream(fileIn.ZipFileIndex, rawCopy, out readStream, out streamSize, out compressionMethod); } } else // Input is a regular file { string fileNameIn = fileIn.FullName; if (!IO.File.Exists(fileNameIn)) { error = "Rescan needed, File Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } IO.FileInfo fileInInfo = new IO.FileInfo(fileNameIn); if (fileInInfo.LastWriteTime != fileIn.TimeStamp) { error = "Rescan needed, File Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } int errorCode = IO.FileStream.OpenFileRead(fileNameIn, out readStream); if (errorCode != 0) { error = new Win32Exception(errorCode).Message + ". " + fileNameIn; return(ReturnCode.FileSystemError); } if (fileIn.Size == null) { error = "Null File Size found in Fixing File :" + fileNameIn; return(ReturnCode.LogicError); } streamSize = (ulong)fileIn.Size; if ((ulong)readStream.Length != streamSize) { error = "Rescan needed, File Length Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } } #endregion } else { sourceTrrntzip = true; } if (!rawCopy && (Settings.FixLevel == eFixLevel.TrrntZipLevel1 || Settings.FixLevel == eFixLevel.TrrntZipLevel2 || Settings.FixLevel == eFixLevel.TrrntZipLevel3)) { compressionMethod = 8; } #region Find and Check/Open Output Files System.IO.Stream writeStream; if (fileOut.FileType == FileType.ZipFile) { // if ZipFileOut == null then we have not open the output zip yet so open it from writing. if (zipFileOut == null) { if (IO.Path.GetFileName(zipFilenameOut) == "__ROMVault.tmp") { if (IO.File.Exists(zipFilenameOut)) { IO.File.Delete(zipFilenameOut); } } else if (IO.File.Exists(zipFilenameOut)) { error = "Rescan needed, File Changed :" + zipFilenameOut; return(ReturnCode.RescanNeeded); } zipFileOut = new ZipFile(); ZipReturn zrf = zipFileOut.ZipFileCreate(zipFilenameOut); if (zrf != ZipReturn.ZipGood) { error = "Error Opening Write Stream " + zrf; return(ReturnCode.FileSystemError); } } else { if (zipFileOut.ZipOpen != ZipOpenType.OpenWrite) { error = "Output Zip File is not set to OpenWrite, Logic Error."; return(ReturnCode.LogicError); } if (zipFileOut.ZipFilename != (new IO.FileInfo(zipFilenameOut).FullName)) { error = "Output Zip file has changed name from " + zipFileOut.ZipFilename + " to " + zipFilenameOut + ". Logic Error"; return(ReturnCode.LogicError); } } if (fileIn.Size == null) { error = "Null File Size found in Fixing File :" + fileIn.FullName; return(ReturnCode.LogicError); } ZipReturn zr = zipFileOut.ZipFileOpenWriteStream(rawCopy, sourceTrrntzip, fileOut.Name, (ulong)fileIn.Size, compressionMethod, out writeStream); if (zr != ZipReturn.ZipGood) { error = "Error Opening Write Stream " + zr; return(ReturnCode.FileSystemError); } } else { if (IO.File.Exists(zipFilenameOut) && fileOut.GotStatus != GotStatus.Corrupt) { error = "Rescan needed, File Changed :" + zipFilenameOut; return(ReturnCode.RescanNeeded); } int errorCode = IO.FileStream.OpenFileWrite(zipFilenameOut, out writeStream); if (errorCode != 0) { error = new Win32Exception(errorCode).Message + ". " + zipFilenameOut; return(ReturnCode.FileSystemError); } } #endregion byte[] bCRC; byte[] bMD5 = null; byte[] bSHA1 = null; if (!isZeroLengthFile) { #region Do Data Tranfer CRC32Hash crc32 = null; MD5 md5 = null; SHA1 sha1 = null; if (!rawCopy) { crc32 = new CRC32Hash(); md5 = MD5.Create(); sha1 = SHA1.Create(); } ulong sizetogo = streamSize; while (sizetogo > 0) { int sizenow = sizetogo > BufferSize ? BufferSize : (int)sizetogo; try { readStream.Read(_buffer, 0, sizenow); } catch (ZlibException) { if (fileIn.FileType == FileType.ZipFile && zipFileIn != null) { ZipReturn zr = zipFileIn.ZipFileCloseReadStream(); if (zr != ZipReturn.ZipGood) { error = "Error Closing " + zr + " Stream :" + zipFileIn.Filename(fileIn.ReportIndex); return(ReturnCode.FileSystemError); } zipFileIn.ZipFileClose(); } else { readStream.Close(); } if (fileOut.FileType == FileType.ZipFile) { ZipReturn zr = zipFileOut.ZipFileCloseWriteStream(new byte[] { 0, 0, 0, 0 }); if (zr != ZipReturn.ZipGood) { error = "Error Closing Stream " + zr; return(ReturnCode.FileSystemError); } zipFileOut.ZipFileRollBack(); } else { writeStream.Flush(); writeStream.Close(); IO.File.Delete(zipFilenameOut); } error = "Error in Data Stream"; return(ReturnCode.SourceCRCCheckSumError); } catch (Exception e) { error = "Error reading Source File " + e.Message; return(ReturnCode.FileSystemError); } if (!rawCopy) { crc32.TransformBlock(_buffer, 0, sizenow, null, 0); md5.TransformBlock(_buffer, 0, sizenow, null, 0); sha1.TransformBlock(_buffer, 0, sizenow, null, 0); } try { writeStream.Write(_buffer, 0, sizenow); } catch (Exception e) { Debug.WriteLine(e.Message); error = "Error writing out file. " + Environment.NewLine + e.Message; return(ReturnCode.FileSystemError); } sizetogo = sizetogo - (ulong)sizenow; } writeStream.Flush(); #endregion #region Collect Checksums // if we did a full copy then we just calculated all the checksums while doing the copy if (!rawCopy) { crc32.TransformFinalBlock(_buffer, 0, 0); md5.TransformFinalBlock(_buffer, 0, 0); sha1.TransformFinalBlock(_buffer, 0, 0); bCRC = crc32.Hash; bMD5 = md5.Hash; bSHA1 = sha1.Hash; } // if we raw copied and the source file has been FileChecked then we can trust the checksums in the source file else { bCRC = ArrByte.Copy(fileIn.CRC); if (fileIn.FileStatusIs(FileStatus.MD5Verified)) { bMD5 = ArrByte.Copy(fileIn.MD5); } if (fileIn.FileStatusIs(FileStatus.SHA1Verified)) { bSHA1 = ArrByte.Copy(fileIn.SHA1); } } #endregion #region close the ReadStream if (fileIn.FileType == FileType.ZipFile && zipFileIn != null) { ZipReturn zr = zipFileIn.ZipFileCloseReadStream(); if (zr != ZipReturn.ZipGood) { error = "Error Closing " + zr + " Stream :" + zipFileIn.Filename(fileIn.ReportIndex); return(ReturnCode.FileSystemError); } zipFileIn.ZipFileClose(); } else { readStream.Close(); //if (IO.File.Exists(tmpFilename)) // IO.File.Delete(tmpFilename); } #endregion } else { // Zero Length File (Directory in a Zip) if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileAddDirectory(); } bCRC = VarFix.CleanMD5SHA1("00000000", 8); bMD5 = VarFix.CleanMD5SHA1("d41d8cd98f00b204e9800998ecf8427e", 32); bSHA1 = VarFix.CleanMD5SHA1("da39a3ee5e6b4b0d3255bfef95601890afd80709", 40); } #region close the WriteStream if (fileOut.FileType == FileType.ZipFile) { ZipReturn zr = zipFileOut.ZipFileCloseWriteStream(bCRC); if (zr != ZipReturn.ZipGood) { error = "Error Closing Stream " + zr; return(ReturnCode.FileSystemError); } fileOut.ZipFileIndex = zipFileOut.LocalFilesCount() - 1; fileOut.ZipFileHeaderPosition = zipFileOut.LocalHeader(fileOut.ZipFileIndex); } else { writeStream.Flush(); writeStream.Close(); IO.FileInfo fi = new IO.FileInfo(zipFilenameOut); fileOut.TimeStamp = fi.LastWriteTime; } #endregion if (!isZeroLengthFile) { if (!rawCopy) { if (!ArrByte.bCompare(bCRC, fileIn.CRC)) { fileIn.GotStatus = GotStatus.Corrupt; error = "Source CRC does not match Source Data stream, corrupt Zip"; if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.SourceCRCCheckSumError); } fileIn.FileStatusSet(FileStatus.CRCVerified | FileStatus.SizeVerified); bool sourceFailed = false; // check to see if we have a MD5 from the DAT file if (fileIn.FileStatusIs(FileStatus.MD5FromDAT)) { if (fileIn.MD5 == null) { error = "Should have an filein MD5 from Dat but not found. Logic Error."; return(ReturnCode.LogicError); } if (!ArrByte.bCompare(fileIn.MD5, bMD5)) { sourceFailed = true; } else { fileIn.FileStatusSet(FileStatus.MD5Verified); } } // check to see if we have an MD5 (not from the DAT) so must be from previously scanning this file. else if (fileIn.MD5 != null) { if (!ArrByte.bCompare(fileIn.MD5, bMD5)) { // if we had an MD5 from a preview scan and it now does not match, something has gone really bad. error = "The MD5 found does not match a previously scanned MD5, this should not happen, unless something got corrupt."; return(ReturnCode.LogicError); } } else // (FileIn.MD5 == null) { fileIn.MD5 = bMD5; fileIn.FileStatusSet(FileStatus.MD5Verified); } // check to see if we have a SHA1 from the DAT file if (fileIn.FileStatusIs(FileStatus.SHA1FromDAT)) { if (fileIn.SHA1 == null) { error = "Should have an filein SHA1 from Dat but not found. Logic Error."; return(ReturnCode.LogicError); } if (!ArrByte.bCompare(fileIn.SHA1, bSHA1)) { sourceFailed = true; } else { fileIn.FileStatusSet(FileStatus.SHA1Verified); } } // check to see if we have an SHA1 (not from the DAT) so must be from previously scanning this file. else if (fileIn.SHA1 != null) { if (!ArrByte.bCompare(fileIn.SHA1, bSHA1)) { // if we had an SHA1 from a preview scan and it now does not match, something has gone really bad. error = "The SHA1 found does not match a previously scanned SHA1, this should not happen, unless something got corrupt."; return(ReturnCode.LogicError); } } else // (FileIn.SHA1 == null) { fileIn.SHA1 = bSHA1; fileIn.FileStatusSet(FileStatus.SHA1Verified); } if (sourceFailed) { if (fileIn.FileType == FileType.ZipFile) { RvFile tZFile = new RvFile(FileType.ZipFile); foundFile = tZFile; tZFile.ZipFileIndex = fileIn.ZipFileIndex; tZFile.ZipFileHeaderPosition = fileIn.ZipFileHeaderPosition; } else { foundFile = new RvFile(fileIn.FileType); } foundFile.Name = fileIn.Name; foundFile.Size = fileIn.Size; foundFile.CRC = bCRC; foundFile.MD5 = bMD5; foundFile.SHA1 = bSHA1; foundFile.TimeStamp = fileIn.TimeStamp; foundFile.SetStatus(DatStatus.NotInDat, GotStatus.Got); foundFile.FileStatusSet(FileStatus.SizeVerified | FileStatus.CRCVerified | FileStatus.MD5Verified | FileStatus.SHA1Verified); if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.SourceCheckSumError); } } } if (fileOut.FileType == FileType.ZipFile) { fileOut.FileStatusSet(FileStatus.SizeFromHeader | FileStatus.CRCFromHeader); } if (fileOut.FileStatusIs(FileStatus.CRCFromDAT) && fileOut.CRC != null && !ArrByte.bCompare(fileOut.CRC, bCRC)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.CRC = bCRC; if (!rawCopy || fileIn.FileStatusIs(FileStatus.CRCVerified)) { fileOut.FileStatusSet(FileStatus.CRCVerified); } if (bSHA1 != null) { if (fileOut.FileStatusIs(FileStatus.SHA1FromDAT) && fileOut.SHA1 != null && !ArrByte.bCompare(fileOut.SHA1, bSHA1)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.SHA1 = bSHA1; fileOut.FileStatusSet(FileStatus.SHA1Verified); } if (bMD5 != null) { if (fileOut.FileStatusIs(FileStatus.MD5FromDAT) && fileOut.MD5 != null && !ArrByte.bCompare(fileOut.MD5, bMD5)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.MD5 = bMD5; fileOut.FileStatusSet(FileStatus.MD5Verified); } if (fileIn.Size != null) { fileOut.Size = fileIn.Size; fileOut.FileStatusSet(FileStatus.SizeVerified); } if (fileIn.GotStatus == GotStatus.Corrupt) { fileOut.GotStatus = GotStatus.Corrupt; } else { fileOut.GotStatus = GotStatus.Got; // Changes RepStatus to Correct } fileOut.FileStatusSet(FileStatus.SizeVerified); if (fileOut.SHA1CHD == null && fileIn.SHA1CHD != null) { fileOut.SHA1CHD = fileIn.SHA1CHD; } if (fileOut.MD5CHD == null && fileIn.MD5CHD != null) { fileOut.MD5CHD = fileIn.MD5CHD; } fileOut.CHDVersion = fileIn.CHDVersion; fileOut.FileStatusSet(FileStatus.SHA1CHDFromHeader | FileStatus.MD5CHDFromHeader | FileStatus.SHA1CHDVerified | FileStatus.MD5CHDVerified, fileIn); return(ReturnCode.Good); }
private void writeToStream(Stream writeStream) { fireDebug("Writing Ticket..."); fireDebug(" Encrypting Title Key..."); encryptTitleKey(); fireDebug(" -> Decrypted Title Key: {0}", Shared.ByteArrayToString(decryptedTitleKey)); fireDebug(" -> Encrypted Title Key: {0}", Shared.ByteArrayToString(encryptedTitleKey)); if (fakeSign) { fireDebug(" Clearing Signature..."); signature = new byte[256]; } //Clear Signature if we fake Sign MemoryStream ms = new MemoryStream(); ms.Seek(0, SeekOrigin.Begin); fireDebug(" Writing Signature Exponent... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(signatureExponent)), 0, 4); fireDebug(" Writing Signature... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(signature, 0, signature.Length); fireDebug(" Writing Padding... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(padding, 0, padding.Length); fireDebug(" Writing Issuer... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(issuer, 0, issuer.Length); fireDebug(" Writing Unknown... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(unknown, 0, unknown.Length); fireDebug(" Writing Title Key... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(encryptedTitleKey, 0, encryptedTitleKey.Length); fireDebug(" Writing Unknown2... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.WriteByte(unknown2); fireDebug(" Writing Ticket ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(ticketId)), 0, 8); fireDebug(" Writing Console ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(consoleId)), 0, 4); fireDebug(" Writing Title ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(titleId)), 0, 8); fireDebug(" Writing Unknwon3... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(unknown3)), 0, 2); fireDebug(" Writing NumOfDLC... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(numOfDlc)), 0, 2); fireDebug(" Writing Unknwon4... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(unknown4)), 0, 8); fireDebug(" Writing Padding2... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.WriteByte(padding2); fireDebug(" Writing Common Key Index... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.WriteByte(commonKeyIndex); fireDebug(" Writing Unknown5... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(unknown5, 0, unknown5.Length); fireDebug(" Writing Unknown6... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(unknown6, 0, unknown6.Length); fireDebug(" Writing Padding3... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(padding3)), 0, 2); fireDebug(" Writing Enable Time Limit... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(enableTimeLimit)), 0, 4); fireDebug(" Writing Time Limit... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(BitConverter.GetBytes(Shared.Swap(timeLimit)), 0, 4); fireDebug(" Writing Padding4... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper()); ms.Write(padding4, 0, padding4.Length); byte[] tik = ms.ToArray(); ms.Dispose(); //fake Sign if (fakeSign) { fireDebug(" Fakesigning Ticket..."); byte[] hash = new byte[20]; SHA1 s = SHA1.Create(); for (ushort i = 0; i < 0xFFFF; i++) { byte[] bytes = BitConverter.GetBytes(i); tik[498] = bytes[1]; tik[499] = bytes[0]; hash = s.ComputeHash(tik); if (hash[0] == 0x00) { fireDebug(" -> Signed ({0})", i); break; } //Win! It's signed... if (i == 0xFFFF - 1) { fireDebug(" -> Signing Failed..."); throw new Exception("Fakesigning failed..."); } } s.Clear(); } writeStream.Seek(0, SeekOrigin.Begin); writeStream.Write(tik, 0, tik.Length); fireDebug("Writing Ticket Finished..."); }
static byte[] Hash(string input) { return(SHA1.Create().ComputeHash(Encoding.GetEncoding(28591).GetBytes(input))); }
private void authorize(string login, string password, bool createNew, ContentControl statusControl) { statusControl.Visibility = Visibility.Hidden; FileSystemSettingsWindow fssw = null; if (createNew) { fssw = new FileSystemSettingsWindow(); if (!fssw.ShowDialog().Value) { return; } } FileDialog dialog = createNew ? (FileDialog) new SaveFileDialog() : (FileDialog) new OpenFileDialog(); dialog.DefaultExt = "mfs"; dialog.Filter = "Meow disk (*.mfs)|*.mfs"; UserInfo userInfo = null; if (dialog.ShowDialog() == true) { FileSystemController fsctrl = new FileSystemController(); SHA1 sha = SHA1.Create(); string digest = UsefulThings.ENCODING.GetString(sha.ComputeHash(UsefulThings.ENCODING.GetBytes(password))); digest = UsefulThings.replaceControlChars(digest); bool success; try { if (createNew) { //Создать //TODO 15.11: запрашивать параметры создаваемого диска? /*ushort clusterSize = FileSystemController.FACTOR * 4; //Блок = 4 КБ * ushort rootSize = (ushort)(clusterSize * 10); //Корневой каталог = 10 блоков * uint diskSize = 50 * FileSystemController.FACTOR * FileSystemController.FACTOR; //Раздел = 50 МБ (или 1 МБ для тестов)*/ fsctrl.SuperBlock = new SuperBlock(fsctrl, "MeowFS", fssw.ClusterSizeBytes, fssw.RootSizeBytes, fssw.DiskSizeBytes); fsctrl.Fat = new FAT(fsctrl, (int)(fssw.DiskSizeBytes / fssw.ClusterSizeBytes)); fsctrl.RootDir = UsefulThings.ENCODING.GetBytes(new String('\0', fssw.RootSizeBytes)); fsctrl.createSpace(dialog.FileName, login, digest); userInfo = new UserInfo(1, login, 1, UserInfo.DEFAULT_GROUP, UserInfo.Roles.ADMIN); success = true; } else { //Открыть fsctrl.openSpace(dialog.FileName); byte[] users = fsctrl.readFile("/users.sys", false); string[] usersStr = UsefulThings.fileFromByteArrToStringArr(users); string[] tokens = { "", "", "", "" }; //0 = login, 1 = digest, 2 = gid, 3 = role ushort uid; success = false; for (uid = 1; uid <= usersStr.Length && !success; ++uid) { tokens = usersStr[uid - 1].Split(UsefulThings.USERDATA_SEPARATOR.ToString().ToArray(), StringSplitOptions.None); success = tokens[0].ToLower().Equals(login.ToLower()) && tokens[1].Equals(digest); } if (success) { --uid; byte[] groups = fsctrl.readFile("/groups.sys", false); string[] groupsStr = UsefulThings.fileFromByteArrToStringArr(groups); ushort gid = ushort.Parse(tokens[2]); if (gid > groups.Length) { gid = 1; } userInfo = new UserInfo(uid, tokens[0], gid, groupsStr[gid - 1], (UserInfo.Roles)Enum.Parse(typeof(UserInfo.Roles), tokens[3])); } } } catch { success = false; } finally { fsctrl.closeSpace(); } if (success) { Session.userInfo = userInfo; MainWindow mw = new MainWindow(dialog.FileName); Close(); mw.Show(); } else { statusControl.Content = "Доступ не разрешён"; statusControl.Visibility = Visibility.Visible; } } }
/// <summary> /// Executes the <paramref name="actions"/> step by step, and emits /// <see cref="ActionEvaluation"/> for each step. /// </summary> /// <param name="blockHash">The <see cref="Block{T}.Hash"/> of <see cref="Block{T}"/> that /// <paramref name="actions"/> belongs to.</param> /// <param name="blockIndex">The <see cref="Block{T}.Index"/> of <see cref="Block{T}"/> that /// <paramref name="actions"/> belongs to.</param> /// <param name="txid">The <see cref="Transaction{T}.Id"/> of <see cref="Transaction{T}"/> /// that <paramref name="actions"/> belongs to. This can be <c>null</c> on rehearsal mode /// or if an action is a <see cref="IBlockPolicy{T}.BlockAction"/>.</param> /// <param name="previousStates">The states immediately before <paramref name="actions"/> /// being executed. Note that its <see cref="IAccountStateDelta.UpdatedAddresses"/> are /// remained to the returned next states.</param> /// <param name="minerAddress">An address of block miner.</param> /// <param name="signer">Signer of the <paramref name="actions"/>.</param> /// <param name="signature"><see cref="Transaction{T}"/> signature used to generate random /// seeds.</param> /// <param name="actions">Actions to evaluate.</param> /// <param name="rehearsal">Pass <c>true</c> if it is intended /// to be dry-run (i.e., the returned result will be never used). /// The default value is <c>false</c>.</param> /// <returns>Enumerates <see cref="ActionEvaluation"/>s for each one in /// <paramref name="actions"/>. The order is the same to the <paramref name="actions"/>. /// Note that each <see cref="IActionContext.Random"/> object /// has a unconsumed state. /// </returns> /// <exception cref="UnexpectedlyTerminatedActionException"> /// Thrown when one of <paramref name="actions"/> throws some exception. /// The actual exception that an <see cref="IAction"/> threw /// is stored in its <see cref="Exception.InnerException"/> property. /// </exception> internal static IEnumerable <ActionEvaluation> EvaluateActionsGradually( HashDigest <SHA256> blockHash, long blockIndex, TxId?txid, IAccountStateDelta previousStates, Address minerAddress, Address signer, byte[] signature, IImmutableList <IAction> actions, bool rehearsal = false) { ActionContext CreateActionContext( IAccountStateDelta prevStates, int randomSeed ) => new ActionContext( signer: signer, miner: minerAddress, blockIndex: blockIndex, previousStates: prevStates, randomSeed: randomSeed, rehearsal: rehearsal ); byte[] hashedSignature; using (var hasher = SHA1.Create()) { hashedSignature = hasher.ComputeHash(signature); } int seed = BitConverter.ToInt32(blockHash.ToByteArray(), 0) ^ (signature.Any() ? BitConverter.ToInt32(hashedSignature, 0) : 0); IAccountStateDelta states = previousStates; foreach (IAction action in actions) { ActionContext context = CreateActionContext(states, seed); IAccountStateDelta nextStates; try { nextStates = action.Execute(context); } catch (Exception e) { string msg; if (!rehearsal) { msg = $"The action {action} (block #{blockIndex} {blockHash}, tx {txid}) " + "threw an exception during execution. See also this exception's " + "InnerException property."; throw new UnexpectedlyTerminatedActionException( blockHash, blockIndex, txid, action, msg, e ); } msg = $"The action {action} threw an exception during its " + "rehearsal. It is probably because the logic of the " + $"action {action} is not enough generic so that it " + "can cover every case including rehearsal mode.\n" + "The IActionContext.Rehearsal property also might be " + "useful to make the action can deal with the case of " + "rehearsal mode.\n" + "See also this exception's InnerException property."; throw new UnexpectedlyTerminatedActionException( null, null, null, action, msg, e ); } // As IActionContext.Random is stateful, we cannot reuse // the context which is once consumed by Execute(). ActionContext equivalentContext = CreateActionContext(states, seed); yield return(new ActionEvaluation( action, equivalentContext, nextStates )); states = nextStates; unchecked { seed++; } } }
/// <summary> /// Creates a name-based UUID using the algorithm from RFC 4122 §4.3. /// </summary> /// <param name="namespaceId">The ID of the namespace.</param> /// <param name="name">The name (within that namespace).</param> /// <param name="version">The version number of the UUID to create; this value must be either /// 3 (for MD5 hashing) or 5 (for SHA-1 hashing).</param> /// <returns>A UUID derived from the namespace and name.</returns> /// <remarks>See <a href="http://code.logos.com/blog/2011/04/generating_a_deterministic_guid.html">Generating a deterministic GUID</a>.</remarks> public static Guid Create(Guid namespaceId, string name, int version) { if (name == null) { throw new ArgumentNullException("name"); } if (version != 3 && version != 5) { throw new ArgumentOutOfRangeException("version", "version must be either 3 or 5."); } // convert the name to a sequence of octets (as defined by the standard or conventions of its namespace) (step 3) // ASSUME: UTF-8 encoding is always appropriate byte[] nameBytes = Encoding.UTF8.GetBytes(name); // convert the namespace UUID to network order (step 3) byte[] namespaceBytes = namespaceId.ToByteArray(); SwapByteOrder(namespaceBytes); // comput the hash of the name space ID concatenated with the name (step 4) byte[] hash; using (HashAlgorithm algorithm = version == 3 ? (HashAlgorithm)MD5.Create() : SHA1.Create()) { algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, null, 0); algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length); hash = algorithm.Hash; } // most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12) byte[] newGuid = new byte[16]; Array.Copy(hash, 0, newGuid, 0, 16); // set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8) newGuid[6] = (byte)((newGuid[6] & 0x0F) | (version << 4)); // set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10) newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80); // convert the resulting UUID to local byte order (step 13) SwapByteOrder(newGuid); return(new Guid(newGuid)); }
public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; MemoryStream dataStream = new MemoryStream(dataArray, true); while (dataStream.Position < dataArray.Length - data.Length) { dataStream.Write(data, 0, data.Length); } dataStream.Position = 0; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); ArraySegment <byte> dataSpan = new ArraySegment <byte>(dataArray2, 1, dataArray.Length); HashAlgorithm halg; if (hashAlgorithm == HashAlgorithmName.MD5) { halg = MD5.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA1) { halg = SHA1.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA256) { halg = SHA256.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA384) { halg = SHA384.Create(); } else if (hashAlgorithm == HashAlgorithmName.SHA512) { halg = SHA512.Create(); } else { throw new Exception("Hash algorithm not supported."); } List <byte[]> signatures = new List <byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm)); signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm)); dataStream.Position = 0; signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count))); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream))); dataStream.Position = 0; foreach (byte[] signature in signatures) { Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2"); Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A"); dataStream.Position = 0; Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A"); dataStream.Position = 0; } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2"); Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B"); dataStream.Position = 0; Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6"); Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B"); dataStream.Position = 0; } }
public HashSHA1(BackgroundWorker bg) : base(bg, SHA1.Create()) { }
private static Byte[] SendConnect(Byte[] webSocketKey) { return(Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String(SHA1.Create().ComputeHash(webSocketKey)) + Environment.NewLine + Environment.NewLine)); }
// Create a login button event, to check the login details private void btnLogin_Click(object sender, EventArgs e) { try { using (SQLiteConnection dbcon = new SQLiteConnection()) { //Use the dbConnection as the data source dbcon.ConnectionString = dbConnection.dbsource; //using SHA1 hash password //create new instance of sha1 SHA1 sha1 = SHA1.Create(); //convert string to an array of bytes byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(textBoxPassword.Text)); //use a StringBuilder to save hash value StringBuilder hashValue = new StringBuilder(); // for each byte, add to the StringBuilder for (int i = 0; i < hashData.Length; i++) { hashValue.Append(hashData[i].ToString()); } // return sha1 hash value string hashresult = hashValue.ToString(); //MessageBox.Show(hashresult); //Check the result //SQL as a String string sql = "SELECT Password,StaffNo,Manager FROM Staff WHERE Username=@name"; using (SQLiteCommand cmd = new SQLiteCommand(sql, dbcon)) { cmd.Parameters.AddWithValue("name", textBoxUsername.Text); dbcon.Open(); using (SQLiteDataReader dr = cmd.ExecuteReader()) { if (!dr.HasRows) { throw new Exception(); } dr.Read(); if (hashresult != dr[0].ToString()) { throw new Exception(); } //stfid = Convert.ToInt32(dr[1]); int IDSM; //use IDSM to check if the one login is a staff or a manager IDSM = Convert.ToInt32(dr[2]); //convert "manager" column to int GlobalData.GDUserName = textBoxUsername.Text; dbcon.Close(); //Close connection to Database tsText.Image = Properties.Resources.green; //Display a Green Tick on the Syayus Bar tsText.Text = "Welcome, " + textBoxUsername.Text + " ! Have a nice day!"; //Change the text on the status bus with username entered. MessageBox.Show("Login Successful. " + "Welcome, " + textBoxUsername.Text + "! Have a nice day!", "Login"); //Display a message box with username entered. StaffView staffView = new StaffView(); ManagerView managerView = new ManagerView(); //using IDSM to decide which interface to show and hide login interface if (IDSM == 0) { this.Hide(); staffView.Show(); } else if (IDSM == 1) { this.Hide(); managerView.Show(); } } } } } //finally { }; catch (Exception) { timer1.Start(); } }
public static byte[] GetHash(HashType type, Stream stream, long reportInterval, IProgress <long> progress) { HashAlgorithm hash = null; try { switch (type) { case HashType.MD5: hash = MD5.Create(); break; case HashType.SHA1: hash = SHA1.Create(); break; case HashType.SHA256: hash = SHA256.Create(); break; case HashType.SHA384: hash = SHA384.Create(); break; case HashType.SHA512: hash = SHA512.Create(); break; default: throw new InvalidOperationException("Invalid Hash Type"); } // No progress report if (reportInterval <= 0 || progress == null) { return(hash.ComputeHash(stream)); } // With progress report long nextReport = reportInterval; long offset = stream.Position; byte[] buffer = new byte[BufferSize]; int bytesRead; do { bytesRead = stream.Read(buffer, 0, buffer.Length); hash.TransformBlock(buffer, 0, bytesRead, buffer, 0); offset += bytesRead; if (nextReport <= offset) { progress.Report(offset); nextReport += reportInterval; } }while (0 < bytesRead); hash.TransformFinalBlock(buffer, 0, 0); return(hash.Hash); } finally { if (hash != null) { hash.Dispose(); } } }
internal static string GetHashCore(KernelTransaction transaction, string fileFullPath, HashType hashType, PathFormat pathFormat) { const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; var fileNameLp = Path.GetExtendedLengthPathCore(transaction, fileFullPath, pathFormat, options); byte[] hash = null; using (var fs = OpenCore(transaction, fileNameLp, FileMode.Open, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.Normal, null, null, PathFormat.LongFullPath)) { switch (hashType) { case HashType.CRC32: using (var hType = new Crc32()) hash = hType.ComputeHash(fs); break; case HashType.CRC64ISO3309: using (var hType = new Crc64()) hash = hType.ComputeHash(fs); break; case HashType.MD5: using (var hType = MD5.Create()) hash = hType.ComputeHash(fs); break; case HashType.RIPEMD160: using (var hType = RIPEMD160.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA1: using (var hType = SHA1.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA256: using (var hType = SHA256.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA384: using (var hType = SHA384.Create()) hash = hType.ComputeHash(fs); break; case HashType.SHA512: using (var hType = SHA512.Create()) hash = hType.ComputeHash(fs); break; } } if (null != hash) { var sb = new StringBuilder(hash.Length); foreach (var b in hash) { sb.Append(b.ToString("X2", CultureInfo.InvariantCulture)); } return(sb.ToString().ToUpperInvariant()); } return(string.Empty); }
public static byte[] GetHash(HashType type, byte[] input, int reportInterval, IProgress <long> progress) { HashAlgorithm hash = null; try { switch (type) { case HashType.MD5: hash = MD5.Create(); break; case HashType.SHA1: hash = SHA1.Create(); break; case HashType.SHA256: hash = SHA256.Create(); break; case HashType.SHA384: hash = SHA384.Create(); break; case HashType.SHA512: hash = SHA512.Create(); break; default: throw new InvalidOperationException("Invalid Hash Type"); } // No progress report if (reportInterval <= 0 || progress == null) { return(hash.ComputeHash(input)); } // With progress report int offset = 0; while (offset < input.Length) { if (offset + reportInterval < input.Length) { hash.TransformBlock(input, offset, reportInterval, input, offset); offset += reportInterval; } else // Last run { int bytesRead = input.Length - offset; hash.TransformFinalBlock(input, offset, bytesRead); offset += bytesRead; } progress.Report(offset); } return(hash.Hash); } finally { if (hash != null) { hash.Dispose(); } } }
private void btninsert_Click(object sender, EventArgs e) { errorProvider1.Clear(); if (combo_usertype.Text.Length <= 0) { errorProvider1.SetError(combo_usertype, "Please Select Usser Type"); } else if (txtusername.Text.Length <= 0) { errorProvider1.SetError(txtusername, "Enter User Name"); } else if (password.Text.Length <= 0) { errorProvider1.SetError(password, "Please Enter the Password "); } else if (password.Text != txtconfirmpassword.Text) { errorProvider1.SetError(txtconfirmpassword, "Password Mismatch"); } else { try { conn.Close(); conn.Open(); String password1 = password.Text; // byte[] hash = null; using (SHA1 sha1 = SHA1.Create()) { // sha1.Initialize(); byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password1)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; ++i) { sb.Append(hash[i].ToString("x2")); } password1 = sb.ToString(); } String query = "Insert into New_User (Username,Password,User_Type,Created_Date) values('" + txtusername.Text + "','" + password1 + "','" + combo_usertype.Text + "','" + labeltime.Text + "')"; SqlDataAdapter execute = new SqlDataAdapter(query, conn); execute.SelectCommand.ExecuteNonQuery(); MessageBox.Show("Successfully Record Inserted!!"); DataTable(); refresh(); conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private static void Validate(string license, DateTime releaseDate, string projectNamespace) { if (license == null || projectNamespace == null) { throw new InvalidLicenseException("License and project namespace cannot be null or empty"); } var licenseParts = license.Trim().Split('-'); if (licenseParts.Length != 2) { throw new InvalidLicenseException("License text is invalid"); } var licenseIdData = licenseParts[0]; var licenseDetailsData = licenseParts[1]; if (!int.TryParse(licenseIdData, NumberStyles.Integer, CultureInfo.InvariantCulture, out var licenseId)) { throw new InvalidLicenseException("License text is invalid"); } byte[] licenseAsBytes; try { licenseAsBytes = Convert.FromBase64String(licenseDetailsData); } catch { throw new InvalidLicenseException("License text is invalid"); } var stream = new MemoryStream(licenseAsBytes, SigningDataLength, licenseAsBytes.Length - SigningDataLength); var parsedLicenseDetails = new StreamReader(stream).ReadToEnd(); var parsedLicenseParts = parsedLicenseDetails.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (parsedLicenseParts.Length != 6) { throw new InvalidLicenseException("License details are invalid"); } if (!DateTime.TryParseExact(parsedLicenseParts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var expiryDate)) { throw new InvalidLicenseException("License expiry date is invalid"); } if (!int.TryParse( parsedLicenseParts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLicenseId)) { throw new InvalidLicenseException("License ID is invalid"); } var licenseDetails = new LicenseDetails { Id = parsedLicenseId, ExpiryDate = expiryDate, User = parsedLicenseParts[2], InformationDetails = parsedLicenseParts[3], Type = parsedLicenseParts[4], NamespacePrefix = parsedLicenseParts[5] }; var parsedSigningData = licenseDetails.GetSignificateData(); var signingData = new byte[SigningDataLength]; Array.Copy(licenseAsBytes, signingData, SigningDataLength); var cryptoProvider = new RSACryptoServiceProvider(1024) { PersistKeyInCsp = false }; cryptoProvider.ImportCspBlob(Convert.FromBase64String(PublicKey)); var dataVerified = cryptoProvider.VerifyData(parsedSigningData, SHA1.Create(), signingData); if (!dataVerified) { throw new InvalidLicenseException("License text does not match signature"); } if (licenseDetails.Id != licenseId) { throw new InvalidLicenseException("License ID does not match signature license ID"); } if (licenseDetails.ExpiryDate < releaseDate) { throw new InvalidLicenseException($"License is not valid for this version of My Tested ASP.NET Core MVC. License expired on {licenseDetails.ExpiryDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}. This version of My Tested ASP.NET Core MVC was released on {releaseDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}"); } if (licenseDetails.Type != LicenseType.Enterprise && licenseDetails.NamespacePrefix != "." && !projectNamespace.StartsWith(licenseDetails.NamespacePrefix)) { throw new InvalidLicenseException($"License is not valid for '{projectNamespace}' test project"); } if (licenseDetails.Type == LicenseType.Internal) { throw new InvalidLicenseException("License is for internal use only"); } registeredLicenses.Add(licenseDetails); }
/// <summary> /// SHA1 加密 /// </summary> /// <param name="input"> 要加密的字符串 </param> /// <param name="encoding"> 字符编码 </param> /// <returns></returns> public static string SHA1Encrypt(string input, Encoding encoding) { return(HashEncrypt(SHA1.Create(), input, encoding)); }
private static string GetHash(string text) { var byteArray = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(text)); return BitConverter.ToString(byteArray).Replace("-", ""); }
protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message) { base.HandleLtMetadataMessage(id, message); switch (message.MetadataMessageType) { case LTMetadata.eMessageType.Data: if (stream == null) { throw new Exception("Need extention handshake before ut_metadata message."); } stream.Seek(message.Piece * LTMetadata.BlockSize, SeekOrigin.Begin); stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length); bitField[message.Piece] = true; if (bitField.AllTrue) { byte[] hash; stream.Position = 0; #if NETSTANDARD1_5 using (SHA1 hasher = SHA1.Create()) #else using (SHA1 hasher = HashAlgoFactory.Create <SHA1>()) #endif hash = hasher.ComputeHash(stream); if (!Manager.InfoHash.Equals(hash)) { bitField.SetAll(false); } else { System.Net.BitTorrent.Common.Torrent t; stream.Position = 0; BEncodedDictionary dict = new BEncodedDictionary(); dict.Add("info", BEncodedValue.Decode(stream)); // FIXME: Add the trackers too if (System.Net.BitTorrent.Common.Torrent.TryLoad(dict.Encode(), out t)) { try { if (Directory.Exists(savePath)) { savePath = Path.Combine(savePath, Manager.InfoHash.ToHex() + ".torrent"); } File.WriteAllBytes(savePath, dict.Encode()); } catch (Exception ex) { Logger.Log(null, "*METADATA EXCEPTION* - Can not write in {0} : {1}", savePath, ex); Manager.Error = new Error(Reason.WriteFailure, ex); Manager.Mode = new ErrorMode(Manager); return; } t.TorrentPath = savePath; Manager.Torrent = t; SwitchToRegular(); } else { bitField.SetAll(false); } } } //Double test because we can change the bitfield in the other block if (!bitField.AllTrue) { RequestNextNeededPiece(id); } break; case LTMetadata.eMessageType.Reject: //TODO //Think to what we do in this situation //for moment nothing ;) //reject or flood? break; case LTMetadata.eMessageType.Request: //ever done in base class but needed to avoid default break; default: throw new MessageException(string.Format("Invalid messagetype in LTMetadata: {0}", message.MetadataMessageType)); } }
public async Task Start(CancellationToken cancellationToken = default) { var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); linkedSource.Token.Register(() => _tcpListener.Stop()); _tcpListener.Start(); while (!linkedSource.Token.IsCancellationRequested) { try { var tcpClient = await _tcpListener.AcceptTcpClientAsync().WithCancellation(linkedSource.Token); var networkStream = tcpClient.GetStream(); while (!networkStream.DataAvailable) { ; } while (tcpClient.Available < 3) { ; // match against "get" } byte[] bytes = new byte[tcpClient.Available]; networkStream.Read(bytes, 0, tcpClient.Available); string s = Encoding.UTF8.GetString(bytes); if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) { string swk = Regex.Match(s, $"{ClientHandshakeHeader} (.*)").Groups[1].Value.Trim(); string swka = swk + Guid; byte[] swkaSha1 = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka)); string swkaSha1Base64 = Convert.ToBase64String(swkaSha1); byte[] response = GetServerHandshakeResponseTemplate(swkaSha1Base64); networkStream.Write(response, 0, response.Length); var webSocket = WebSocket.CreateFromStream(networkStream, isServer: true, null, Timeout.InfiniteTimeSpan); if (await _webSocketQueue.SendAsync(webSocket)) { var actionBlock = new ActionBlock <WebSocket>( (ws) => ProcessWebSocketClient(ws, cancellationToken: linkedSource.Token), _consumerOptions); _webSocketQueue.LinkTo(actionBlock, _linkOptions); _clients.Add(webSocket); } } } catch (OperationCanceledException) { //ignore } catch (Exception) { //maybe log the error } } }