public CookieTicketSource(ISystemTime systemTime, IEncryptor encryptor, ILoginCookieService cookies, ILogger logger)
 {
     _systemTime = systemTime;
     _encryptor = encryptor;
     _cookies = cookies;
     _logger = logger;
 }
 public MembershipValidator(IApplicationSettings applicationSettings, IEncryptor encryptor)
 {
     _applicationSettings = applicationSettings;
     _encryptor = encryptor;
     _passwordRegEx = _applicationSettings.PasswordStrengthRegularExpression;
     _requiresUniqueEmail = _applicationSettings.RequiresUniqueEmail;
 }
Пример #3
0
        public static Encryption CreateClientGame(GameEncryptionType type, uint seed)
        {
            IEncryptor encryptor;
            IDecryptor decryptor;

            switch (type)
            {
                case GameEncryptionType.None:
                    encryptor = new NoEncryption();
                    decryptor = new Huffman();
                    break;

                case GameEncryptionType.Old: // Blowfish
                    encryptor = new BlowfishEncryption();
                    decryptor = new Huffman();
                    break;

                case GameEncryptionType.Rare:  // Blowfish + Twofish
                    encryptor = new BlowfishTwofishEncryption(seed);
                    decryptor = new Huffman();
                    break;

                case GameEncryptionType.New: // Twofish + MD5
                    encryptor = new TwofishEncryption(seed);
                    decryptor = new HuffmanMD5Encryption(seed);
                    break;

                default:
                    throw new Exception("Internal error.");
            }

            return new Encryption(encryptor, decryptor);
        }
Пример #4
0
 private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor)
 {
     byte[] plain = new byte[16384];
     byte[] cipher = new byte[plain.Length + 16];
     byte[] plain2 = new byte[plain.Length + 16];
     int outLen = 0;
     int outLen2 = 0;
     var random = new Random();
     random.NextBytes(plain);
     encryptor.Encrypt(plain, plain.Length, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(plain.Length, outLen2);
     for (int j = 0; j < plain.Length; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
     encryptor.Encrypt(plain, 1000, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(1000, outLen2);
     for (int j = 0; j < outLen2; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
     encryptor.Encrypt(plain, 12333, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(12333, outLen2);
     for (int j = 0; j < outLen2; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
 }
Пример #5
0
 public AzureTableContext(CloudTable table, IEncryptor encryptor)
 {
     _table = table;
     _encryptor = encryptor;
     _context = new TableBatchOperation();
     _deleteBackupContext = new TableBatchOperation();
 }
Пример #6
0
        public Encryption(IEncryptor enc, IDecryptor dec)
        {
            if (enc == null) throw new ArgumentNullException("enc");
            if (dec == null) throw new ArgumentNullException("dec");

            encryptor = enc;
            decryptor = dec;
        }
 public MembershipService(ICustomerRepository customerRepository, IEncryptor encryptor, IMembershipValidator membershipValidator,
     IStateRepository stateRepository, IUnitOfWork uow, IUserLoginRepository userLoginRepository)
 {
     _customerRepository = customerRepository;
     _encryptor = encryptor;
     _membershipValidator = membershipValidator;
     _stateRepository = stateRepository;
     _uow = uow;
     _userLoginRepository = userLoginRepository;
 }
Пример #8
0
        public static InstanceDb ToCommon(this Instance instance, IEncryptor encryptor)
        {
            if (instance == null) return null;

            return new InstanceDb
            {
                InstanceId = instance.InstanceId,
                InstanceName = instance.InstanceName
            };
        }
Пример #9
0
        public static BlobDb ToCommon(this Blob blob, IEncryptor encryptor)
        {
            if (blob == null) return null;

            return new BlobDb
            {
                BlobId = blob.BlobId,
                InstanceId = blob.InstanceId,
                Data = blob.Data
            };
        }
 private void setMainEncryptor()
 {
     if (plainTextEncryptRB.Checked)
     {
         encryptor = new PlainText();
     }
     else
     {
         encryptor = new Rot13();
     }
 }
Пример #11
0
        public static VariableDb ToCommon(this Variable variable, IEncryptor encryptor)
        {
            if (variable == null) return null;

            return new VariableDb
            {
                VariableId = variable.VariableId,
                InstanceId = variable.InstanceId,
                VariableKey = variable.VariableKey,
                VariableValue = variable.VariableValue
            };
        }
Пример #12
0
        public Model(object encryptor, object storageController)
        {
            _password = new ConcretePassword();

            if (encryptor is XOR_EncryptorController)
            {
                _encryptor = encryptor as XOR_EncryptorController;
            }

            if(storageController is FILE_StorageController)
            {
                _storageController = storageController as FILE_StorageController;
            }
        }
Пример #13
0
        public static UserDb ToCommon(this User user, IEncryptor encryptor)
        {
            if (user == null) return null;

            return new UserDb
            {
                UserId = user.UserId,
                Login = user.Login,
                Password = user.Password,
                Email = user.Email,
                UserFIO = user.UserFIO,
                RegistrationCode = user.RegistrationCode,
                IsActive = user.IsActive
            };
        }
        public DisplayUserViewModel(Domain.Users.User user, IEncryptor encryptor)
        {
            UserId = user.Id;
            Email = user.Email;
            DisplayName = user.DisplayName;
            Roles = string.Join(", ", user.Roles);
            IsActive = user.IsActive;
            GravatarHash = encryptor.Md5Encrypt(Email).Trim().ToLower();

            AllRoles =
                (
                    from object role in Enum.GetValues(typeof (Domain.Users.Role))
                    select new RoleViewModel { RoleId = (int)role , RoleName = role.ToString(), IsSelected = user.IsInRole(role.ToString())}
                )
                .ToList();
        }
Пример #15
0
        public SecureStoreIndexInput(SecureStoreDirectory directory, Directory cache, ISecureStore store, IEncryptor encryptor, StoreLocation location, string cachePath)
        {
            _directory = directory;
            _cache = cache;
            _name = cachePath;

            _fileMutex = BlobMutexManager.GrabMutex(_name);
            _fileMutex.WaitOne();
            try
            {
                InitialiseFile(store, encryptor, location).WaitAndWrap();
            }
            finally
            {
                _fileMutex.ReleaseMutex();
            }
        }
Пример #16
0
        public static DataLogDb ToCommon(this DataLog dataLog, IEncryptor encryptor)
        {
            if (dataLog == null) return null;

            return new DataLogDb
            {
                DataLogId = dataLog.DataLogId,
                InstanceId = dataLog.InstanceId,
                UserId = dataLog.UserId,
                OperationTime = dataLog.OperationTime,
                TableName = dataLog.TableName,
                RecordId = dataLog.RecordId,
                Operation = dataLog.Operation,
                Details = dataLog.Details,
                TransactionNumber = dataLog.TransactionNumber
            };
        }
Пример #17
0
            public void RecvFromCallback(IAsyncResult ar)
            {
                try
                {
                    EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    int      bytesRead      = _remote.EndReceiveFrom(ar, ref remoteEndPoint);

                    byte[] dataOut = new byte[bytesRead];
                    int    outlen;

                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
                    if (encryptor != null)
                    {
                        encryptor.Decrypt(_buffer, bytesRead, dataOut, out outlen);
                    }
                    else
                    {
                        dataOut = _buffer;
                        outlen  = bytesRead;
                    }

                    byte[] sendBuf = new byte[outlen + 3];
                    Array.Copy(dataOut, 0, sendBuf, 3, outlen);

                    _local.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);
                    Receive();
                }
                catch (ObjectDisposedException)
                {
                    // TODO: handle the ObjectDisposedException
                }
                catch (Exception)
                {
                    // TODO: need more think about handle other Exceptions, or should remove this catch().
                }
                finally
                {
                }
            }
Пример #18
0
        public void Init()
        {
            conection  = new MSSQLDB(new DBConfiguration());
            _PREP      = new ProfessorRepository(conection);
            _encryptor = new Encryptor();
            handler    = new ProfessorQueryHandler(_PREP);

            var db = conection.GetCon();

            var    cpf      = "357.034.413-40";
            string password = cpf.Replace("-", "").Replace(".", "");

            password = _encryptor.Encrypt(password, out string salt);

            professor = new Professor("Lívia", "Emanuelly Elisa", cpf, "*****@*****.**", "(21) 2682-8370", EDegree.Master, password, salt);
            _PREP.Create(professor);

            commandGet = new ProfessorInputGet()
            {
                ProfessorId = professor.Id
            };
        }
Пример #19
0
        /****************************************************************************/
        public static string Decrypt(this IEncryptor encryptor, long iAuthenticator, string strValue)
        {
            if (strValue.Normalized() == "")
            {
                return("");
            }

            try
            {
                string     strDecrypted = encryptor.Decrypt(strValue);
                StringList aParts       = new StringList(strDecrypted, kSeparator, false);

                if (aParts.Count == 2)
                {
                    long iCheckAuthenticator = 0L;

                    if (!long.TryParse(aParts[0], out iCheckAuthenticator))
                    {
                        return("");
                    }

                    if (iCheckAuthenticator != iAuthenticator)
                    {
                        return("");
                    }

                    return(aParts[1]);
                }
                else
                {
                    return(strDecrypted);
                }
            }
            catch
            {
            }

            return(strValue);
        }
Пример #20
0
        /****************************************************************************/
        public static string Decrypt(this IEncryptor encryptor, string strEncrypted)
        {
            if (strEncrypted.Normalized() == "")
            {
                return("");
            }

            try
            {
                int    iLength      = 0;
                char[] chDecrypted  = encryptor.DecryptChars(strEncrypted, out iLength);
                string strDecrypted = new String(chDecrypted, 0, iLength);

                chDecrypted.Clear();

                return(strDecrypted.Replace(((char)6).ToString(), "")); // Was getting weird char problems
            }
            catch (Exception ex)
            {
                return(strEncrypted);
            }
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserService" /> class.
        /// </summary>
        /// <param name="userRepository">The user repository.</param>
        /// <param name="roleRepository">The role repository.</param>
        /// <param name="encryptor">The encryptor.</param>
        public UserService(
            IUserRepository userRepository,
            IRoleRepository roleRepository,
            IEncryptor encryptor)
        {
            if (userRepository == null)
            {
                throw new ArgumentNullException("userRepository");
            }
            else if (roleRepository == null)
            {
                throw new ArgumentNullException("roleRepository");
            }
            else if (encryptor == null)
            {
                throw new ArgumentNullException("encryptor");
            }

            this.UserRepository = userRepository;
            this.RoleRepository = roleRepository;
            this.Encryptor      = encryptor;
        }
Пример #22
0
 public static Configuration Load(string config_str)
 {
     try
     {
         if (GlobalConfiguration.config_password.Length > 0)
         {
             byte[]     cfg_encrypt = System.Convert.FromBase64String(config_str);
             IEncryptor encryptor   = EncryptorFactory.GetEncryptor("aes-256-cfb", GlobalConfiguration.config_password, false);
             byte[]     cfg_data    = new byte[cfg_encrypt.Length];
             int        data_len    = 0;
             const int  buffer_size = 32768;
             byte[]     input       = new byte[buffer_size];
             byte[]     ouput       = new byte[buffer_size + 128];
             for (int start_pos = 0; start_pos < cfg_encrypt.Length; start_pos += buffer_size)
             {
                 int len = Math.Min(cfg_encrypt.Length - start_pos, buffer_size);
                 int out_len;
                 Buffer.BlockCopy(cfg_encrypt, start_pos, input, 0, len);
                 encryptor.Decrypt(input, len, ouput, out out_len);
                 Buffer.BlockCopy(ouput, 0, cfg_data, data_len, out_len);
                 data_len += out_len;
             }
             config_str = UTF8Encoding.UTF8.GetString(cfg_data, 0, data_len);
         }
     }
     catch
     {
     }
     try
     {
         Configuration config = SimpleJson.SimpleJson.DeserializeObject <Configuration>(config_str, new JsonSerializerStrategy());
         config.FixConfiguration();
         return(config);
     }
     catch
     {
     }
     return(null);
 }
Пример #23
0
            /// <summary>
            /// 处理数据,并发送给ss服务器
            /// </summary>
            /// <param name="data"></param>
            /// <param name="length"></param>
            public void Send(byte[] data, int length)
            {
                /*
                 +----+------+------+----------+----------+----------+
                 |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
                 +----+------+------+----------+----------+----------+
                 | 2  |  1   |  1   | Variable |    2     | Variable |
                 +----+------+------+----------+----------+----------+
                 |
                 | trim => (去掉前三位,猜测是无用信息,减小数据大小/网络开销)
                 |
                 +------+----------+----------+----------+
                 | ATYP | DST.ADDR | DST.PORT |   DATA   |
                 +------+----------+----------+----------+
                 |  1   | Variable |    2     | Variable |
                 +------+----------+----------+----------+
                 |
                 | encrypt => (加密)
                 |
                 +-------+--------------+
                 |   IV  |    PAYLOAD   |
                 +-------+--------------+
                 | Fixed |   Variable   |
                 +-------+--------------+
                 */
                // 去掉前三个字节
                IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password, _server.auth, true);

                byte[] dataIn = new byte[length - 3 + IVEncryptor.ONETIMEAUTH_BYTES];
                Array.Copy(data, 3, dataIn, 0, length - 3);
                byte[] dataOut = new byte[length - 3 + 16 + IVEncryptor.ONETIMEAUTH_BYTES];
                int    outlen;

                // 加密
                encryptor.Encrypt(dataIn, length - 3, dataOut, out outlen);
                Logging.Debug($"++++++Send Server Port, size:" + outlen);
                // 发送给ss服务器
                _remote.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint);
            }
Пример #24
0
            public void RecvFromCallback(IAsyncResult ar)
            {
                try
                {
                    if (_remote == null)
                    {
                        return;
                    }
                    EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    int      bytesRead      = _remote.EndReceiveFrom(ar, ref remoteEndPoint);

                    byte[] dataOut = new byte[bytesRead];
                    int    outlen;

                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
                    encryptor.DecryptUDP(_buffer, bytesRead, dataOut, out outlen);

                    byte[] sendBuf = new byte[outlen + 3];
                    Array.Copy(dataOut, 0, sendBuf, 3, outlen);

                    Logging.Debug(_localEndPoint, _remoteEndPoint, outlen, "UDP Relay");
                    _local?.SendTo(sendBuf, outlen + 3, 0, _localEndPoint);

                    Receive();
                }
                catch (ObjectDisposedException)
                {
                    // TODO: handle the ObjectDisposedException
                }
                catch (Exception)
                {
                    // TODO: need more think about handle other Exceptions, or should remove this catch().
                }
                finally
                {
                    // No matter success or failed, we keep receiving
                }
            }
Пример #25
0
        public override byte[] ClientUdpPostDecrypt(byte[] plaindata, int datalength, out int outlength)
        {
            if (datalength <= 8)
            {
                outlength = 0;
                return(plaindata);
            }
            MbedTLS.HMAC md5     = CreateHMAC(user_key);
            byte[]       md5data = md5.ComputeHash(plaindata, 0, datalength - 1);
            if (md5data[0] != plaindata[datalength - 1])
            {
                outlength = 0;
                return(plaindata);
            }
            md5     = CreateHMAC(Server.key);
            md5data = md5.ComputeHash(plaindata, datalength - 8, 7);
            int rand_len = UdpGetRandLen(random_server, md5data);

            outlength = datalength - rand_len - 8;
            encryptor = EncryptorFactory.GetEncryptor("rc4", System.Convert.ToBase64String(user_key) + System.Convert.ToBase64String(md5data, 0, 16));
            encryptor.Decrypt(plaindata, outlength, plaindata, out outlength);
            return(plaindata);
        }
Пример #26
0
        public void Init()
        {
            conection  = new MSSQLDB(new DBConfiguration());
            _PREP      = new ProfessorRepository(conection);
            _encryptor = new Encryptor();
            handler    = new ProfessorCommandHandler(_PREP, _encryptor);

            var db = conection.GetCon();

            var    cpf      = "357.034.413-40";
            string password = cpf.Replace("-", "").Replace(".", "");

            password = _encryptor.Encrypt(password, out string salt);

            professor = new Professor("Lívia", "Emanuelly Elisa", cpf, "*****@*****.**", "(21) 2682-8370", EDegree.Master, password, salt);
            _PREP.Create(professor);

            commandRegister = new ProfessorInputRegister()
            {
                FirstName = "Lívia",
                LastName  = "Emanuelly Elisa",
                CPF       = cpf,
                Email     = "*****@*****.**",
                Phone     = "(21) 2682-8370",
                Degree    = EDegree.Master
            };

            commandUpdate = new ProfessorInputUpdate()
            {
                ProfessorId = professor.Id,
                FirstName   = "Lívia",
                LastName    = "Emanuelly Elisa",
                Email       = "*****@*****.**",
                Phone       = "(21) 2682-8370",
                Degree      = EDegree.Master
            };
        }
Пример #27
0
        private void RunAEADEncryptionRound(IEncryptor encryptor, IEncryptor decryptor)
        {
            byte[]    plain = new byte[16384];
            const int Salt  = 32;

            // make the cipher array large enough to hold chunks
            byte[] cipher  = new byte[plain.Length * 2 + Salt];
            byte[] plain2  = new byte[plain.Length + Salt];
            int    outLen  = 0;
            int    outLen2 = 0;

            _random.NextBytes(plain);
            // make sure we have initialized the address buffer
            Buffer.BlockCopy(abufBytes, 0, plain, 0, abufLength);
            encryptor.Encrypt(plain, plain.Length, cipher, out outLen);
            decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
            Assert.AreEqual(plain.Length, outLen2);
            for (int j = 0; j < plain.Length; j++)
            {
                Assert.AreEqual(plain[j], plain2[j]);
            }
            encryptor.Encrypt(plain, 1000, cipher, out outLen);
            decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
            Assert.AreEqual(1000, outLen2);
            for (int j = 0; j < outLen2; j++)
            {
                Assert.AreEqual(plain[j], plain2[j]);
            }
            encryptor.Encrypt(plain, 12333, cipher, out outLen);
            decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
            Assert.AreEqual(12333, outLen2);
            for (int j = 0; j < outLen2; j++)
            {
                Assert.AreEqual(plain[j], plain2[j]);
            }
        }
Пример #28
0
        public Form1(IEncryptor encryptor, IFileOperator fileOperator)
        {
            InitializeComponent();

            this._encryptor    = encryptor;
            this._fileOperator = fileOperator;

            this.cb_encoding.DataSource = new List <Encoding>()
            {
                Encoding.Default,
                Encoding.UTF8,
                Encoding.ASCII,
                Encoding.Unicode,
                Encoding.BigEndianUnicode
            };
            this.cb_encoding.DisplayMember = nameof(Encoding.EncodingName);

            this.bt_encrypt.Enabled = false;
            this.bt_decrypt.Enabled = false;

            this._searchNavigator = new SearchNavigator();

            this.ProcessCommandArgs(Environment.GetCommandLineArgs());
        }
Пример #29
0
        public void Test_LoadCustom()
        {
            MockRepository mocks = new MockRepository();

            // Set new encryptor
            EsapiConfig.Instance.Encryptor.Type = typeof(SurrogateEncryptor).AssemblyQualifiedName;

            IEncryptor encryptor = Esapi.Encryptor;

            Assert.IsTrue(encryptor.GetType().Equals(typeof(SurrogateEncryptor)));

            // Do some calls
            IEncryptor mockEncryptor = mocks.StrictMock <IEncryptor>();

            ((SurrogateEncryptor)encryptor).Impl = mockEncryptor;

            Expect.Call(mockEncryptor.VerifySeal(null)).Return(true);
            Expect.Call(mockEncryptor.Seal(null, 0)).Return(null);
            mocks.ReplayAll();

            Assert.IsTrue(encryptor.VerifySeal(null));
            Assert.IsNull(encryptor.Seal(null, 0));
            mocks.VerifyAll();
        }
 public DefaultMembershipProvider(IUserRepository repository, IEncryptor encryptor)
 {
     m_repository = repository;
     m_encryptor = encryptor;
 }
Пример #31
0
 public AuthService()
 {
     this.unitOfWork = new UnitOfWork();
     this.encryptor  = new Encryptor();
 }
 public void SetPassword(string password, IEncryptor encryptor)
 {
     Salt     = encryptor.GetSalt(password);
     Password = encryptor.GetHash(password, Salt);
 }
Пример #33
0
            public async Task Start(byte[] data, int length)
            {
                Interlocked.Exchange(ref _state, _running);
                SaeaAwaitable upSaea   = null;
                SaeaAwaitable downSaea = null;

                try
                {
                    Logging.Debug($"-----UDP relay got {length}-----");
                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
                    byte[]     dataIn    = new byte[length - 3];
                    Array.Copy(data, 3, dataIn, 0, length - 3);

                    upSaea = _argsPool.Rent();
                    int outlen;
                    encryptor.EncryptUDP(dataIn, dataIn.Length, upSaea.Saea.Buffer, out outlen);
                    upSaea.Saea.SetBuffer(0, outlen);
                    upSaea.Saea.RemoteEndPoint = _serverEndPoint;

                    var ret = await _serverSocket.SendToAsync(upSaea);

                    if (ret != SocketError.Success)
                    {
                        Logging.Error($"[udp] remote sendto {ret},{upSaea.Saea.BytesTransferred}");
                        Close();
                        return;
                    }
                    Logging.Debug($"[udp] remote sendto {_localEndPoint} -> {_serverEndPoint} {upSaea.Saea.BytesTransferred}");

                    _argsPool.Return(upSaea);
                    upSaea = null;

                    while (IsRunning)
                    {
                        downSaea = _argsPool.Rent();
                        downSaea.Saea.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        ret = await _serverSocket.ReceiveFromAsync(downSaea);

                        var bytesReceived = downSaea.Saea.BytesTransferred;
                        if (ret != SocketError.Success)
                        {
                            Logging.Error($"[udp] remote recvfrom {ret},{bytesReceived}");
                            Close();
                            return;
                        }
                        Logging.Debug($"[udp] remote recvfrom {downSaea.Saea.RemoteEndPoint} -> {_localSocket.LocalEndPoint} {bytesReceived}");
                        byte[] dataOut = new byte[bytesReceived];
                        encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
                        encryptor.DecryptUDP(downSaea.Saea.Buffer, bytesReceived, dataOut, out outlen);
                        downSaea.ClearAndResetSaeaProperties();

                        byte[] buf = downSaea.Saea.Buffer;
                        buf[0] = buf[1] = buf[2] = 0;
                        Array.Copy(dataOut, 0, buf, 3, outlen);
                        downSaea.Saea.RemoteEndPoint = _localEndPoint;
                        downSaea.Saea.SetBuffer(0, outlen + 3);
                        ret = await _localSocket.SendToAsync(downSaea);

                        if (ret != SocketError.Success)
                        {
                            Logging.Error($"[udp] local sendto {ret},{downSaea.Saea.BytesTransferred}");
                            Close();
                            return;
                        }
                        Logging.Debug($"[udp] local sendto {_localSocket.LocalEndPoint} -> {_localEndPoint} {downSaea.Saea.BytesTransferred}");
                        _argsPool.Return(downSaea);
                        downSaea = null;
                    }
                }
                catch (Exception e)
                {
                    Logging.LogUsefulException(e);
                    Close();
                }
                finally
                {
                    _argsPool.Return(upSaea);
                    upSaea = null;
                    _argsPool.Return(downSaea);
                    downSaea = null;
                }
            }
Пример #34
0
 public XmlFileWriter(IEncryptor encryptor)
 {
     _encryptor = encryptor;
 }
Пример #35
0
        private async Task InitialiseFile(ISecureStore store, IEncryptor encryptor, StoreLocation location)
        {
            bool fFileNeeded = false;
            if (!_cache.FileExists(_name))
            {
                fFileNeeded = true;
            }
            else
            {
                long cachedLength = _cache.FileLength(_name);

                var metadata = await store.GetMetadata(location).ConfigureAwait(false);
                if (metadata == null)
                {
                    throw new System.IO.FileNotFoundException(_name);
                }

                var blobLength = metadata.ContentLength ?? 0;
                var blobLastModifiedUTC = metadata.LastModified ?? DateTime.UtcNow;

                if (cachedLength != blobLength)
                {
                    fFileNeeded = true;
                }
                else
                {
                    // there seems to be an error of 1 tick which happens every once in a while 
                    // for now we will say that if they are within 1 tick of each other and same length 
                    var elapsed = _cache.FileModified(_name);

                    // normalize RAMDirectory and FSDirectory times
                    if (elapsed > ticks1970)
                    {
                        elapsed -= ticks1970;
                    }

                    var cachedLastModifiedUTC = new DateTime(elapsed, DateTimeKind.Local).ToUniversalTime();
                    if (cachedLastModifiedUTC != blobLastModifiedUTC)
                    {
                        var timeSpan = blobLastModifiedUTC.Subtract(cachedLastModifiedUTC);
                        if (timeSpan.TotalSeconds > 1)
                        {
                            fFileNeeded = true;
                        }
                    }
                }
            }

            // if the file does not exist
            // or if it exists and it is older then the lastmodified time in the blobproperties (which always comes from the blob storage)
            if (fFileNeeded)
            {
                using (StreamOutput fileStream = _directory.CreateCachedOutputAsStream(_name))
                {
                    var data = await store.LoadData(location, null, encryptor).ConfigureAwait(false);
                    if (data == null)
                    {
                        throw new System.IO.FileNotFoundException(_name);
                    }
                    await data.Stream.CopyToStream(fileStream, CancellationToken.None).ConfigureAwait(false);
                }

                // and open it as an input 
                _indexInput = _cache.OpenInput(_name);
            }
            else
            {
                // open the file in read only mode
                _indexInput = _cache.OpenInput(_name);
            }
        }
Пример #36
0
 public TokenService(IEncryptor encryptor, IUserService userService)
 {
     this.encryptor = encryptor;
     this.userService = userService;
 }
Пример #37
0
		public void SetParameterValues(IDictionary<string,string> parameters)
		{
			if (parameters != null)
			{
				object parmValue = parameters["encryptor"];
				encryptor = parmValue != null
				            	? ReflectionExtensions.Instantiate<IEncryptor>(Type.GetType(parmValue.ToString()))
				            	: new uNHAddinsEncryptor();

				parmValue = parameters["encryptionKey"];
				if (parmValue != null)
				{
					encryptor.EncryptionKey = parameters["encryptionKey"].ToString();
				}
			}
			else
			{
				encryptor = new uNHAddinsEncryptor();
			}
		}
Пример #38
0
 public UserRepository()
 {
     _encryptor = new Encryptor();
 }
Пример #39
0
        public void BeginConnect(string method, string password, IPEndPoint ep, string proxyServerURI, int proxyServerPort, AsyncCallback callback, Object state)
        {
            if (this.State == ConnectState.END)
            {
                throw new SocketException((int)SocketError.ConnectionAborted);
            }
            Update();
            {
                if (this.State == ConnectState.READY)
                {
                    encryptMethod = method;
                    encryptPassword = password;
                    this.encryptor = EncryptorFactory.GetEncryptor(method, password);
                    this.decryptor = EncryptorFactory.GetEncryptor(method, password);
                    this.sockEndPoint = ep;
                    this.proxyServerURI = proxyServerURI;
                    this.proxyServerPort = proxyServerPort;

                    sock = new Socket(ep.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                    sock.SendBufferSize = 1024 * 1024 * 4;
                    sock.ReceiveBufferSize = 1024 * 1024 * 4;

                    random.NextBytes(localid);
                    byte[] sendBuffer = CreateConnectData();

                    lock (asyncCallBackSendLock)
                    {
                        this.asyncCallBackSend = callback;
                        //this.callBackState = state;
                    }

                    RemoteSendto(sendBuffer, sendBuffer.Length, -1, false);
                    doRecv();
                    this.State = ConnectState.CONNECTING;
                }
            }
        }
Пример #40
0
 public FileSystem(ICredManager manager, IEncryptor crypto)
 {
 }
Пример #41
0
 public ClientPeer(IPEndPoint superPeerEndPoint, IEncryptor encryptor)
 {
     Peer = new Peer(superPeerEndPoint, encryptor);
 }
Пример #42
0
 private void Connect()
 {
     lock (server)
     {
         server.ServerSpeedLog().AddConnectTimes();
         if (this.State == ConnectState.HANDSHAKE)
         {
             this.State = ConnectState.CONNECTING;
         }
         server.GetConnections().AddRef(this.connection);
         encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
         encryptorUDP = EncryptorFactory.GetEncryptor(server.method, server.password);
     }
     this.obfs = ObfsFactory.GetObfs(server.obfs);
     closed = false;
     {
         IPAddress ipAddress;
         string serverURI = server.server;
         int serverPort = server.server_port;
         if (socks5RemotePort > 0)
         {
             serverURI = socks5RemoteHost;
             serverPort = socks5RemotePort;
         }
         bool parsed = IPAddress.TryParse(serverURI, out ipAddress);
         if (!parsed)
         {
             //IPHostEntry ipHostInfo = Dns.GetHostEntry(serverURI);
             //ipAddress = ipHostInfo.AddressList[0];
             if (server.DnsBuffer().isExpired(serverURI))
             {
                 Dns.BeginGetHostEntry(serverURI, new AsyncCallback(DnsCallback), null);
                 return;
             }
             else
             {
                 ipAddress = server.DnsBuffer().ip;
             }
         }
         //else
         BeginConnect(ipAddress, serverPort);
     }
 }
Пример #43
0
 public CryptoController(IEncryptor encryptor, IDecryptor decryptor, IDbSettingsResolved dbSettingsResolved)
 {
     _encryptor          = encryptor;
     _decryptor          = decryptor;
     _dbSettingsResolved = dbSettingsResolved;
 }
Пример #44
0
 public MessageManager()
 {
     _encryptor = null;
 }
Пример #45
0
 public MessageManager(IEncryptor encryptor)
 {
     _encryptor = encryptor;
 }
Пример #46
0
 public AddApplicationCommand(IEncryptor encryptor)
 {
     _encryptor = encryptor;
 }
Пример #47
0
//************************************************************************************************************************
        public UserService(IEncryptor encryptor)
        {
            this.encryptor = encryptor;

            this.context = new FinalDbContext();
        }
Пример #48
0
 /****************************************************************************/
 public KeyStore(IBlobStore blobStore, IEncryptor keyEncryptor)
 {
     _blobStore    = blobStore;
     _keyEncryptor = keyEncryptor;
 }
Пример #49
0
 public UserController(IUserRepository userRepository, IEncryptor encryptor
                       )
 {
     _userRepository = userRepository;
     _encryptor      = encryptor;
 }
Пример #50
0
        public void ServerFromSS(string ssURL)
        {
            // ss://obfs:protocol:method:passwd@host:port/#remarks
            string[] r1     = Regex.Split(ssURL, "ss://", RegexOptions.IgnoreCase);
            string   base64 = r1[1].ToString();
            string   data   = DecodeBase64(base64);

            if (data.Length == 0)
            {
                throw new FormatException();
            }
            try
            {
                int indexLastAt       = data.LastIndexOf('@');
                int remarkIndexLastAt = data.IndexOf('#', indexLastAt);
                if (remarkIndexLastAt > 0)
                {
                    if (remarkIndexLastAt + 1 < data.Length)
                    {
                        this.remarks_base64 = data.Substring(remarkIndexLastAt + 1);
                    }
                    data = data.Substring(0, remarkIndexLastAt);
                }
                remarkIndexLastAt = data.IndexOf('/', indexLastAt);
                string param = "";
                if (remarkIndexLastAt > 0)
                {
                    if (remarkIndexLastAt + 1 < data.Length)
                    {
                        param = data.Substring(remarkIndexLastAt + 1);
                    }
                    data = data.Substring(0, remarkIndexLastAt);
                }
                //int paramIndexLastAt = param.IndexOf('?', indexLastAt);
                //Dictionary<string, string> params_dict = new Dictionary<string, string>();
                //if (paramIndexLastAt >= 0)
                //{
                //    string[] obfs_params = param.Substring(paramIndexLastAt + 1).Split('&');
                //    foreach (string p in obfs_params)
                //    {
                //        if (p.IndexOf('=') > 0)
                //        {
                //            int index = p.IndexOf('=');
                //            string key, val;
                //            key = p.Substring(0, index);
                //            val = p.Substring(index + 1);
                //            try
                //            {
                //                byte[] b64_bytes = System.Convert.FromBase64String(val);
                //                if (b64_bytes != null)
                //                {
                //                    val = Encoding.UTF8.GetString(b64_bytes);
                //                }
                //            }
                //            catch (FormatException)
                //            {
                //                continue;
                //            }
                //            params_dict[key] = val;
                //        }
                //    }
                //}

                string afterAt        = data.Substring(indexLastAt + 1);
                int    indexLastColon = afterAt.LastIndexOf(':');
                this.server_port = int.Parse(afterAt.Substring(indexLastColon + 1));
                this.server      = afterAt.Substring(0, indexLastColon);

                string beforeAt = data.Substring(0, indexLastAt);
                this.method = "";
                for (bool next = true; next;)
                {
                    string[] parts = beforeAt.Split(new[] { ':' }, 2);
                    if (parts.Length > 1)
                    {
                        try
                        {
                            Obfs.ObfsBase obfs = (Obfs.ObfsBase)Obfs.ObfsFactory.GetObfs(parts[0]);
                            if (obfs.GetObfs().ContainsKey(parts[0]))
                            {
                                int[] p = obfs.GetObfs()[parts[0]];
                                if (p[0] == 1)
                                {
                                    this.protocol = parts[0];
                                }
                                if (p[1] == 1)
                                {
                                    this.obfs = parts[0];
                                }
                            }
                            else
                            {
                                next = false;
                            }
                        }
                        catch
                        {
                            try
                            {
                                IEncryptor encryptor = EncryptorFactory.GetEncryptor(parts[0], "m");
                                encryptor.Dispose();
                                this.method = parts[0];
                                beforeAt    = parts[1];
                            }
                            catch
                            {
                            }
                            break;
                        }
                        beforeAt = parts[1];
                    }
                    else
                    {
                        break;
                    }
                }
                if (this.method.Length == 0)
                {
                    throw new FormatException();
                }
                this.password = beforeAt;
                //if (params_dict.ContainsKey("obfs"))
                //{
                //    this.obfsparam = params_dict["obfs"];
                //}
            }
            catch (IndexOutOfRangeException)
            {
                throw new FormatException();
            }
        }
 public SuperuserAccountService(IUnitOfWork unitOfWork, IRegisterValidator registerValidator, IEncryptor encryptor, ISession session)
     : base(unitOfWork, registerValidator, encryptor, session)
 {
 }
Пример #52
0
 public void Init()
 {
     _encryptionByPleyfer = new EncryptionByPleyfer();
 }
        public bool ValidatePassword(string password, IEncryptor encryptor)
        {
            var isValid = Password.Equals(encryptor.GetHash(password, Salt));

            return(isValid);
        }
Пример #54
0
 /// <summary>
 /// Construct with data
 /// </summary>
 public HttpRequestGet(Uri url, IEncryptor encrptor) : base(url, encrptor)
 {
 }
Пример #55
0
 public AuthService(IUnitOfWork unitOfWork, IEncryptor encryptor)
 {
     this.unitOfWork = unitOfWork;
     this.encryptor  = encryptor;
 }
 public EncryptingActionSettingsSerialiser(IActionSettingsSerialiser serialiser, IEncryptor encryptor)
 {
     _serialiser = serialiser;
     _encryptor = encryptor;
 }
Пример #57
0
 private PasswordSetting(IEncryptor encryptor)
 {
     _encryptor = encryptor;
 }
Пример #58
0
 public static void SetEncryptor(IEncryptor encryptor)
 {
     _encryptor = encryptor;
 }
Пример #59
0
 public void CreateEncryptor(string method, string password)
 {
     _encryptor = EncryptorFactory.GetEncryptor(method, password);
     _method    = method;
     _password  = password;
 }
Пример #60
0
 public void CreateRemote()
 {
     Server server = controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)connection.RemoteEndPoint);
     if (server == null || server.server == "")
     {
         throw new ArgumentException("No server configured");
     }
     encryptor = EncryptorFactory.GetEncryptor(server.method, server.password, server.auth, false);
     this.server = server;
 }