public string registerSale(string idClient, string phonesQuantities, string total, string key) { EncryptionMethods em = new EncryptionMethods(); string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); ClientBusiness cb = new ClientBusiness(conn); SaleBusiness sb = new SaleBusiness(conn); PhoneSaleBusiness psb = new PhoneSaleBusiness(conn); PhoneBusiness pb = new PhoneBusiness(conn); Client client = cb.getClientById(Int32.Parse(em.decrypting(idClient, key))); Sale sale = new Sale(0, client, Int32.Parse(em.decrypting(total, key)), DateTime.Today.ToString()); int r = sb.insertSale(sale); sale.IdSale = r; string phonesQ = em.decrypting(phonesQuantities, key); string[] phones = phonesQ.Split('#'); for (int i = 0; i < phones.Length; i++) { string[] data = phones[i].Split(';'); Phone phone = pb.getPhoneById(Int32.Parse(data[0])); PhoneSale ps = new PhoneSale(0, phone, sale, Int32.Parse(data[1])); psb.insertPhoneSale(ps); } string response = "1"; return(em.encrypt(response, key)); }
private void btnRegister_Click(object sender, EventArgs e) { try { EncryptionMethods em = new EncryptionMethods(); var hashedPassword = em.SHA256_Hash(txtPassword.Text); var user = new UserViewModel() { User1 = txtUserName.Text, Password = hashedPassword, FirstName = txtFirstName.Text, MiddleName = string.IsNullOrEmpty(txtMiddleName.Text) ? null : txtMiddleName.Text, LastName = txtLastName.Text, SecondLastName = string.IsNullOrEmpty(txtSecondLastName.Text) ? null : txtSecondLastName.Text, IdentityNumber = txtIdentityNumber.Text, BirthDate = dtpBirthDate.Value, Email = txtEmail.Text, rowguid = Guid.NewGuid(), Nationality = Convert.ToInt32(cbCountries.SelectedValue), CreateDate = DateTime.Now, ModifiedDate = DateTime.Now }; _userRepository.Add(user); MessageBox.Show("User {0} has been created", user.FirstName); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public string getClient(string nameUser, string key) { string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); ClientBusiness cb = new ClientBusiness(conn); EncryptionMethods em = new EncryptionMethods(); Client client = cb.getClientByUserName(em.decrypting(nameUser, key)); string response = client.IdUser + ";" + client.Name + ";" + client.LastName_1 + ";" + client.LastName_2 + ";" + client.PasswordUser + ";" + client.Email + ";" + client.NumberCard + ";" + client.AddressDirection + ";" + client.PostalCode + ";" + client.SvcCard; return(em.encrypt(response, key)); }
public string getBrandById(string idBrand, string key) { EncryptionMethods em = new EncryptionMethods(); string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); BrandBusiness b = new BrandBusiness(conn); int t = Int32.Parse(em.decrypting(idBrand + "", key)); Brand brand = b.getBrandById(t); string response = brand.IdBrand + ";" + brand.Name; return(em.encrypt(response, key)); }
public string deleteClient(string idClient, string key) { EncryptionMethods em = new EncryptionMethods(); string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); ClientBusiness cb = new ClientBusiness(conn); int t = Int32.Parse(em.decrypting(idClient + "", key)); int r = cb.deleteClient(t); string response = em.encrypt(r + "", key); return(response); }
public string deleteBrand(string idBrand, string key) { string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); BrandBusiness b = new BrandBusiness(conn); EncryptionMethods em = new EncryptionMethods(); int t = Int32.Parse(em.decrypting(idBrand + "", key)); int r = b.deleteBrand(t); string response = em.encrypt(r + "", key); return(response); }
public static string EncryptString(this object input) { string str = Convert.ToString(input); try { return(EncryptionMethods.EncryptString(str)); } catch { return(null); } }
public string verifyExistsClient(string client, string key) { string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); ClientBusiness cb = new ClientBusiness(conn); EncryptionMethods em = new EncryptionMethods(); string text = em.decrypting(client, key); string[] fields = text.Split(';'); int r = cb.verifyExistsClient(fields[0], fields[1]); string response = em.encrypt(r + "", key); return(response); }
/// <summary> /// Update session key for Non-FIPS according to section 5.3.7 Session Key Updates. /// </summary> /// <param name="initialKey">The initial session key.</param> /// <param name="currentKey">The current session key.</param> /// <param name="encryptionMethod">The current encryption method.</param> /// <returns>The new session key.</returns> private static byte[] UpdateKey(byte[] initialKey, byte[] currentKey, EncryptionMethods encryptionMethod) { byte[] pad1 = ConstValue.NON_FIPS_PAD1; byte[] pad2 = ConstValue.NON_FIPS_PAD2; byte[] newKey = null; // SHAComponent = SHA(InitialEncryptKey + Pad1 + CurrentEncryptKey) byte[] shaComponentBuffer = RdpbcgrUtility.ConcatenateArrays(initialKey, pad1, currentKey); byte[] shaComponent = ShaHash(shaComponentBuffer); // TempKey128 = MD5(InitialEncryptKey + Pad2 + SHAComponent) byte[] tempKey128Buffer = RdpbcgrUtility.ConcatenateArrays(initialKey, pad2, shaComponent); byte[] tempKey128 = MD5Hash(tempKey128Buffer); if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_128BIT) { // S-TableEncrypt = InitRC4(TempKey128) RC4CryptoServiceProvider rc4 = new RC4CryptoServiceProvider(); ICryptoTransform ict = rc4.CreateEncryptor(tempKey128, null); // NewEncryptKey128 = RC4(TempKey128, S-TableEncrypt) newKey = ict.TransformFinalBlock(tempKey128, 0, tempKey128.Length); } else if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_40BIT || encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_56BIT) { // TempKey64 = First64Bits(TempKey128) byte[] tempKey64 = GetFirstNBits(64, tempKey128); // S-TableEncrypt = InitRC4(TempKey64) RC4CryptoServiceProvider rc4 = new RC4CryptoServiceProvider(); ICryptoTransform ict = rc4.CreateEncryptor(tempKey64, null); // PreSaltKey = RC4(TempKey64, S-TableEncrypt) byte[] preSaltKey = ict.TransformFinalBlock(tempKey64, 0, tempKey64.Length); if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_40BIT) { // NewEncryptKey40 = 0xD1269E + Last40Bits(PreSaltKey) newKey = RdpbcgrUtility.ConcatenateArrays(ConstValue.NON_FIPS_SALT_40BIT, GetLastNBits(40, preSaltKey)); } else { // NewEncryptKey56 = 0xD1 + Last56Bits(PreSaltKey) newKey = RdpbcgrUtility.ConcatenateArrays(ConstValue.NON_FIPS_SALT_56BIT, GetLastNBits(56, preSaltKey)); } } // else do nothing return(newKey); }
public string updateClient(string client, string key) { string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); ClientBusiness cb = new ClientBusiness(conn); EncryptionMethods em = new EncryptionMethods(); string text = em.decrypting(client, key); string[] fields = text.Split(';'); Client clientO = new Client(Int32.Parse(fields[0]), fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], fields[7], fields[8], fields[9], fields[10]); int r = cb.updateClient(clientO); string response = em.encrypt(r + "", key); return(response); }
public static string DecryptString(this object input) { string str = Convert.ToString(input); try { string decryptedString = EncryptionMethods.DecryptString(str); return(decryptedString); } catch { return(null); } }
public string getAllBrands(string key) { string response = ""; string conn = WebConfigurationManager.ConnectionStrings["KeggPhonesConnectionString"].ToString(); BrandBusiness b = new BrandBusiness(conn); EncryptionMethods em = new EncryptionMethods(); DataSet dsBrand = b.getAllBrands(); DataRowCollection dataRowCollection = dsBrand.Tables["TBrand"].Rows; foreach (DataRow currentRow in dataRowCollection) { response += currentRow["idBrand"].ToString() + ";" + currentRow["name"].ToString() + "#"; } return(em.encrypt(response, key)); }
public static IEncryptor GetEncryptor(DisplayMonkeyEntities _db) // 1.4.0 { EncryptionMethods encryptionMethod = EncryptionMethods.RsaContainer; IEncryptor encryptor = null; Setting s = Setting.GetSetting(_db, Keys.EncryptionMethod); if (s != null) { encryptionMethod = (EncryptionMethods)s.IntValuePositive; } switch (encryptionMethod) { case EncryptionMethods.RsaContainer: encryptor = new RsaEncryptor(); break; case EncryptionMethods.Aes: encryptor = new AesEncryptor(); s = Setting.GetSetting(_db, Keys.EncryptionIV); if (s != null && s.RawValue != null) { (encryptor as AesEncryptor).IV = s.RawValue; } else { Setting.SaveSetting(_db, Keys.EncryptionIV, (encryptor as AesEncryptor).IV); } s = Setting.GetSetting(_db, Keys.EncryptionKey); if (s != null && s.RawValue != null) { (encryptor as AesEncryptor).Key = s.RawValue; } else { Setting.SaveSetting(_db, Keys.EncryptionKey, (encryptor as AesEncryptor).Key); } break; } return(encryptor); }
/// <summary> /// Create an EncryptionAlgorithm for specified encryption level and encryption method. /// </summary> /// <param name="method">Specify the encryption method.</param> public EncryptionAlgorithm(EncryptionMethods method) { encryptionMethod = method; }
/// <summary> /// Expect a client initiated RDP connection sequence. /// </summary> /// <param name="serverSelectedProtocol">The server selected security protocol.</param> /// <param name="enMethod">The server selected security method.</param> /// <param name="enLevel">The server selected security level.</param> /// <param name="isExtendedClientDataSupported">Indicates if server supports Extended Client Data Blocks.</param> /// <param name="expectAutoReconnect">Indicates if expect an Auto-Connect sequence.</param> /// <param name="rdpServerVersion">The RDP Sever version</param> /// <param name="multiTransportTypeFlags">Flags of Multitransport Channel Data</param> /// <param name="supportRDPEGFX">Whether support RDPEGFX</param> /// <param name="supportRestrictedAdminMode">Whether support restricted admin mode</param> public void EstablishRDPConnection( selectedProtocols_Values serverSelectedProtocol, EncryptionMethods enMethod, EncryptionLevel enLevel , bool isExtendedClientDataSupported, bool expectAutoReconnect, TS_UD_SC_CORE_version_Values rdpServerVersion, MULTITRANSPORT_TYPE_FLAGS multiTransportTypeFlags = MULTITRANSPORT_TYPE_FLAGS.None, bool supportRDPEGFX = false, bool supportRestrictedAdminMode = false) { #region Logging this.site.Log.Add(LogEntryKind.Comment, @"EstablishRDPConnection( Selected Protocol = {0}, Encyrption Method = {1}, Encyrption Level = {2}, Extended Client Data Supported = {3}, Auto-Reconnection Expected = {4}, RDP Version Code= {5}).", serverSelectedProtocol.ToString(), enMethod.ToString(), enLevel.ToString(), isExtendedClientDataSupported, expectAutoReconnect, rdpServerVersion.ToString()); #endregion //Update server config context. serverConfig.selectedProtocol = serverSelectedProtocol; serverConfig.encryptionMethod = enMethod; serverConfig.encryptionLevel = enLevel; serverConfig.isExtendedClientDataSupported = isExtendedClientDataSupported; #region Connection Initiation //5.4.2.1 Negotiation-Based Approach //Once the External Security Protocol (section 5.4.5) handshake has successfully run to completion, //the RDP messages resume, continuing with the MCS Connect Initial PDU (section 2.2.1.3). //if (serverConfig.encryptedProtocol != EncryptedProtocol.NegotiationCredSsp) //{ ExpectPacket<Client_X_224_Connection_Request_Pdu>(sessionContext, pduWaitTimeSpan); RDP_NEG_RSP_flags_Values RDP_NEG_RSP_flags = RDP_NEG_RSP_flags_Values.None; if (serverConfig.isExtendedClientDataSupported) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.EXTENDED_CLIENT_DATA_SUPPORTED; } if (supportRDPEGFX) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.DYNVC_GFX_PROTOCOL_SUPPORTED; } if (supportRestrictedAdminMode) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.RESTRICTED_ADMIN_MODE_SUPPORTED; } Server_X_224_Connection_Confirm(serverConfig.selectedProtocol, RDP_NEG_RSP_flags); //} #endregion #region Basic Setting Exchange ExpectPacket<Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(sessionContext, pduWaitTimeSpan); Server_MCS_Connect_Response( enMethod, enLevel, rdpServerVersion, NegativeType.None, multiTransportTypeFlags, false, SC_earlyCapabilityFlags_Values.RNS_UD_SC_EDGE_ACTIONS_SUPPORTED, ConstValue.IO_CHANNEL_ID, ConstValue.MCS_MESSAGE_CHANNEL_ID); #endregion #region Channel Connection ExpectPacket<Client_MCS_Erect_Domain_Request>(sessionContext, pduWaitTimeSpan); ExpectPacket<Client_MCS_Attach_User_Request>(sessionContext, pduWaitTimeSpan); MCSAttachUserConfirm(NegativeType.None); //Join Channel int channelNum = 2; if (sessionContext.VirtualChannelIdStore != null) { channelNum += sessionContext.VirtualChannelIdStore.Length; } if (sessionContext.IsServerMessageChannelDataSend) channelNum++; for (int i = 0; i < channelNum; i++) { ExpectPacket<Client_MCS_Channel_Join_Request>(sessionContext, pduWaitTimeSpan); MCSChannelJoinConfirm(lastRequestJoinChannelId, NegativeType.None); } #endregion #region RDP Security Commencement if (serverConfig.encryptedProtocol == EncryptedProtocol.Rdp) { ExpectPacket<Client_Security_Exchange_Pdu>(sessionContext, pduWaitTimeSpan); } #endregion #region Secure Setting Exchange ExpectPacket<Client_Info_Pdu>(sessionContext, pduWaitTimeSpan); if (expectAutoReconnect) { site.Assert.IsNotNull(tsInfoPacket.extraInfo, "TS_EXTENDED_INFO_PACKET should be provided in Auto-Reconnect sequence."); site.Assert.AreNotEqual<ushort>(0, tsInfoPacket.extraInfo.cbAutoReconnectLen, "The autoReconnectCookie should be provided in Auto-Reconnect sequence."); } #endregion #region Licensing Server_License_Error_Pdu_Valid_Client(NegativeType.None); #endregion #region Capabilities Exchange Server_Demand_Active(NegativeType.None); //Once the Confirm Active PDU has been sent, the client can start sending input PDUs (see section 2.2.8) to the server. ExpectPacket<Client_Confirm_Active_Pdu>(sessionContext, pduWaitTimeSpan); #endregion #region Connection Finalization WaitForPacket<Client_Synchronize_Pdu>(sessionContext, pduWaitTimeSpan); ServerSynchronize(); ServerControlCooperate(); WaitForPacket<Client_Control_Pdu_Cooperate>(sessionContext, pduWaitTimeSpan); WaitForPacket<Client_Control_Pdu_Request_Control>(sessionContext, pduWaitTimeSpan); ServerControlGrantedControl(); if (serverConfig.CapabilitySetting.BitmapCacheHostSupportCapabilitySet) { ITsCapsSet cap = this.clientCapSet.FindCapSet(capabilitySetType_Values.CAPSTYPE_BITMAPCACHE_REV2); if (cap != null) { TS_BITMAPCACHE_CAPABILITYSET_REV2 bitmapCacheV2 = (TS_BITMAPCACHE_CAPABILITYSET_REV2)cap; if ((bitmapCacheV2.CacheFlags & CacheFlags_Values.PERSISTENT_KEYS_EXPECTED_FLAG) != 0) { WaitForPacket<Client_Persistent_Key_List_Pdu>(sessionContext, pduWaitTimeSpan); } } } WaitForPacket<Client_Font_List_Pdu>(sessionContext, pduWaitTimeSpan); ServerFontMap(); #endregion }
public SecretKeySpec(byte[] secretKey, EncryptionMethods encryptionMethod) { _secretKey = Protect(secretKey); _method = encryptionMethod; }
public override void Initialize(string name, NameValueCollection config) { _Name = name ?? config["name"]; _logger.Debug(d => d("'{0}' Initializing...", _Name)); try { _logger.Debug("pgMembershipProvider Initialize() invoked."); #region Set the configuration values _ConnectionStringName = config["connectionStringName"] ?? _ConnectionStringName; _logger.Debug(d => d("_ConnectionStringName: {0}", _ConnectionStringName)); _PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"] ?? _PasswordStrengthRegularExpression; _logger.Debug(d => d("_PasswordStrengthRegularExpression: {0}", _PasswordStrengthRegularExpression)); _ApplicationName = config["applicationName"] ?? _ApplicationName; _logger.Debug(d => d("_ApplicationName: {0}", _ApplicationName)); if (config["enablePasswordReset"] != null) { _EnablePasswordReset = Convert.ToBoolean(config["enablePasswordReset"]); } _logger.Debug(d => d("_EnablePasswordReset: {0}", _EnablePasswordReset)); if (config["enablePasswordRetrieval"] != null) { _EnablePasswordRetrieval = Convert.ToBoolean(config["enablePasswordRetrieval"]); } _logger.Debug(d => d("_EnablePasswordRetrieval: {0}", _EnablePasswordRetrieval)); if (config["requiresQuestionAndAnswer"] != null) { _RequiresQuestionAndAnswer = Convert.ToBoolean(config["requiresQuestionAndAnswer"]); } _logger.Debug(d => d("_RequiresQuestionAndAnswer: {0}", _RequiresQuestionAndAnswer)); if (config["requiresUniqueEmail"] != null) { _RequiresUniqueEmail = Convert.ToBoolean(config["requiresUniqueEmail"]); } _logger.Debug(d => d("_RequiresUniqueEmail: {0}", _RequiresUniqueEmail)); if (config["maxInvalidPasswordAttempts"] != null) { _MaxInvalidPasswordAttempts = Convert.ToInt32(config["maxInvalidPasswordAttempts"]); if (_MaxInvalidPasswordAttempts < 0) { throw new ProviderConfigurationException("MaxInvalidPasswordAttempts must be 0 or greater."); } } _logger.Debug(d => d("_MaxInvalidPasswordAttempts: {0}", _MaxInvalidPasswordAttempts)); if (config["minRequiredNonAlphanumericCharacters"] != null) { _MinRequiredNonAlphanumericCharacters = Convert.ToInt32(config["minRequiredNonAlphanumericCharacters"]); if (_MinRequiredNonAlphanumericCharacters < 0) { throw new ProviderConfigurationException( "MinRequiredNonAlphanumericCharacters must be 0 or greater."); } } _logger.Debug(d => d("_MinRequiredNonAlphanumericCharacters: {0}", _MinRequiredNonAlphanumericCharacters)); if (config["passwordAttemptWindow"] != null) { _PasswordAttemptWindow = Convert.ToInt32(config["passwordAttemptWindow"]); if (_PasswordAttemptWindow < 0) { throw new ProviderConfigurationException("Password Attempt window must be 0 or greater."); } } _logger.Debug(d => d("_PasswordAttemptWindow: {0}", _PasswordAttemptWindow)); if (config["encryptionKey"] != null) { _EncryptionKey = Convert.FromBase64String(config["encryptionKey"]); } _logger.Debug(d => d("_EncryptionKey: {0}", _EncryptionKey)); if (config["minSaltCharacters"] != null) { _MinSaltCharacters = Convert.ToInt32(config["minSaltCharacters"]); if (_MinSaltCharacters < 0 || _MinSaltCharacters > 250) { throw new ProviderConfigurationException("MinSaltCharacters must be between 0 and 250."); } } _logger.Debug(d => d("_MinSaltCharacters: {0}", _MinSaltCharacters)); if (config["maxSaltCharacters"] != null) { _MaxSaltCharacters = Convert.ToInt32(config["maxSaltCharacters"]); if (_MaxSaltCharacters < 1 || _MaxSaltCharacters > 250) { throw new ProviderConfigurationException("MaxSaltCharacters must be between 1 and 250."); } } _logger.Debug(d => d("_MaxSaltCharacters: {0}", _MaxSaltCharacters)); if (config["minRequiredPasswordLength"] != null) { _MinRequiredPasswordLength = Convert.ToInt32(config["minRequiredPasswordLength"]); if (_MinRequiredPasswordLength < 0 || _MinRequiredPasswordLength > 100) { throw new ProviderConfigurationException( "Minimum password characters must be between 0 and 100."); } } _logger.Debug(d => d("_MinRequiredPasswordLength: {0}", _MinRequiredPasswordLength)); if (config["lockoutTime"] != null) { _LockoutTime = Convert.ToInt32(config["lockoutTime"]); if (_LockoutTime < 0) { throw new ProviderConfigurationException("Minimum lockout time is 0 minutes."); } } _logger.Debug(d => d("_LockoutTime: {0}", _LockoutTime)); if (config["sessionTime"] != null) { _SessionTime = Convert.ToInt32(config["sessionTime"]); if (_SessionTime < 1) { throw new ProviderConfigurationException("Minimum session time is 1 minute."); } } _logger.Debug(d => d("_SessionTime: {0}", _SessionTime)); if (config["dbOwner"] != null) { _dbOwner = config["dbOwner"]; } _logger.Debug(d => d("_dbOwner: {0}", _dbOwner)); #endregion #region validate configuration #region validate database config and connectivity _logger.Debug(d => d("Checking to make sure the specified connection string exists...")); var cs = ConfigurationManager.ConnectionStrings[_ConnectionStringName]; if (cs == null || string.IsNullOrEmpty(cs.ConnectionString)) { throw new ProviderConfigurationException( string.Format("The membership provider connection string, '{0}', is not defined.", _ConnectionStringName)); } ConnectionString = ConfigurationManager.ConnectionStrings[_ConnectionStringName].ConnectionString; _logger.Debug(d => d("ConnectionString: {0}", ConnectionString)); _logger.Debug(d => d("Checking to make sure the specified connection string can connect...")); using (var conn = new NpgsqlConnection(ConnectionString)) { conn.Open(); using (var comm = new NpgsqlCommand("select 1", conn)) { comm.CommandType = CommandType.Text; comm.ExecuteNonQuery(); } } #endregion #region validate encryption mechanism if (_EnablePasswordRetrieval) { _logger.Debug(d => d("Password Retrieval is enabled, checking for a valid encryption key...")); if (_EncryptionKey == null || _EncryptionKey.Length != 32) { throw new ProviderConfigurationException( "When password retrieval is enabled, a Base-64 encoded 32-byte encryption key must be supplied."); } EncryptionMethod = EncryptionMethods.ReversibleSymmetric; } else { EncryptionMethod = EncryptionMethods.Hash; } #endregion #region detect conflicting settings if (_MaxSaltCharacters < _MinSaltCharacters) { throw new ProviderConfigurationException( "MaxSaltCharacters value cannot be less than MinSaltCharacters value."); } #endregion #endregion } catch (Exception ex) { var message = "Error initializing the membership configuration settings"; _logger.Error(message, ex); throw new ProviderConfigurationException(message, ex); } DDLManager.ValidateVersion(_ConnectionStringName, _dbOwner); }
protected void LoadConfig() { #region Read and convert properties from PTFCONFIG file #region Security Approach and Protocol string strRDPSecurityProtocol; bool isNegotiationBased = true; if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RdpSecurityNegotiation, out isNegotiationBased)) { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityNegotiation); } selectedProtocol = selectedProtocols_Values.PROTOCOL_RDP_FLAG; if (!PtfPropUtility.GetStringPtfProperty(TestSite, RdpPtfPropNames.RdpSecurityProtocol, out strRDPSecurityProtocol)) { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityProtocol); } else {//TLS, CredSSP, or RDP if (strRDPSecurityProtocol.Equals("TLS", StringComparison.CurrentCultureIgnoreCase)) { selectedProtocol = selectedProtocols_Values.PROTOCOL_SSL_FLAG; if (isNegotiationBased) { transportProtocol = EncryptedProtocol.NegotiationTls; } else { transportProtocol = EncryptedProtocol.DirectTls; } } else if (strRDPSecurityProtocol.Equals("CredSSP", StringComparison.CurrentCultureIgnoreCase)) { selectedProtocol = selectedProtocols_Values.PROTOCOL_HYBRID_FLAG; if (isNegotiationBased) { transportProtocol = EncryptedProtocol.NegotiationCredSsp; } else { transportProtocol = EncryptedProtocol.DirectCredSsp; } } else if (strRDPSecurityProtocol.Equals("RDP", StringComparison.CurrentCultureIgnoreCase)) { selectedProtocol = selectedProtocols_Values.PROTOCOL_RDP_FLAG; if (!isNegotiationBased) { this.TestSite.Log.Add(LogEntryKind.Warning, "The property \"RDP.Security.Protocol\" is not valid and will be ingored. (When use RDP as security protocol, the negotiation-based approch MUST be used."); } } else { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityProtocol); } } #endregion #region Encryption Level string strRDPSecurityEncryptionLevel; enLevel = EncryptionLevel.ENCRYPTION_LEVEL_LOW; if (!PtfPropUtility.GetStringPtfProperty(TestSite, RdpPtfPropNames.RdpSecurityEncryptionLevel, out strRDPSecurityEncryptionLevel)) { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityEncryptionLevel); } else {//None, Low, Client, High, FIPS if (strRDPSecurityEncryptionLevel.Equals("None", StringComparison.CurrentCultureIgnoreCase)) { enLevel = EncryptionLevel.ENCRYPTION_LEVEL_NONE; } else if (strRDPSecurityEncryptionLevel.Equals("Low", StringComparison.CurrentCultureIgnoreCase)) { enLevel = EncryptionLevel.ENCRYPTION_LEVEL_LOW; } else if (strRDPSecurityEncryptionLevel.Equals("Client", StringComparison.CurrentCultureIgnoreCase)) { enLevel = EncryptionLevel.ENCRYPTION_LEVEL_CLIENT_COMPATIBLE; } else if (strRDPSecurityEncryptionLevel.Equals("High", StringComparison.CurrentCultureIgnoreCase)) { enLevel = EncryptionLevel.ENCRYPTION_LEVEL_HIGH; } else if (strRDPSecurityEncryptionLevel.Equals("FIPS", StringComparison.CurrentCultureIgnoreCase)) { enLevel = EncryptionLevel.ENCRYPTION_LEVEL_FIPS; } else { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityEncryptionLevel); } } if (transportProtocol == EncryptedProtocol.Rdp && enLevel == EncryptionLevel.ENCRYPTION_LEVEL_NONE) { this.TestSite.Assert.Fail("When use Standard RDP Security, the encryption level must be greater than None."); } if (transportProtocol != EncryptedProtocol.Rdp && enLevel != EncryptionLevel.ENCRYPTION_LEVEL_NONE) { this.TestSite.Assert.Fail("When use enhanced security protocls (TLS or CredSSP), the encryption level MUST be None."); } #endregion #region Encryption Method string strRDPSecurityEncryptionMethod; enMethod = EncryptionMethods.ENCRYPTION_METHOD_128BIT; if (!PtfPropUtility.GetStringPtfProperty(TestSite, RdpPtfPropNames.RdpSecurityEncryptionMethod, out strRDPSecurityEncryptionMethod)) { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityEncryptionMethod); } else {//None, 40bit, 56bit, 128bit, FIPS if (strRDPSecurityEncryptionMethod.Equals("None", StringComparison.CurrentCultureIgnoreCase)) { enMethod = EncryptionMethods.ENCRYPTION_METHOD_NONE; } else if (strRDPSecurityEncryptionMethod.Equals("40bit", StringComparison.CurrentCultureIgnoreCase)) { enMethod = EncryptionMethods.ENCRYPTION_METHOD_40BIT; } else if (strRDPSecurityEncryptionMethod.Equals("56bit", StringComparison.CurrentCultureIgnoreCase)) { enMethod = EncryptionMethods.ENCRYPTION_METHOD_56BIT; } else if (strRDPSecurityEncryptionMethod.Equals("128bit", StringComparison.CurrentCultureIgnoreCase)) { enMethod = EncryptionMethods.ENCRYPTION_METHOD_128BIT; } else if (strRDPSecurityEncryptionMethod.Equals("FIPS", StringComparison.CurrentCultureIgnoreCase)) { enMethod = EncryptionMethods.ENCRYPTION_METHOD_FIPS; } else { assumeFailForInvalidPtfProp(RdpPtfPropNames.RdpSecurityEncryptionMethod); } } if (enLevel == EncryptionLevel.ENCRYPTION_LEVEL_NONE && enMethod != EncryptionMethods.ENCRYPTION_METHOD_NONE) { this.TestSite.Assume.Fail("When Encryption Level is set to None, the Encryption Method should also set to None."); } if (enLevel == EncryptionLevel.ENCRYPTION_LEVEL_FIPS && enMethod != EncryptionMethods.ENCRYPTION_METHOD_FIPS) { this.TestSite.Assume.Fail("When Encryption Level is set to FIPS, the Encryption Method should also set to FIPS."); } #endregion #region RDP Version rdpServerVersion = TS_UD_SC_CORE_version_Values.V2; #endregion #region WaitTime int waitSeconds; if (!PtfPropUtility.GetIntPtfProperty(TestSite, RdpPtfPropNames.Timeout, out waitSeconds)) { assumeFailForInvalidPtfProp(RdpPtfPropNames.Timeout); } else { waitTime = new TimeSpan(0, 0, waitSeconds); } #endregion #region SUT Display Verification if (!PtfPropUtility.GetBoolPtfProperty(TestSite, "VerifySUTDisplay.Enable", out verifySUTDisplay)) { verifySUTDisplay = false; } int shiftX, shiftY; if (!PtfPropUtility.GetIntPtfProperty(TestSite, "VerifySUTDisplay.Shift.X", out shiftX)) { shiftX = 0; } if (!PtfPropUtility.GetIntPtfProperty(TestSite, "VerifySUTDisplay.Shift.Y", out shiftY)) { shiftY = 0; } sutDisplayShift = new Point(shiftX, shiftY); if (!PtfPropUtility.GetStringPtfProperty(TestSite, "VerifySUTDisplay.BitmapSavePath", out bitmapSavePath)) { bitmapSavePath = @".\"; } // If the bitmap save path is not existed, create it. if (!Directory.Exists(bitmapSavePath)) { Directory.CreateDirectory(bitmapSavePath); } #endregion SUT Display Verification #region Other configrations if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportFastPathInput, out isClientSupportFastPathInput)) { isClientSupportFastPathInput = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportAutoReconnect, out isClientSuportAutoReconnect)) { isClientSuportAutoReconnect = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportRDPEFS, out isClientSupportRDPEFS)) { isClientSupportRDPEFS = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportServerRedirection, out isClientSupportServerRedirection)) { isClientSupportServerRedirection = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportSoftSync, out isClientSupportSoftSync)) { isClientSupportSoftSync = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportTunnelingStaticVCTraffic, out isClientSupportTunnelingStaticVCTraffic)) { isClientSupportTunnelingStaticVCTraffic = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, RdpPtfPropNames.RDPClientSupportRdpNegDataEmpty, out isClientSupportEmptyRdpNegData)) { isClientSupportEmptyRdpNegData = false; //if property not found, set to false as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, "IsWindowsImplementation", out isWindowsImplementation)) { isWindowsImplementation = true; //if property not found, set to true as default value } if (!PtfPropUtility.GetBoolPtfProperty(TestSite, "VerifyRdpbcgrMessage", out bVerifyRdpbcgrMessage)) { bVerifyRdpbcgrMessage = true; //if property not found, set to true as default value } String rdprfxImageFile; if (!PtfPropUtility.GetStringPtfProperty(TestSite, "RDPRFX.Image", out rdprfxImageFile)) { rdprfxImageFile = ""; //if property not found, set to true as default value } String rdprfxVideoModeImageFile; if (!PtfPropUtility.GetStringPtfProperty(TestSite, "RDPRFXVideoMode.Image", out rdprfxVideoModeImageFile)) { rdprfxVideoModeImageFile = ""; //if property not found, set to true as default value } try { //Get image from file image_64X64 = Image.FromFile(rdprfxImageFile); imageForVideoMode = Image.FromFile(rdprfxVideoModeImageFile); } catch (System.IO.FileNotFoundException) { //capture screen if failed to get image from file //Capture 64*64 bitmap for Image Mode image_64X64 = captureScreenImage(0, 0, TileSize, TileSize); //Capture screen bitmap for Vedio Mode imageForVideoMode = captureScreenImage(0, 0, TileSize * VideoMode_TileRowNum, TileSize * VideoMode_TileColNum); } #endregion #endregion #region Logging this.TestSite.Log.Add(LogEntryKind.Debug, @"isClientSupportFastPathInput = {0}; isClientSuportAutoReconnect = {1}; isClientSupportRDPEFS = {2}; isClientSupportServerRedirection = {3}; isClientSupportEmptyRdpNegData = {4}; isClientSupportSoftSync = {5} isClientSupportTunnelingStaticVCTraffic = {6}", isClientSupportFastPathInput, isClientSuportAutoReconnect, isClientSupportRDPEFS, isClientSupportServerRedirection, isClientSupportEmptyRdpNegData, isClientSupportSoftSync, isClientSupportTunnelingStaticVCTraffic); #endregion }
/// <summary> /// Expect a client initiated RDP connection sequence. /// </summary> /// <param name="serverSelectedProtocol">The server selected security protocol.</param> /// <param name="enMethod">The server selected security method.</param> /// <param name="enLevel">The server selected security level.</param> /// <param name="isExtendedClientDataSupported">Indicates if server supports Extended Client Data Blocks.</param> /// <param name="expectAutoReconnect">Indicates if expect an Auto-Connect sequence.</param> /// <param name="rdpServerVersion">The RDP Sever version</param> /// <param name="isMultitransportSupported">Whether support multitransport</param> /// <param name="supportRDPEGFX">Whether support RDPEGFX</param> /// <param name="supportRestrictedAdminMode">Whether support restricted admin mode</param> public void EstablishRDPConnection( selectedProtocols_Values serverSelectedProtocol, EncryptionMethods enMethod, EncryptionLevel enLevel, bool isExtendedClientDataSupported, bool expectAutoReconnect, TS_UD_SC_CORE_version_Values rdpServerVersion, bool isMultitransportSupported = false, bool supportRDPEGFX = false, bool supportRestrictedAdminMode = false) { #region Logging this.site.Log.Add(LogEntryKind.Comment, @"EstablishRDPConnection( Selected Protocol = {0}, Encyrption Method = {1}, Encyrption Level = {2}, Extended Client Data Supported = {3}, Auto-Reconnection Expected = {4}, RDP Version Code= {5}).", serverSelectedProtocol.ToString(), enMethod.ToString(), enLevel.ToString(), isExtendedClientDataSupported, expectAutoReconnect, rdpServerVersion.ToString()); #endregion //Update server config context. serverConfig.selectedProtocol = serverSelectedProtocol; serverConfig.encryptionMethod = enMethod; serverConfig.encryptionLevel = enLevel; serverConfig.isExtendedClientDataSupported = isExtendedClientDataSupported; #region Connection Initiation //5.4.2.1 Negotiation-Based Approach //Once the External Security Protocol (section 5.4.5) handshake has successfully run to completion, //the RDP messages resume, continuing with the MCS Connect Initial PDU (section 2.2.1.3). //if (serverConfig.encryptedProtocol != EncryptedProtocol.NegotiationCredSsp) //{ ExpectPacket <Client_X_224_Connection_Request_Pdu>(sessionContext, pduWaitTimeSpan); RDP_NEG_RSP_flags_Values RDP_NEG_RSP_flags = RDP_NEG_RSP_flags_Values.None; if (serverConfig.isExtendedClientDataSupported) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.EXTENDED_CLIENT_DATA_SUPPORTED; } if (supportRDPEGFX) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.DYNVC_GFX_PROTOCOL_SUPPORTED; } if (supportRestrictedAdminMode) { RDP_NEG_RSP_flags |= RDP_NEG_RSP_flags_Values.RESTRICTED_ADMIN_MODE_SUPPORTED; } Server_X_224_Connection_Confirm(serverConfig.selectedProtocol, RDP_NEG_RSP_flags); //} #endregion #region Basic Setting Exchange ExpectPacket <Client_MCS_Connect_Initial_Pdu_with_GCC_Conference_Create_Request>(sessionContext, pduWaitTimeSpan); Server_MCS_Connect_Response(enMethod, enLevel, rdpServerVersion, NegativeType.None, isMultitransportSupported); #endregion #region Channel Connection ExpectPacket <Client_MCS_Erect_Domain_Request>(sessionContext, pduWaitTimeSpan); ExpectPacket <Client_MCS_Attach_User_Request>(sessionContext, pduWaitTimeSpan); MCSAttachUserConfirm(NegativeType.None); //Join Channel int channelNum = 2; if (sessionContext.VirtualChannelIdStore != null) { channelNum += sessionContext.VirtualChannelIdStore.Length; } if (sessionContext.IsServerMessageChannelDataSend) { channelNum++; } for (int i = 0; i < channelNum; i++) { ExpectPacket <Client_MCS_Channel_Join_Request>(sessionContext, pduWaitTimeSpan); MCSChannelJoinConfirm(lastRequestJoinChannelId, NegativeType.None); } #endregion #region RDP Security Commencement if (serverConfig.encryptedProtocol == EncryptedProtocol.Rdp) { ExpectPacket <Client_Security_Exchange_Pdu>(sessionContext, pduWaitTimeSpan); } #endregion #region Secure Setting Exchange ExpectPacket <Client_Info_Pdu>(sessionContext, pduWaitTimeSpan); if (expectAutoReconnect) { site.Assert.IsNotNull(tsInfoPacket.extraInfo, "TS_EXTENDED_INFO_PACKET should be provided in Auto-Reconnect sequence."); site.Assert.AreNotEqual <ushort>(0, tsInfoPacket.extraInfo.cbAutoReconnectLen, "The autoReconnectCookie should be provided in Auto-Reconnect sequence."); } #endregion #region Licensing Server_License_Error_Pdu_Valid_Client(NegativeType.None); #endregion #region Capabilities Exchange Server_Demand_Active(NegativeType.None); //Once the Confirm Active PDU has been sent, the client can start sending input PDUs (see section 2.2.8) to the server. ExpectPacket <Client_Confirm_Active_Pdu>(sessionContext, pduWaitTimeSpan); #endregion #region Connection Finalization WaitForPacket <Client_Synchronize_Pdu>(sessionContext, pduWaitTimeSpan); ServerSynchronize(); ServerControlCooperate(); WaitForPacket <Client_Control_Pdu_Cooperate>(sessionContext, pduWaitTimeSpan); WaitForPacket <Client_Control_Pdu_Request_Control>(sessionContext, pduWaitTimeSpan); ServerControlGrantedControl(); if (serverConfig.CapabilitySetting.BitmapCacheHostSupportCapabilitySet) { ITsCapsSet cap = this.clientCapSet.FindCapSet(capabilitySetType_Values.CAPSTYPE_BITMAPCACHE_REV2); if (cap != null) { TS_BITMAPCACHE_CAPABILITYSET_REV2 bitmapCacheV2 = (TS_BITMAPCACHE_CAPABILITYSET_REV2)cap; if ((bitmapCacheV2.CacheFlags & CacheFlags_Values.PERSISTENT_KEYS_EXPECTED_FLAG) != 0) { WaitForPacket <Client_Persistent_Key_List_Pdu>(sessionContext, pduWaitTimeSpan); } } } WaitForPacket <Client_Font_List_Pdu>(sessionContext, pduWaitTimeSpan); ServerFontMap(); #endregion }
public void TestMethod1() { //PhoneData data = new PhoneData("Data Source = 163.178.107.130; Initial Catalog = KeggPhones; User Id = sqlserver; Password = saucr.12"); //DataSet dsPhones = data.getPhonesLike("8"); //DataRowCollection dataRowCollection = dsPhones.Tables["TPhone"].Rows; //foreach (DataRow currentRow in dataRowCollection) //{ // Console.WriteLine(currentRow["model"]); //} //Reports.ReportsMethods r = new Reports.ReportsMethods(); //r.generatePhoneSaleReport(); //SaleData pd = new SaleData("Data Source = 163.178.107.130; Initial Catalog = KeggPhones; User Id = sqlserver; Password = saucr.12"); //Object[] a = pd.getBestClients(); //List<Client> c = (List<Client>) a[0]; //List<int> i = (List<int>)a[1]; //int x = 0; //SaleServiceReference.SaleServiceClient c = new SaleServiceReference.SaleServiceClient(); //c.registerSale(11, "18.1,19.2", 10000); //PhoneData cd = new PhoneData("Data Source = 163.178.107.130; Initial Catalog = KeggPhones; User Id = sqlserver; Password = saucr.12"); //Phone c = cd.getPhoneById(18); //Console.WriteLine(c.Model); //Console.ReadLine(); string texto = "20000"; Console.WriteLine(texto); Console.WriteLine("------------------------------------------------------------------"); string key = "YARR"; EncryptionMethods e = new EncryptionMethods(); string textoe = e.encrypt(texto, key); Console.WriteLine(textoe); Console.WriteLine("------------------------------------------------------------------"); string textodes = e.decrypting(textoe, key); Console.WriteLine(textodes); //string ruta = "../Images/imagen.png"; //Console.WriteLine(ruta.Length+""); //Console.WriteLine(ruta.Substring(2, ruta.Length-2)); //PhoneServiceReference.PhoneServiceClient c = new PhoneServiceReference.PhoneServiceClient(); //int r = c.getPhones().Count(); //Console.WriteLine(r); //Console.ReadLine(); }
public SecretKeySpec(byte[] secretKey, EncryptionMethods encryptionMethod) { _secretKey = secretKey; _method = encryptionMethod; }
/// <summary> /// Update session key for Non-FIPS according to section 5.3.7 Session Key Updates. /// </summary> /// <param name="initialKey">The initial session key.</param> /// <param name="currentKey">The current session key.</param> /// <param name="encryptionMethod">The current encryption method.</param> /// <returns>The new session key.</returns> private static byte[] UpdateKey(byte[] initialKey, byte[] currentKey, EncryptionMethods encryptionMethod) { byte[] pad1 = ConstValue.NON_FIPS_PAD1; byte[] pad2 = ConstValue.NON_FIPS_PAD2; byte[] newKey = null; // SHAComponent = SHA(InitialEncryptKey + Pad1 + CurrentEncryptKey) byte[] shaComponentBuffer = RdpbcgrUtility.ConcatenateArrays(initialKey, pad1, currentKey); byte[] shaComponent = ShaHash(shaComponentBuffer); // TempKey128 = MD5(InitialEncryptKey + Pad2 + SHAComponent) byte[] tempKey128Buffer = RdpbcgrUtility.ConcatenateArrays(initialKey, pad2, shaComponent); byte[] tempKey128 = MD5Hash(tempKey128Buffer); if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_128BIT) { // S-TableEncrypt = InitRC4(TempKey128) RC4CryptoServiceProvider rc4 = new RC4CryptoServiceProvider(); ICryptoTransform ict = rc4.CreateEncryptor(tempKey128, null); // NewEncryptKey128 = RC4(TempKey128, S-TableEncrypt) newKey = ict.TransformFinalBlock(tempKey128, 0, tempKey128.Length); } else if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_40BIT || encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_56BIT) { // TempKey64 = First64Bits(TempKey128) byte[] tempKey64 = GetFirstNBits(64, tempKey128); // S-TableEncrypt = InitRC4(TempKey64) RC4CryptoServiceProvider rc4 = new RC4CryptoServiceProvider(); ICryptoTransform ict = rc4.CreateEncryptor(tempKey64, null); // PreSaltKey = RC4(TempKey64, S-TableEncrypt) byte[] preSaltKey = ict.TransformFinalBlock(tempKey64, 0, tempKey64.Length); if (encryptionMethod == EncryptionMethods.ENCRYPTION_METHOD_40BIT) { // NewEncryptKey40 = 0xD1269E + Last40Bits(PreSaltKey) newKey = RdpbcgrUtility.ConcatenateArrays(ConstValue.NON_FIPS_SALT_40BIT, GetLastNBits(40, preSaltKey)); } else { // NewEncryptKey56 = 0xD1 + Last56Bits(PreSaltKey) newKey = RdpbcgrUtility.ConcatenateArrays(ConstValue.NON_FIPS_SALT_56BIT, GetLastNBits(56, preSaltKey)); } } // else do nothing return newKey; }