Пример #1
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);
        }
Пример #2
0
        /// <summary>
        /// Read meta information <see cref="Entity"/>
        /// </summary>
        /// <param name="stream">Stream.</param>
        /// <param name="decryptor">Decryptor.</param>
        /// <param name="decryptIndexBlock">Index Decrypt Block.</param>
        /// <param name="endian">File endian.</param>
        /// <param name="version">File version.</param>
        /// <returns></returns>
        public static Entity Read(Stream stream, IDecryptor decryptor, ref ulong decryptIndexBlock, Endian endian)
        {
            var cryptBlockCount = 0ul;
            var nextDecrIndex   = 0ul;

            var type = decryptor.ReadInt32(stream, decryptIndexBlock + cryptBlockCount, ref nextDecrIndex, endian);

            var blockSize = (ulong)Marshal.SizeOf(type);

            cryptBlockCount += (blockSize + Decryptor.CryptBlockSize - 1) / Decryptor.CryptBlockSize;

            var size = decryptor.ReadInt32(stream, decryptIndexBlock + cryptBlockCount, ref nextDecrIndex, endian);

            blockSize        = (ulong)Marshal.SizeOf(size);
            cryptBlockCount += (blockSize + Decryptor.CryptBlockSize - 1) / Decryptor.CryptBlockSize;
            var startDecryptIndexBlock = decryptIndexBlock + cryptBlockCount;

            var offset = stream.Position;

            cryptBlockCount += (ulong)((size + Decryptor.CryptBlockSize - 1) / Decryptor.CryptBlockSize);
            stream.Seek(size, SeekOrigin.Current);

            decryptIndexBlock += cryptBlockCount;
            return(new Entity
            {
                Type = type,
                Size = size,
                OffsetRawBlock = offset,
                DecryptIndexBlock = startDecryptIndexBlock,
            });
        }
Пример #3
0
        static void Main(string[] args)
        {
            DecryptorFactory decryptorFactory     = new DecryptorFactory();
            IDecryptor       applicationDecryptor = decryptorFactory.CreateDecryptor();

            AuthorizerFactory authorizerFactory     = new AuthorizerFactory();
            IAuthorizer       applicationAuthorizer = authorizerFactory.CreateAuthorizer();

            Context applicationContext = new Context(applicationDecryptor, applicationAuthorizer);
            UI      userInterface      = new UI();

            bool readAnotherFile = false;

            do
            {
                applicationContext = userInterface.AddUserInfoToContext(applicationContext);

                // handles opening file and displaying content to the console
                FileReader ApplicationFileReader = new FileReader(applicationContext);
                ApplicationFileReader.DisplayContent();

                // ask user if application should read another file
                readAnotherFile = userInterface.AskReadAnotherFile();
            } while (readAnotherFile);
        }
Пример #4
0
 // Constructor.
 public LetsKodeUiComponent
 (
     ITestBackgroundDataProvider <UserRole, TestEnvironment> testBackgroundDataProvider,
     IDecryptor decryptor = null
 )
     : base(testBackgroundDataProvider, decryptor)
 {
 }
 // To match the ISerializer<T> interface we must take passphrase and salt as parameter
 // restricting the usages of this class' instances.
 public EncryptionSerializer(ISerializer <T> serializer, IEncryptor encryptor, IDecryptor decryptor, SecureString passphrase, string salt)
 {
     _serializer = serializer;
     _encryptor  = encryptor;
     _decryptor  = decryptor;
     _passphrase = passphrase;
     _salt       = salt;
 }
Пример #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 void Setup()
        {
            IAlgorithmFactory algorithmFactory = new GenericAlgorithmFactory <AesManaged>();
            ICryptoSettings   settings         = new Settings();

            encryptor = new StringEncryptor(algorithmFactory, settings);
            decryptor = new StringDecryptor(algorithmFactory, settings);
        }
Пример #8
0
 // Constructor.
 public SignInFlowComponent
 (
     ITestBackgroundDataProvider <UserRole, TestEnvironment> testBackgroundDataProvider,
     IDecryptor decryptor
 )
     : base(testBackgroundDataProvider, decryptor)
 {
 }
 public void DecryptFile(string filePath)
 {
     if (File.Exists(filePath) && !IsPlainText(filePath))
     {
         IDecryptor decryptor      = _keyProvider.GetDecryptor();
         byte[]     decryptedbytes = decryptor.Transform(File.ReadAllBytes(filePath));
         File.WriteAllBytes(filePath, decryptedbytes);
     }
 }
Пример #10
0
        private void DecryptWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            TimeSpan  ts;
            const int timeSlice = 50;
            const int nrOfSpeedMeasurements = 50;
            ulong     passwordCount = 0, prevPasswordCount = 0;

            object[]          args             = (object[])e.Argument;
            IDecryptor        decryptor        = DecryptorFactory.Get((EncryptionRecord)args[0]);
            IPasswordIterator passwordIterator = (IPasswordIterator)args[1];
            ValidationMode    validationMode   = (ValidationMode)args[2];
            IMovingAverage    avg              = new SimpleMovingAverage(nrOfSpeedMeasurements);
            PasswordValidity  passwordValidity = PasswordValidity.Invalid;
            Stopwatch         stopWatch        = new Stopwatch();

            stopWatch.Start();
            string currentPassword = passwordIterator.GetNextPassword();

            while (!string.IsNullOrEmpty(currentPassword) &&
                   validationMode != ValidationMode.None &&
                   !decryptBackgroundWorker.CancellationPending)
            {
                passwordValidity = decryptor.ValidatePassword(currentPassword, validationMode);

                passwordCount++;
                ts = stopWatch.Elapsed;
                if (ts.Milliseconds > timeSlice || passwordValidity != PasswordValidity.Invalid)
                {
                    avg.AddSample((60000 * (passwordCount - prevPasswordCount)) / ((ulong)ts.Milliseconds + 1)); //Avoid div by zero
                    decryptBackgroundWorker.ReportProgress(0, new object[]
                                                           { passwordValidity, currentPassword, (ulong)avg.Average, passwordCount });
                    prevPasswordCount = passwordCount;
                    stopWatch.Restart();

                    if ((passwordValidity & PasswordValidity.OwnerPasswordIsValid) == PasswordValidity.OwnerPasswordIsValid)
                    {
                        validationMode &= ~ValidationMode.ValidateOwnerPassword;
                    }

                    if ((passwordValidity & PasswordValidity.UserPasswordIsValid) == PasswordValidity.UserPasswordIsValid)
                    {
                        validationMode &= ~ValidationMode.ValidateUserPassword;
                    }
                }
                currentPassword = passwordIterator.GetNextPassword();
            }

            if (decryptBackgroundWorker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                e.Result = passwordCount;
            }
        }
Пример #11
0
 public IConfigurationStore Initialize(
     IConfigurationValidator validator = null,
     IErrorLogger errorLogger          = null,
     IDecryptor decryptor = null)
 {
     _validator   = validator ?? new DefaultValidator();
     _errorLogger = errorLogger ?? new DefaultErrorLogger();
     _decryptor   = decryptor ?? new DefaultDecryptor();
     return(this);
 }
Пример #12
0
 public int SetDecryptor(string dll)
 {
     Decrypt = Decryptor.Decryptor.InitDecryptDll(dll);
     if (Decrypt == null)
     {
         Console.WriteLine("Unable to load the decryptor dll!");
         return(-1);
     }
     return(Decrypt.DecryptInit());
 }
Пример #13
0
 public AuthBasicFeature()
 {
     this.dataProvider = new InsuranceOneTestBackgroundDataProvider();
     this.decryptor    = new DummyDecryptor();
     this.signInComponent
         = new SignInFlowComponent <UserRole, TestEnvironment>
           (
               this.dataProvider,
               this.decryptor
           );
 }
Пример #14
0
        internal static T Decrypt <T>(Encrypted encrypted, IDecryptor decryptor)
        {
            var plaintext = decryptor.Decrypt(encrypted).ToUtf8();

            try
            {
                return(JsonConvert.DeserializeObject <T>(plaintext));
            }
            catch (JsonException e)
            {
                throw new InternalErrorException("Failed to parse JSON", e);
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            // TODO - change with your decryptor
            IDecryptor decryptor = null;
            var        uplink    = new Uplink(decryptor);

            var results = uplink.Run();

            results.ForEach(Console.WriteLine);

            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }
 public void PrintFile(string filePath)
 {
     if (File.Exists(filePath) && !IsPlainText(filePath))
     {
         IDecryptor decryptor      = _keyProvider.GetDecryptor();
         byte[]     decryptedBytes = decryptor.Transform(File.ReadAllBytes(filePath));
         _printer.Print(Encoding.ASCII.GetString(decryptedBytes));
     }
     else
     {
         _printer.Print(File.ReadAllText(filePath));
     }
 }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Connection"/> class.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="encryptor">The encryptor.</param>
        /// <param name="decryptor">The decryptor.</param>
        public Connection(Socket socket, IEncryptor encryptor, IDecryptor decryptor)
        {
            this.socket         = socket;
            this.remoteEndPoint = socket.RemoteEndPoint;
            this.encryptor      = encryptor;
            this.decryptor      = decryptor;
            encryptor?.Reset();
            decryptor?.Reset();

            this.receiveEventArgs = new SocketAsyncEventArgs();
            this.receiveEventArgs.SetBuffer(this.buffer, 0, this.buffer.Length);
            this.receiveEventArgs.Completed += (sender, args) => this.EndReceive(args);
        }
Пример #18
0
        public static Either <Response <ErrorCode>, Response <T> > Read <T>(IDecryptor decryptorLeft,
                                                                            IDecryptor decryptorRight, NetMQMessage message)
        {
            // Frame 0: Message type
            // Frame 1: Payload
            Debug.Assert(message.FrameCount == 2);

            var type = (MessageType)message.First.ConvertToInt32();

            return(type == MessageType.Error
                ? (Either <Response <ErrorCode>, Response <T> >) new Left <Response <ErrorCode>, Response <T> >(
                       Read <ErrorCode>(decryptorLeft, message))
                : new Right <Response <ErrorCode>, Response <T> >(Read <T>(decryptorRight, message)));
        }
Пример #19
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;
        }
Пример #20
0
        public DbSettingsBridge(IOptionsSnapshot <DbSettings> dbSettings, ISettingsValidator validator, IDecryptor decryptor)
        {
            _dbSettings = dbSettings ?? throw new ArgumentNullException(nameof(dbSettings));
            _decryptor  = decryptor ?? throw new ArgumentException(nameof(decryptor));
            if (validator == null)
            {
                throw new ArgumentNullException(nameof(validator));
            }

            if (!validator.TryValidate(dbSettings.Value, out var validationException))
            {
                throw validationException;
            }
        }
Пример #21
0
        private static ICollection <Entity> ReadEntities(IDecryptor decryptor, string fileName)
        {
            using (var stream = File.OpenRead(fileName))
            {
                var header = ReadHeader(stream);
                var endian = GetEndian(header.Version);

                var cryptBlockIndex = 0ul;

                var countEntities = decryptor.ReadInt32(stream, cryptBlockIndex, ref cryptBlockIndex, endian);

                return(Enumerable.Range(0, countEntities)
                       .Select(v => Entity.Read(stream, decryptor, ref cryptBlockIndex, endian))
                       .ToArray());
            }
        }
Пример #22
0
        public FileContainer(string filePath, ILogger logger = null)
        {
            FilePath = filePath;
            _logger  = logger;


            if (!File.Exists(FilePath))
            {
                _logger?.LogCritical("File not found: {filePath}.", filePath);
                throw new FileNotFoundException("File not found.", filePath);
            }

            Initialize();

            _decryptor = new Decryptor(Header.Seed);
        }
Пример #23
0
        public static Response <T> Read <T>(IDecryptor decryptor, NetMQMessage message)
        {
            // Frame 0: Message type
            // Frame 1: Payload
            Debug.Assert(message.FrameCount == 2);

            var type = (MessageType)message.Pop().ConvertToInt32();

            var payload = default(T);

            if (!message.First.IsEmpty)
            {
                payload = JsonConvert.DeserializeObject <T>(decryptor.Decrypt(message.Pop().ToByteArray()));
            }

            return(new Response <T>(type, payload));
        }
        private void Setup(string cryptoId)
        {
            _cryptoMock = new Mock <ICrypto>();
            _encryptor  = new Mock <IEncryptor>().Object;
            _decryptor  = new Mock <IDecryptor>().Object;

            _cryptoMock.Setup(f => f.CanEncrypt(cryptoId)).Returns(true);
            _cryptoMock.Setup(f => f.CanEncrypt(It.Is <string>(s => s != cryptoId))).Returns(false);
            _cryptoMock.Setup(f => f.Encrypt(It.IsAny <string>(), It.IsAny <string>())).Returns($"EncryptedString : {cryptoId}");
            _cryptoMock.Setup(f => f.Encrypt(It.IsAny <byte[]>(), It.IsAny <string>())).Returns(Encoding.UTF8.GetBytes(cryptoId));
            _cryptoMock.Setup(f => f.GetEncryptor(cryptoId)).Returns(_encryptor);

            _cryptoMock.Setup(f => f.CanDecrypt(cryptoId)).Returns(true);
            _cryptoMock.Setup(f => f.CanDecrypt(It.Is <string>(s => s != cryptoId))).Returns(false);
            _cryptoMock.Setup(f => f.Decrypt(It.IsAny <string>(), It.IsAny <string>())).Returns($"DecryptedString : {cryptoId}");
            _cryptoMock.Setup(f => f.Decrypt(It.IsAny <byte[]>(), It.IsAny <string>())).Returns(Encoding.UTF8.GetBytes(cryptoId));
            _cryptoMock.Setup(f => f.GetDecryptor(cryptoId)).Returns(_decryptor);
        }
Пример #25
0
        public ClientAuthorization(
            IDecryptor decryptor,
            IEncryptor encryptor,
            IServiceContext serviceContext,
            IRepository <AuthorizationInfo> authorizationInfoRepo)
        {
            _decryptor             = decryptor;
            _authorizationInfoRepo = authorizationInfoRepo;
            _encryptor             = encryptor;
            _serviceContext        = serviceContext;

            // 初始化授权数据并保存到缓存中
            var authorizationCaches = _authorizationInfoRepo.GetAllList().Select(p => {
                return(new AuthorizationCache(p, _serviceContext));
            }).ToList();

            _auths = authorizationCaches;
        }
        public static Int32 ReadInt32(
            this IDecryptor decryptor,
            Stream stream,
            ulong cryptBlockIndex,
            ref ulong nextCryptBlockIndex,
            Endian endian
            )
        {
            var buffer = stream.FillBuffer(4);

            decryptor.Decrypt(buffer, cryptBlockIndex, ref nextCryptBlockIndex);
            if (endian == Endian.Big)
            {
                Array.Reverse(buffer);
            }

            return(BitConverter.ToInt32(buffer, 0));
        }
Пример #27
0
        private static void ProcessDecryptCommand(DecryptVerbOptions options)
        {
            string inputFilePath = options.InputFilePath;

            Console.Out.WriteLine($@"The file ""{Path.GetFileName(inputFilePath)}"" is being decrypted...");

            byte[] inputByteArray = File.ReadAllBytes(options.InputFilePath);
            byte[] keyByteArray   = File.ReadAllBytes(options.KeyPath);

            IDecryptor desDecryptor = CryptoFactory.CreateDecryptor(inputByteArray, keyByteArray);

            byte[] decryptedData = desDecryptor.DecryptData();

            GenerateOutputFileNameIfNotSet(options);
            FileStream outputFileStream = File.OpenWrite(options.OutputFilePath);

            outputFileStream.Write(decryptedData, 0, decryptedData.Length);

            Console.Out.WriteLine($"The result file is: {Path.GetFileName(options.OutputFilePath)}");
        }
Пример #28
0
 public virtual byte[] DecryptByteArray(byte[] b)
 {
     try {
         MemoryStream ba  = new MemoryStream();
         IDecryptor   dec = securityHandler.GetDecryptor();
         byte[]       b2  = dec.Update(b, 0, b.Length);
         if (b2 != null)
         {
             ba.Write(b2);
         }
         b2 = dec.Finish();
         if (b2 != null)
         {
             ba.Write(b2);
         }
         return(ba.ToArray());
     }
     catch (System.IO.IOException e) {
         throw new PdfException(PdfException.PdfEncryption, e);
     }
 }
Пример #29
0
        public IEnumerable <byte[]> GetDataBlocks(IDecryptor decryptor)
        {
            byte[] buf = null;
            while (true)
            {
                if (buf != null)
                {
                    //yield return decryptor.DecryptBlock(buf, false);
                    yield return(buf);
                }

                byte tag = this._binaryReader.ReadByte();
                if (tag != 0x42)
                {
                    yield break;
                }

                IFileStreamHandler <IDictionary <string, object> > dataHandler =
                    this._handlerFactory.GetHandler <IDictionary <string, object> >(tag);
                IDictionary <string, object> contentDirectory = dataHandler.Handle(this._binaryReader);
                contentDirectory.TryGetValue("type", out var typeValue);
                string typeValueString = typeValue as string;
                if (!"data".Equals(typeValueString))
                {
                    if ("metadata".Equals(typeValueString))
                    {
                        contentDirectory.TryGetValue("file_md5", out var md5Value);
                        string md5String = md5Value as string;
                        if (md5String != null)
                        {
                            this._contentHash = md5String;
                        }
                    }

                    yield break;
                }

                buf = (byte[])contentDirectory["data"];
            }
        }
Пример #30
0
        public static Request <T> Read <T>(IDecryptor decryptor, NetMQMessage message)
        {
            // Frame 0: RequesterID
            // Frame 1: Empty
            // Frame 2: Message type
            // Frame 3: Payload
            Debug.Assert(message.FrameCount == 4);

            var requester = message.Pop().ToByteArray();

            message.Pop(); // Empty frame
            var type = (MessageType)message.Pop().ConvertToInt32();

            var payload = default(T);

            if (!message.First.IsEmpty)
            {
                payload = JsonConvert.DeserializeObject <T>(decryptor.Decrypt(message.Pop().ToByteArray()));
            }

            return(new Request <T>(requester, type, payload));
        }
Пример #31
0
 public static Request <object> Read(IDecryptor decryptor, NetMQMessage message)
 {
     return(Read <object>(decryptor, message));
 }
Пример #32
0
 internal static T Decrypt <T>(R.Encrypted encrypted, IDecryptor decryptor)
 {
     return(Decrypt <T>(Encrypted.Parse(encrypted), decryptor));
 }
Пример #33
0
        public static Encryption CreateClientLogin(LoginEncryptionType type, uint seed, uint key1, uint key2)
        {
            IEncryptor encryptor;
            IDecryptor decryptor;

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

                case LoginEncryptionType.Old:
                case LoginEncryptionType.Rare:
                    throw new Exception("Unsupported login encryption.");

                case LoginEncryptionType.New:
                    encryptor = new LoginEncryption(seed, key1, key2);
                    decryptor = new NoEncryption();
                    break;

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

            return new Encryption(encryptor, decryptor);
        }