Пример #1
0
        public void DecryptToStream(IFile file, Stream outputStream)
        {
            if (file == null)
                throw new ArgumentNullException(nameof(file));
            if (outputStream == null)
                throw new ArgumentNullException(nameof(outputStream));

            //Read IV
            int ivSize = _encryptionProvider.BlockSize / 8;
            byte[] iv = new byte[ivSize];
            using (Stream fileData = file.Read())
            {
                fileData.Seek(0, SeekOrigin.Begin);
                fileData.Read(iv, 0, iv.Length);

                //Write decrypted data
                byte[] key = _key.GenerateBlock(_encryptionProvider.BlockSize);
                ICryptoTransform decryptor = _encryptionProvider.CreateDecryptor(key, iv);

                using (var cryptoStream = new CryptoStream(fileData, decryptor, CryptoStreamMode.Read))
                {
                    cryptoStream.CopyTo(outputStream);
                }
            }
        }
        HttpContent IHttpContentEncryptor.Decrypt(HttpContent encryptedContent)
        {
            if (encryptedContent == null)
            {
                throw new ArgumentNullException("encryptedContent");
            }

            var encodedString = encryptedContent.ReadAsStringAsync().Result;

            using (var encryptedData = new MemoryStream(Convert.FromBase64String(encodedString)))
            {
                if (encryptedData.Length == 0)
                {
                    return encryptedContent;
                }

                this.algorithm.Key = this.keyProvider.Key;
                this.algorithm.IV = this.keyProvider.IV;

                using (var decryptor = algorithm.CreateDecryptor())
                {
                    var cryptoStream = new CryptoStream(encryptedData, decryptor, CryptoStreamMode.Read);
                    var originData = new MemoryStream((int)encryptedData.Length);
                    cryptoStream.CopyTo(originData);
                    originData.Flush();
                    originData.Position = 0;

                    var originContent = new StreamContent(originData);
                    originContent.Headers.ContentType = encryptedContent.Headers.ContentType;

                    return originContent;
                }
            }
        }
Пример #3
0
        public static void DecryptAes(Stream inStream, Stream outStream, string password)
        {
            if (inStream == null)
            {
                throw new ArgumentNullException("inStream");
            }
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // generate an encryption key with the shared secret and salt
            using (var key = new Rfc2898DeriveBytes(password, Salt))
            {
                using (var aesAlg = new RijndaelManaged())
                {
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                    using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
                    {
                        using (var csEncrypt = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                        {
                            csEncrypt.CopyTo(outStream);
                        }
                    }
                }
            }
        }
Пример #4
0
        public static void EncryptAndUpload(string file, string awsPath, string key)
        {
            if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                    aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
                    using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
                    {
                        using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
                        {
                            stream.CopyTo(temp);
                        }
                    }

                    UploadFile(file + "_encrypted", awsPath);

                    File.Delete(file + "_encrypted");
                }
            }
            else
                UploadFile(file, awsPath);
        }
Пример #5
0
        public static void TripleDesCreate()
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes("This is a secret message and is a sentence that is longer than a block, it ensures that multi-block functions work.");
            TripleDES tripleDes = TripleDES.Create();

            byte[] encryptedBytes;
            using (MemoryStream input = new MemoryStream(inputBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateEncryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                encryptedBytes = output.ToArray();
            }

            Assert.NotEqual(inputBytes, encryptedBytes);

            byte[] decryptedBytes;
            using (MemoryStream input = new MemoryStream(encryptedBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, tripleDes.CreateDecryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                decryptedBytes = output.ToArray();
            }

            Assert.Equal(inputBytes, decryptedBytes);
        }
Пример #6
0
		public static byte[] TransformEntireBlock(this ICryptoTransform transform, byte[] data)
		{
			using (var input = new MemoryStream(data))
			using (var output = new CryptoStream(input, transform, CryptoStreamMode.Read))
			using (var result = new MemoryStream())
			{
				output.CopyTo(result);
				return result.ToArray();
			}
		}
Пример #7
0
        static void Decrypt(string[] args)
        {
            //Precheck if a tmp file already exists.
            //If so delete it.
            if (File.Exists(args[0] + ".tmp"))
            {
                Display("Destroying old .tmp files.");
                DestroyFile(args[0] + ".tmp");
                Display("Done.");
            }

            //SET UP STREAMS//
            FileStream Output;
            FileStream Input;
            CryptoStream CryptStream;

            //SET UP SERVICE PROVIDERS//
            AesCryptoServiceProvider ACSP = new AesCryptoServiceProvider();

            //AES PARAMETERS//
            ACSP.Padding = PaddingMode.PKCS7;
            Display("Creating keys.");
            ACSP.IV = GenerateIV(args[2]);      //initialization vector
            ACSP.Key = GenerateKey(args[2]);    //32 byte key
            Display("Done.");

            Input = new FileStream(args[0], FileMode.Open);
            Output = new FileStream(args[0] + ".tmp", FileMode.CreateNew);
            CryptStream = new CryptoStream(Input, ACSP.CreateDecryptor(), CryptoStreamMode.Read);

            Display("Starting decryption.");
            CryptStream.CopyTo(Output);
            Display("Done.");
            Input.Flush();
            Input.Dispose();
            CryptStream.Flush();
            //CryptStream.Dispose(); <-- Is disposed with input.
            Output.Flush();
            Output.Dispose();

            Display("Destroying old raw file.");
            DestroyFile(args[0]);
            Display("Done.");

            //Rename .tmp to the original file.
            Display("Renaming new file.");
            File.Move(args[0] + ".tmp", args[0]);
            Display("Done.");

            ACSP.Dispose();

            Display("Decryption process completed.");
            Console.ReadKey();
            return;
        }
Пример #8
0
 public static Byte[] Decrypt(this AesManaged aes, Byte[] source, Byte[] key, Byte[] iv)
 {
     var bytesKey = ResizeBytesArray(key, aes.Key.Length);
     var bytesIv = ResizeBytesArray(iv, aes.IV.Length);
     using (var msIn = new MemoryStream(source))
     using (var cryptStreem = new CryptoStream(msIn, aes.CreateDecryptor(bytesKey, bytesIv), CryptoStreamMode.Read))
     {
         MemoryStream m = new MemoryStream();
         cryptStreem.CopyTo(m);
         return m.ToArray();
     }
 }
Пример #9
0
		public string Decrypt(string name) {
			using (var ms = new MemoryStream(Base64Decode(name))) {
				byte ivId = (byte)ms.ReadByte();
				cipher.IV = GetIV(ivId);

				var result = new MemoryStream();
				using (var stream = new CryptoStream(ms, cipher.CreateDecryptor(), CryptoStreamMode.Read))
					stream.CopyTo(result);

				return Encoding.UTF8.GetString(result.ToArray());
			}
		}
Пример #10
0
		public static Stream ResolveAddonStream (string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read) {
			var stream = File.OpenRead(FindScaledAsset(Path.Combine(_userPath, path)));

			if (_key != null && _iv != null) {
				var ms = new MemoryStream();

				using (var cs = new CryptoStream(stream, _rm.CreateDecryptor(_key, _iv), CryptoStreamMode.Read)) {
					cs.CopyTo(ms);
				}
				ms.Position = 0;
				return ms;
			} else
				return stream;
		}
Пример #11
0
        public static void Decrypt(string source, string key, string destination, string algorithmName)
        {
            using (var algorithm = SymmetricAlgorithm.Create(algorithmName))
            {
                using (var inputStream = new FileStream(key, FileMode.Open, FileAccess.Read))
                using (var streamReader = new StreamReader(inputStream))
                {
                    algorithm.Key = Convert.FromBase64String(streamReader.ReadLine());
                    algorithm.IV = Convert.FromBase64String(streamReader.ReadLine());
                }

                using (var inputStream = new FileStream(source, FileMode.Open, FileAccess.Read))
                using (var cryptoStream = new CryptoStream(inputStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read))
                using (var outputStream = new FileStream(destination, FileMode.Create, FileAccess.Write))
                    cryptoStream.CopyTo(outputStream);
            }
        }
Пример #12
0
        private void MakeDycrypt()
        {

            var autofc = new Autofc();
            _container = autofc.Container;
            var currentAlgorithm = _container.ResolveKeyed<SymmetricAlgorithm>(_algorithm);
            currentAlgorithm.Padding = PaddingMode.None;
            //var currentAlgorithm = new AesCryptoServiceProvider {Padding = PaddingMode.None};
            ReadKey();
            var decryptor = currentAlgorithm.CreateDecryptor(_key, _iv);
            using (var cryptoStream = new CryptoStream(_reader, decryptor, CryptoStreamMode.Read))
            {
                cryptoStream.CopyTo(_writer);
            }
            _reader.Dispose();
            _writer.Dispose();
        }
Пример #13
0
 public static byte[] EncryptData(byte[] data, string key)
 {
     using (var aesAlg = new AesManaged())
     {
         aesAlg.Key = new UTF8Encoding().GetBytes(key);
         ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, new byte[] {0x00});
         using (var msEncrypt = new MemoryStream())
         using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
         {
             using (var memoryStream = new MemoryStream())
             {
                 csEncrypt.CopyTo(memoryStream);
                 return memoryStream.ToArray();
             }
         }
     }
 }
Пример #14
0
        public static void Encrypt(string source, string destination, string algorithmName)
        {
            using (var algorithm = SymmetricAlgorithm.Create(algorithmName))
            {
                using (var inputStream = new FileStream(source, FileMode.Open, FileAccess.Read))
                using (var cryptoStream = new CryptoStream(inputStream, algorithm.CreateEncryptor(), CryptoStreamMode.Read))
                using (var outputStream = new FileStream(destination, FileMode.Create, FileAccess.Write))
                    cryptoStream.CopyTo(outputStream);

                using (var outputStream = new FileStream(String.Format("{0}.key", source), FileMode.Create, FileAccess.Write))
                using (var streamWriter = new StreamWriter(outputStream))
                {
                    streamWriter.WriteLine(Convert.ToBase64String(algorithm.Key));
                    streamWriter.WriteLine(Convert.ToBase64String(algorithm.IV));
                }
            }
        }
Пример #15
0
        public static byte[] DecryptData(byte[] cipherText)
        {
            var decryptor = CurrProvider.CreateDecryptor();

            byte[] plainText;
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        csDecrypt.CopyTo(memoryStream);
                        plainText = memoryStream.ToArray();
                    }
                }
            }
            return plainText;
        }
Пример #16
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (Rijndael rij = Rijndael.Create())
            {

                rij.Padding = PaddingMode.None;
                rij.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                rij.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                using (ICryptoTransform decryptor = rij.CreateDecryptor(rij.Key, rij.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
            }
            }
        }
Пример #17
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Padding = PaddingMode.None;

                aes.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                aes.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
                }

            }
        }
Пример #18
0
 public static void EncryptFile(string input, string output, string key)
 {
     FileStream fsIn = new FileStream(input, FileMode.Open);
     using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
     {
         csp.Padding = PaddingMode.PKCS7;
         csp.Mode = CipherMode.ECB;
         csp.Key = Encoding.ASCII.GetBytes(key);
         csp.IV = csp.Key;
         ICryptoTransform encryptor = csp.CreateEncryptor();
         using (CryptoStream cs = new CryptoStream(fsIn, encryptor, CryptoStreamMode.Read))
         {
             using (FileStream fsOut = new FileStream(output, FileMode.Create))
             {
                 cs.CopyTo(fsOut);
             }
         }
     }
 }
Пример #19
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider())
            {
                rc2.Padding = PaddingMode.None;

                rc2.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                rc2.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                //ICryptoTransform decryptor = aes.CreateDecryptor();
                using (ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key, rc2.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
                }
            }
        }
Пример #20
0
        public void Decrypt(Stream streamIn, Stream streamOut, StreamReader streamKey)
        {
            using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
            {
                des.Padding = PaddingMode.None;
                //tmpiv =
                des.IV = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));
                des.Key = Convert.FromBase64String(streamKey.ReadLine().TrimEnd(new Char[] {' '}));

                //ICryptoTransform decryptor = aes.CreateDecryptor();
                using (ICryptoTransform decryptor = des.CreateDecryptor(des.Key, des.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(streamIn, decryptor, CryptoStreamMode.Read))
                    {
                        cryptoStream.CopyTo(streamOut);
                    }
                }
            }
        }
Пример #21
0
        public byte[] Decrypt(byte[] encrypted,
                              int    workFactor,
                              byte[] salt)
        {
            if (encrypted == null)
            {
                throw new ArgumentNullException("encrypted", "Cannot be null");
            }

            if (workFactor < MIN_VALID_WORK_FACTOR || MAX_VALID_WORK_FACTOR < workFactor)
            {
                throw new ArgumentOutOfRangeException("workFactor",
                                                      workFactor,
                                                      string.Format("workFactor value must be between {0} and {1} inclusive.",
                                                                    MIN_VALID_WORK_FACTOR,
                                                                    MAX_VALID_WORK_FACTOR));
            }

            if (salt == null)
            {
                throw new ArgumentNullException("salt", "Cannot be null");
            }

            using (var encryptedMemoryStream = new MemoryStream(encrypted))
            using (var aes = new AesCryptoServiceProvider())
            {
                InitAesKeyAndIv(aes, workFactor, salt);
                ICryptoTransform decryptor = aes.CreateDecryptor();

                using (var cs = new CryptoStream(encryptedMemoryStream, decryptor, CryptoStreamMode.Read))
                {
                    var unencryptedMemoryStream = new MemoryStream();

                    cs.CopyTo(unencryptedMemoryStream);

                    return unencryptedMemoryStream.ToArray();
                }
            }
        }
        public Stream Decrypt(RSAParameters privateKey, string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new ArgumentException(string.Format("File {0} does not exist", fileName));
            }

            var rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(privateKey);

            var ms = new MemoryStream();

            using (var fs = new FileStream(fileName, FileMode.Open))
            using (var reader = new StreamReader(fs))
            {
                var keyLength = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var keyString = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var ivLength = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var ivString = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);

                var key = rsaProvider.Decrypt(Convert.FromBase64String(keyString), false);
                var iv = rsaProvider.Decrypt(Convert.FromBase64String(ivString), false);

                RijndaelManaged rijndaelManaged = new RijndaelManaged();
                rijndaelManaged.Padding = PaddingMode.Zeros;
                rijndaelManaged.IV = iv;
                rijndaelManaged.Key = key;

                fs.Seek(keyLength.Length + int.Parse(keyLength) + ivLength.Length + int.Parse(ivLength) + 4, SeekOrigin.Begin);
                var crypto = new CryptoStream(fs, rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV), CryptoStreamMode.Read);
                crypto.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                rijndaelManaged.Dispose();
            }

            rsaProvider.Dispose();
            return ms;
        }
Пример #23
0
        public static byte[] Decrypt(string privateKey, byte[] data)
        {
            using (var aes = new AesCryptoServiceProvider())
            {
                var iv = new byte[128];
                var key = new byte[128];

                Buffer.BlockCopy(data, 0, iv, 0, 128);
                Buffer.BlockCopy(data, 128, key, 0, 128);

                using (var encryptor = aes.CreateDecryptor(Rsa.Decrypt(privateKey, key), Rsa.Decrypt(privateKey, iv)))
                using (var src = new MemoryStream(data, writable: false))
                using (var dst = new MemoryStream())
                {
                    src.Seek(256, SeekOrigin.Begin);
                    using (var cs = new CryptoStream(src, encryptor, CryptoStreamMode.Read))
                    {
                        cs.CopyTo(dst);
                    }
                    return dst.ToArray();
                }
            }
        }
Пример #24
0
        public byte[] Decrypt(EncryptedMessage em)
        {
            using (var aes = new AesManaged())
            {
                aes.Key = em.Key;
                aes.IV = em.IV;

                using (var decryptor = aes.CreateDecryptor())
                {
                    using (var msInput = new MemoryStream(em.CipherBytes))
                    {
                        using (var cryptoStream = new CryptoStream(msInput, decryptor, CryptoStreamMode.Read))
                        {
                            using (var msOutput = new MemoryStream())
                            {
                                cryptoStream.CopyTo(msOutput);
                                return msOutput.ToArray();
                            }
                        }
                    }
                }
            }
        }
Пример #25
0
            public static byte[] DecryptData(byte[] data, string key)
            {
                byte[] encKey = Encoding.UTF8.GetBytes(key);

                using (var aesAlg = new AesManaged())
                {
                    aesAlg.Key = encKey;
                    aesAlg.Mode = CipherMode.ECB;
                    aesAlg.Padding = PaddingMode.PKCS7;
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (var msDecrypt = new MemoryStream(data))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var memoryStream = new MemoryStream())
                            {
                                csDecrypt.CopyTo(memoryStream);
                                return memoryStream.ToArray();
                            }
                        }
                    }
                }
            }
Пример #26
0
        internal static PlayerFile ReadPlayer(string path)
        {
            // warning: here be dragons (or worse)!

            BinBuffer bb;

            using (CryptoStream cs = new CryptoStream(new MemoryStream(File.ReadAllBytes(path)),
                new RijndaelManaged().CreateDecryptor(unicodeKey, unicodeKey), CryptoStreamMode.Read))
            {
                // copy the Stream to a BinBufferByte so it can be closed immediately.

                MemoryStream ms = new MemoryStream();
                cs.CopyTo(ms);

                bb = new BinBuffer(new BinBufferByte(ms.ToArray()));

                ms.Close();
                cs.Close();
            }

            PlayerFile ret = new PlayerFile();

            int ver = ret.version = bb.ReadInt();


            ret.name = ReadString(bb);

            if (ver >= 10)
            {
                if (ver >= 17)
                    ret.difficulty = (Difficulty)bb.ReadByte();
                else if (bb.ReadBool())
                    ret.difficulty = Difficulty.Hardcore;
            }

            ret.hair = bb.ReadInt();

            if (ver >= 82)
                ret.hairDye = bb.ReadByte();
            if (ver >= 83)
                ret.hideVisual = bb.ReadByte();

            ret.gender = ver <= 17
                ? (ret.hair == 5 || ret.hair == 6 || ret.hair == 9 || ret.hair == 11
                    ? Gender.Female
                    : Gender.Male)
                : (Gender)bb.ReadByte();

            ret.life = bb.ReadInt();
            ret.lifeMax = Math.Min(bb.ReadInt(), 500);
            ret.life = Math.Min(ret.lifeMax, ret.lifeMax);

            ret.mana = bb.ReadInt();
            ret.manaMax = Math.Min(bb.ReadInt(), 400);
            ret.mana = Math.Min(ret.mana, ret.manaMax);

            ret.hairColour = bb.ReadColorRGB();
            ret.skinColour = bb.ReadColorRGB();
            ret.eyeColour = bb.ReadColorRGB();
            ret.shirtColour = bb.ReadColorRGB();
            ret.undershirtColour = bb.ReadColorRGB();
            ret.pantsColour = bb.ReadColorRGB();
            ret.shoeColour = bb.ReadColorRGB();

            #region inventory
            if (ver < 38)
            {
                // screw this
                throw new FormatException("Player format too old.");
            }

            for (int i = 0; i < (ver >= 81 ? 16 : 11); i++)
                ret.armour[i] = new Item()
                {
                    netID = bb.ReadInt(),
                    stack = 1,
                    prefix = bb.ReadByte()
                };

            if (ver >= 47)
                for (int i = 0; i < (ver >= 81 ? 8 : 3); i++)
                    if (i < 3) // 1.2.2!
                        ret.dye[i] = new Item()
                        {
                            netID = bb.ReadInt(),
                            stack = 1,
                            prefix = bb.ReadByte()
                        };

            for (int i = 0; i < (ver >= 58 ? 58 : 48); i++)
                ret.inventory[i] = new Item()
                {
                    netID = bb.ReadInt(),
                    stack = bb.ReadInt(),
                    prefix = bb.ReadByte()
                };

            ret.inventory[58] = new Item(); // mouse item in tapi

            for (int i = 0; i < (ver >= 58 ? 40 : 20); i++)
                ret.piggyBank[i] = new Item()
                {
                    netID = bb.ReadInt(),
                    stack = bb.ReadInt(),
                    prefix = bb.ReadByte()
                };

            for (int i = 0; i < (ver >= 58 ? 40 : 20); i++)
                ret.safe[i] = new Item()
                {
                    netID = bb.ReadInt(),
                    stack = bb.ReadInt(),
                    prefix = bb.ReadByte()
                };
            #endregion

            // buffs
            if (ver >= 11)
                for (int i = 0; i < (ver >= 74 ? 22 : 10); i++)
                {
                    ret.buffType[i] = bb.ReadInt();
                    ret.buffTime[i] = bb.ReadInt();
                }

            // spawn
            for (int i = 0; i < 200; i++)
            {
                int spX = bb.ReadInt();

                if (spX <= -1)
                    break;

                ret.spX[i] = spX;
                ret.spY[i] = bb.ReadInt();
                ret.spI[i] = bb.ReadInt();
                ret.spN[i] = ReadString(bb);
            }

            if (ver >= 16)
                ret.hbLocked = bb.ReadBool();
            if (ver >= 98)
                ret.anglerQuestsFinished = bb.ReadInt();

            return ret;
        }
Пример #27
0
        public Task Handle(string path, HttpListenerContext context)
        {
            if (!path.StartsWith(_pathPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }

            var resourceNameSuffix = path.Substring(_pathPrefixLength).Replace("/", ".");
            var caseInsensitiveResourceName = _resourceNamePrefix + resourceNameSuffix;

            string resourceName;
            if (_resources.TryGetValue(caseInsensitiveResourceName, out resourceName))
            {
                var ifNoneMatch = context.Request.Headers.Get("If-None-Match");
                if (ifNoneMatch != null)
                {
                    string etag;
                    if (_etags.TryGetValue(resourceName, out etag))
                    {
                        if (etag == ifNoneMatch)
                        {
                            SetNotModified(context);
                            return TaskAsyncHelper.Empty;
                        }
                    }
                }

                var contentType = GetContentType(resourceName);

                using (var stream = _assembly.GetManifestResourceStream(resourceName))
                {
                    if (stream == null)
                    {
                        // should not happen
                        SetNotFound(context);
                    }
                    else
                    {

                        var hashAlgorithm = MD5.Create();
                        var memoryStream = new MemoryStream();
                        var cryptoStream = new CryptoStream(stream, hashAlgorithm, CryptoStreamMode.Read);
                        cryptoStream.CopyTo(memoryStream);
                        var digest = hashAlgorithm.Hash;

                        var sb = new StringBuilder(digest.Length * 2);

                        foreach (byte b in digest)
                        {
                            sb.AppendFormat("{0:x2}", b);
                        }

                        var etag = sb.ToString();
                        _etags[resourceName] = etag;

                        context.Response.SendChunked = false;
                        context.Response.ContentType = contentType;
                        context.Response.ContentLength64 = memoryStream.Length;
                        context.Response.AddHeader("ETag", etag);
                        context.Response.AddHeader("Expires", DateTime.UtcNow.AddMonths(1).ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT");

                        //context.Response.AddHeader("Expires", DateTime.UtcNow.AddMonths(1).ToString("ddd, dd MMM yyyy HH:mm:ss GMT"));
                        //context.Response.AddHeader("ETag", etag);
                        //memoryStream.Seek(0, SeekOrigin.Begin);

                        // note that WriteTo is more efficient than CopyTo
                        // See http://geekswithblogs.net/mknapp/archive/2011/10/23/writing-to-an-httplistenerresponse-output-stream.aspx
                        memoryStream.WriteTo(context.Response.OutputStream);
                        //context.Response.OutputStream.Close();
                    }
                }
            }
            else
            {
                SetNotFound(context);
            }

            return TaskAsyncHelper.Empty;
        }
Пример #28
0
        public string Encrypt(string data)
        {
            try
            {
                List<byte> hexString = new List<byte>(Encoding.Default.GetBytes(data));
                while (hexString.Count % 16 != 0)
                {
                    hexString.Add(0x00);
                }
                _rijndael.Key = _chatKey;

                CryptoStream stream = new CryptoStream(new MemoryStream(hexString.ToArray()), _rijndael.CreateEncryptor(), CryptoStreamMode.Read);
                MemoryStream textBytes = new MemoryStream();
#if NET20 || NET35
                byte[] buffer = new byte[1024];
                int read = stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                textBytes.Write(buffer, 0, read);
#else
                stream.CopyTo(textBytes);
#endif
                return Convert.ToBase64String(textBytes.ToArray());
            }
            catch (CryptographicException e)
            {
                Debug.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }
		private byte[] Decrypt(ISymmetricAlgorithm algo, byte[] ivAndCiphertext)
		{
			// The encrypted payload's first block is the IV, the rest is cipher text.
			byte[] iv, ciphertext;
			DecodeCiphertext(ivAndCiphertext, out iv, out ciphertext);
			algo.IV = iv;

			using (var inputStream = new MemoryStream(ciphertext))
			{
				using (ICryptoTransform decryptor = algo.CreateDecryptor())
				{
					using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
					{
						using (var resultStream = new MemoryStream())
						{
							cryptoStream.CopyTo(resultStream);
							return resultStream.ToArray();
						}
					}
				}
			}
		}
Пример #30
0
        public static void Unpack(string inputFileName, string outputBase, byte[] key, byte[] iv)
        {
            var info = new List<string>();

            if (key.Length != 16)
                throw new ApplicationException("Invalid key length");
            if (iv.Length != 16)
                throw new ApplicationException("Invalid IV length");
            if (!File.Exists(inputFileName))
                throw new ApplicationException("Input file not found");


            info.Add("name " + Path.GetFileName(inputFileName));
            info.Add("key " + BitConverter.ToString(key).Replace("-", ""));
            info.Add("iv " + BitConverter.ToString(iv).Replace("-", ""));

            // decrypt
            var decryptedData = new MemoryStream();
            var aes = new RijndaelManaged();
            aes.Mode = CipherMode.CFB;
            aes.Key = key;
            aes.IV = iv;
            aes.Padding = PaddingMode.None;
            var decryptor = new NoPaddingTransformWrapper(aes.CreateDecryptor());

            using (var inputFile = File.OpenRead(inputFileName))
            {
                info.Add("original.size " + inputFile.Length);
                info.Add("original.sha256 " + HashStream(inputFile));
                using (var cryptoStream = new CryptoStream(inputFile, decryptor, CryptoStreamMode.Read))
                {
                    cryptoStream.CopyTo(decryptedData);
                }
                info.Add("decrypted.size " + decryptedData.Length);
                info.Add("decrypted.sha256 " + HashStream(decryptedData));
            }

            var outputDecryptedName = Path.ChangeExtension(outputBase, "decrypted");
            File.WriteAllBytes(outputDecryptedName, decryptedData.ToArray());

            // First 4 bytes are unknown. The next 2 bytes are the zlib header 789C. After that the raw deflate data follows.
            var header = new byte[6];
            if (decryptedData.Read(header, 0, header.Length) != header.Length)
                throw new IOException("Did not read the full header");
            if (header[4] != 0x78 || header[5] != 0x9C)//zlib header
                throw new ApplicationException("Incorrect key/iv");

            decryptedData.Position = 6;

            // decompress using deflate
            var unpackedData = new MemoryStream();
            int revision;
            using (var deflateStream = new DeflateStream(decryptedData, CompressionMode.Decompress, true))
            {
                deflateStream.CopyTo(unpackedData);
            }
            info.Add("unpacked.size " + unpackedData.Length);
            info.Add("unpacked.sha256 " + HashStream(unpackedData));

            using (var reader = new BinaryReader(unpackedData, Encoding.Unicode, true))
            {
                unpackedData.Position = 0x0C;
                revision = reader.ReadInt32();
                info.Insert(1, "revision " + revision);
            }

            File.WriteAllLines(Path.ChangeExtension(outputBase, revision + ".dcinfo"), info);
            File.WriteAllBytes(Path.ChangeExtension(outputBase, revision + ".unpacked"), unpackedData.ToArray());
            File.Delete(outputDecryptedName);
        }