예제 #1
0
파일: Program.cs 프로젝트: xoposhiy/cvk2012
        static void Main(string[] args)
        {
            Console.WriteLine("loading options...");
            options = LoadOptions("options.csv");
            mmmOptions = LoadOptions("mmm_candidates.csv");
            Console.WriteLine("loading voters...");
            var lines = File.ReadAllLines("voters.csv").Skip(1).Select(line => line.Split(';')).ToList();
            Console.WriteLine("parsing voters...");
            deactivated = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[3].Contains("Deactivated"));
            voters = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[1]); //id+phone => datetime
            Console.WriteLine("voters: {0}", voters.Count);

            Console.WriteLine("decrypting...");
            var decrypted = new Blowfish(File.ReadAllText("key.txt")).decryptString(File.ReadAllText("protocol.csv"));
            File.WriteAllText("decrypted.csv", decrypted);
            Console.WriteLine("filtering...");
            var voteLines = decrypted.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(line => line.Split(';'));
            var votes = voteLines
                .Select(
                parts => new
                    {
                        voter = parts[0] + parts[1],  //id + phone
                        candidates = parts[2].Split(',').ToArray()
                    }).ToList();
            Console.WriteLine("deactivated count: " + deactivated.Count(kv => kv.Value)); // не 0
            Console.WriteLine("Votes by deactivated: " + votes.Count(v => deactivated[v.voter])); //0
            Console.WriteLine("Voters with more than 45 votes: " + votes.Count(v => v.candidates.Count() > 45)); //0
            Console.WriteLine("Voters with duplicated votes: " + votes.Count(v => v.candidates.Distinct().Count() != v.candidates.Count())); //0
            Console.WriteLine("Voters with more than 45 UNIQUE votes: " + votes.Count(v => v.candidates.Distinct().Count() > 45)); //0

            Console.WriteLine("Banned MMMs: " + votes.Count(v => IsMmm(v.voter, v.candidates)));

            var results = votes
                .Where(v => !IsMmm(v.voter, v.candidates) && !deactivated[v.voter])
                .SelectMany(v => v.candidates.Distinct())
                .GroupBy(cand => cand)
                .ToDictionary(g => g.Key, g => g.Count());
            Console.WriteLine("results:");
            foreach (var res in results.OrderByDescending(kv => kv.Value))
            {
                Console.WriteLine(res.Value + "\t" + options[res.Key]);
            }
            Console.WriteLine("Elliminate ALL MMM:");
            Console.WriteLine("Banned ALL MMMs: " + votes.Count(v => IsMmmAll(v.voter, v.candidates)));
            Console.WriteLine("results:");
            var results2 = votes
                .Where(v => !IsMmmAll(v.voter, v.candidates) && !deactivated[v.voter])
                .SelectMany(v => v.candidates.Distinct())
                .GroupBy(cand => cand)
                .ToDictionary(g => g.Key, g => g.Count());
            foreach (var res in results2.OrderByDescending(kv => kv.Value))
            {
                Console.WriteLine(res.Value + "\t" + options[res.Key]);
            }
        }
        private void encryptFile()
        {
            FileStream originalStream = File.OpenRead(path + filename); //Change to your file name
            Blowfish   alg            = new Blowfish(Encoding.Unicode.GetBytes(myKey));

            m_originalLength = originalStream.Length;
            Byte[] buffer = new byte[originalStream.Length + (8 - (originalStream.Length % 8))];
            originalStream.Read(buffer, 0, buffer.Length);
            originalStream.Close();
            alg.Encipher(buffer, buffer.Length);
            FileStream stream = new FileStream(path + "Enc_" + filename, FileMode.Create);

            stream.Write(buffer, 0, buffer.Length);
            stream.Close();
            File.Delete(path + filename);
        }
예제 #3
0
    public string EnCrypt(string sStringToEncrypt)
    {
        //the "EncryptionKey" in the web.config is an encrypted version of the actual user-defined key
        //EncryptionKey is encrypted using our hardcoded, proprietary key.

        string sKey = Blowfish.DecryptFromBase64(BLOWFISH_KEY, DatabaseSettings.EnvironmentKey);

        if (!string.IsNullOrEmpty(sKey) && !string.IsNullOrEmpty(sStringToEncrypt))
        {
            return(EnCryptUsingKey(sKey, sStringToEncrypt));
        }
        else
        {
            return("");
        }
    }
예제 #4
0
파일: MixFile.cs 프로젝트: zidonuke/OpenRA
        static MemoryStream Decrypt(uint[] h, Blowfish fish)
        {
            var decrypted = fish.Decrypt(h);

            var ms     = new MemoryStream();
            var writer = new BinaryWriter(ms);

            foreach (var t in decrypted)
            {
                writer.Write(t);
            }
            writer.Flush();

            ms.Seek(0, SeekOrigin.Begin);
            return(ms);
        }
예제 #5
0
파일: DLC.cs 프로젝트: MarkH221/MH4U_Cipher
        /// <summary>
        /// Decrypt a buffer containing MH4U DLC
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns>Decrypted DLC</returns>
        public byte[] Decrypt(byte[] buffer)
        {
            _cipher = new Blowfish(Key);
            var b = new byte[8];

            //var hash = new byte[20];
            using (var m = new MemoryStream(buffer, true))
            {
                while (m.Position < m.Length - 4) //0x1c //4 //28=24+4
                {
                    //Endian swap 2 sets of 4 bytes
                    for (int i = 3; i >= 0; i--)
                    {
                        b[i] = (byte)m.ReadByte();
                    }
                    for (int i = 7; i >= 4; i--)
                    {
                        b[i] = (byte)m.ReadByte();
                    }
                    //Decrypt the 8 bytes
                    _cipher.Decipher(b, 8);
                    //Reset stream position to prepare for writing.
                    m.Position -= 8;
                    //Endian swap 4 bytes twice
                    for (int i = 3; i >= 0; i--)
                    {
                        m.WriteByte(b[i]);
                    }
                    for (int i = 7; i >= 4; i--)
                    {
                        m.WriteByte(b[i]);
                    }
                }
                //m.Position -= 24;
                ////capture sh1 hash
                //m.Read(hash, 0, 20);
                //var sh1 = System.Security.Cryptography.SHA1.Create(); sh1.ComputeHash(buffer, 0, buffer.Length - 28);
                //if (!sh1.Hash.SequenceEqual(hash))
                //{
                //    MessageBox.Show("Invalid SHA1 hash in footer.");
                //    return;
                //}
            }

            //Trim the hash (24) and other useless data (4) by cloning into a new array.
            return(StripJunk(buffer));
        }
예제 #6
0
        private byte[] FindKey(BinReader reader, TellTaleFileStructureInfo fileInfo, IEnumerable <TellTaleKeyInfo> keys)
        {
            const int decompressSize = 4;
            const int readSize       = 4096;

            byte[] readBytes    = new byte[readSize];
            byte[] testBytes    = new byte[readSize];
            byte[] deflateBytes = new byte[decompressSize];
            reader.Position = fileInfo.VirtualBlocksOffset;
            reader.Read(readBytes, 0, readSize);

            using (MemoryStream stream = new MemoryStream(testBytes))
            {
                foreach (var info in keys)
                {
                    var testBlowfish = new Blowfish(info.Key, true);
                    testBlowfish.Decipher(readBytes, testBytes, readSize);

                    stream.Position = 0;
                    using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress, true))
                    {
                        try
                        {
                            int bytesRead = 0;
                            // FIXME: Sometimes DeflateStream.Read reads 0 bytes...
                            while (bytesRead == 0)
                            {
                                bytesRead = deflateStream.Read(deflateBytes, 0, decompressSize);
                            }
                        }
                        catch (InvalidDataException)
                        {
                            // Since a wrong key may cause invalid zlib input,
                            // we catch the exception for that, and continue to the next key
                            continue;
                        }
                    }
                    if (deflateBytes[0] == '3' && deflateBytes[1] == 'A' && deflateBytes[2] == 'T' &&
                        deflateBytes[3] == 'T')
                    {
                        return(info.Key);
                    }
                }
            }
            return(null);
        }
예제 #7
0
        public static void LayCauHinh()
        {
            byte[]       key      = Blowfish.GetBytes("ThinhPhat@JSC@123").Clone() as byte[];
            Blowfish     blowfish = new Blowfish(key);
            StringReader reader   = new StringReader(blowfish.ReadFromFile(Application.StartupPath + @"\Config.tps"));
            DataSet      ds       = new DataSet();

            ds.ReadXml(reader);
            if (ds.Tables[0].Rows.Count < 1)
            {
                throw new Exception("File cấu hình không có kết nối nào");
            }
            _dbname   = Convert.ToString(ds.Tables["KetNoi"].Rows[0]["DBName"]);
            _server   = Convert.ToString(ds.Tables["KetNoi"].Rows[0]["ServerName"]);
            _username = Convert.ToString(ds.Tables["KetNoi"].Rows[0]["UserName"]);
            _pass     = Convert.ToString(ds.Tables["KetNoi"].Rows[0]["Password"]);
            //ConnectDb.Connect(xml.db_server, xml.db_name, xml.db_username, xml.db_password);
        }
예제 #8
0
        public static bool Decrypt(byte[] data, int offset, int length, ClientCryptData cryptData)
        {
            if (length % 8 != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "The lenght must be a multiple of 8!");
            }

            var uintData = new uint[length / 4];

            Buffer.BlockCopy(data, offset, uintData, 0, length);

            var x = SwitchEndianInt(BitConverter.ToUInt32(cryptData.MD5, 0));
            var y = SwitchEndianInt(BitConverter.ToUInt32(cryptData.MD5, 4));

            for (var i = 0; i < (length / 8); ++i)
            {
                //Switch endian first
                var a2 = i * 2;

                uintData[a2]     = SwitchEndianInt(uintData[a2]);
                uintData[a2 + 1] = SwitchEndianInt(uintData[a2 + 1]);

                //Store new XOR
                var x2 = uintData[a2];
                var y2 = uintData[a2 + 1];

                Blowfish.Decrypt(uintData, a2, cryptData.Key);

                uintData[a2]     ^= x;
                uintData[a2 + 1] ^= y;

                //Update XOR
                x = x2;
                y = y2;

                //Switch endian now
                uintData[a2]     = SwitchEndianInt(uintData[a2]);
                uintData[a2 + 1] = SwitchEndianInt(uintData[a2 + 1]);
            }

            Buffer.BlockCopy(uintData, 0, data, offset, length);

            return(true);
        }
예제 #9
0
        static int GetVersionFromSvt(byte[] svtContents)
        {
            byte[]   bfKey = ASCIIEncoding.ASCII.GetBytes("SILKROAD");
            Blowfish bf    = new Blowfish();

            bf.Initialize(bfKey);

            byte[] toDecode = new byte[8];
            Buffer.BlockCopy(svtContents, 4, toDecode, 0, 8);

            byte[] decoded = bf.Decode(toDecode);
            string verStr  = ASCIIEncoding.ASCII.GetString(decoded);

            int firstZeroTermAt = verStr.IndexOf('\0');

            verStr = verStr.Remove(firstZeroTermAt, verStr.Length - firstZeroTermAt);
            byte[] verStrBytes = ASCIIEncoding.ASCII.GetBytes(verStr);
            return(int.Parse(verStr));
        }
예제 #10
0
파일: ArcINT.cs 프로젝트: ziyuejun/GARbro
        private ArcFile OpenEncrypted(ArcView file, int entry_count, uint main_key)
        {
            if (1 == entry_count)
            {
                return(null); // empty archive
            }
            long current_offset = 8;

            uint seed    = file.View.ReadUInt32(current_offset + 0x44);
            var  twister = new MersenneTwister(seed);

            byte[] blowfish_key = BitConverter.GetBytes(twister.Rand());
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(blowfish_key);
            }

            var blowfish = new Blowfish(blowfish_key);
            var dir      = new List <Entry> (entry_count - 1);

            byte[] name_buffer = new byte[0x40];
            for (int i = 1; i < entry_count; ++i)
            {
                current_offset += 0x48;
                file.View.Read(current_offset, name_buffer, 0, 0x40);
                uint offset = file.View.ReadUInt32(current_offset + 0x40) + (uint)i;
                uint size   = file.View.ReadUInt32(current_offset + 0x44);
                blowfish.Decipher(ref offset, ref size);
                twister.SRand(main_key + (uint)i);
                uint   name_key = twister.Rand();
                string name     = DecipherName(name_buffer, name_key);

                var entry = FormatCatalog.Instance.Create <Entry> (name);
                entry.Offset = offset;
                entry.Size   = size;
                if (!entry.CheckPlacement(file.MaxOffset))
                {
                    return(null);
                }
                dir.Add(entry);
            }
            return(new FrontwingArchive(file, this, dir, blowfish));
        }
예제 #11
0
        private IndexEntry[] ReadHeader(Stream stream, out int body_offset)
        {
            BinaryReader reader = new BinaryReader(stream);
            uint         flags  = (this.version == MixFileVersion.CNC) ? 0 : reader.ReadUInt32();
            int          nfiles = 0;

            IndexEntry[] index;

            // The mix is encrypted.
            if ((flags & FlagEncrypted) != 0)
            {
                // Read the Mix key and convert it to a Blowfish key.
                byte[]   key_source = reader.ReadBytes(80);
                byte[]   key        = new BlowfishKeyProvider().DecryptKey(key_source);
                Blowfish bf         = new Blowfish(key);

                // Parse the header.
                byte[] header_buf = stream.ReadBytes(8);
                bf.Decipher(header_buf, 8);
                this.ParseHeader(header_buf, out nfiles);

                // Parse the index.
                int    index_size = (12 * nfiles + 5) & ~7;
                byte[] index_buf  = stream.ReadBytes(index_size);
                bf.Decipher(index_buf, index_size);
                Array.Copy(index_buf, 0, index_buf, 2, index_size - 2);
                Array.Copy(header_buf, 6, index_buf, 0, 2);
                this.ParseIndex(index_buf, nfiles, out index);
            }
            else
            {
                byte[] header_buf = new byte[6];
                stream.Read(header_buf, 0, 6);
                this.ParseHeader(header_buf, out nfiles);

                byte[] index_buf = new byte[12 * nfiles];
                stream.Read(index_buf, 0, 12 * nfiles);
                this.ParseIndex(index_buf, nfiles, out index);
            }

            body_offset = (int)stream.Position;
            return(index);
        }
예제 #12
0
        internal static byte[] Cipher(byte[] buffer, ref byte[] key, bool decrypt)
        {
            var cipher = new Blowfish(key);
            var b      = new byte[8];

            using (var m = new MemoryStream(buffer, true))
            {
                while (m.Position < m.Length)
                {
                    //Endian swap 2 sets of 4 bytes
                    for (int i = 3; i >= 0; i--)
                    {
                        b[i] = (byte)m.ReadByte();
                    }
                    for (int i = 7; i >= 4; i--)
                    {
                        b[i] = (byte)m.ReadByte();
                    }
                    //cipher the 8 bytes
                    if (decrypt)
                    {
                        cipher.Decipher(b, 8);
                    }
                    else
                    {
                        cipher.Encipher(b, 8);
                    }
                    //Reset stream position to prepare for writing.
                    m.Position -= 8;
                    //Endian swap 4 bytes twice
                    for (int i = 3; i >= 0; i--)
                    {
                        m.WriteByte(b[i]);
                    }
                    for (int i = 7; i >= 4; i--)
                    {
                        m.WriteByte(b[i]);
                    }
                }
            }
            return(buffer);
        }
예제 #13
0
        private MemoryStream DecryptHeader(long offset, out long headerEnd)
        {
            rawStream.Seek(offset, SeekOrigin.Begin);

            // Decrypt blowfish key
            var keyblock    = rawStream.ReadBytes(80);
            var blowfishKey = new BlowfishKeyProvider().DecryptKey(keyblock);
            var fish        = new Blowfish(blowfishKey);

            // Decrypt first block to work out the header length
            var ms       = new BinaryReader(Decrypt(ReadBlocks(offset + 80, 1), fish));
            var numFiles = ms.ReadUInt16();

            // Decrypt the full header - round bytes up to a full block
            var blockCount = (13 + numFiles * 12) / 8;

            headerEnd = offset + 80 + blockCount * 8;

            return(Decrypt(ReadBlocks(offset + 80, blockCount), fish));
        }
예제 #14
0
        static MemoryStream DecryptHeader(Stream s, long offset, out long headerEnd)
        {
            s.Seek(offset, SeekOrigin.Begin);

            // Decrypt blowfish key
            var keyblock    = s.ReadBytes(80);
            var blowfishKey = new BlowfishKeyProvider().DecryptKey(keyblock);
            var fish        = new Blowfish(blowfishKey);

            // Decrypt first block to work out the header length
            var ms       = Decrypt(ReadBlocks(s, offset + 80, 1), fish);
            var numFiles = ms.ReadUInt16();

            // Decrypt the full header - round bytes up to a full block
            var blockCount = (13 + numFiles * PackageEntry.Size) / 8;

            headerEnd = offset + 80 + blockCount * 8;

            return(Decrypt(ReadBlocks(s, offset + 80, blockCount), fish));
        }
예제 #15
0
        MemoryStream DecryptHeader(VirtualFile reader)
        {
            byte[] keyblock    = reader.Read(80);
            byte[] blowfishKey = new BlowfishKeyProvider().DecryptKey(keyblock);

            // Decrypt just the 1st block to determine the number of items, and thereby the length of the header
            var fish = new Blowfish(blowfishKey);

            uint[] h = fish.Decrypt(ReadUints(reader, 2));

            // First 2 decrypted bytes indicate number of files defined in header
            ushort numFiles = (ushort)(h[0] & 0xFFFF);
            // now we can determine the actual header length, rounded up to full number of blocks
            const int blockSize    = 8;
            int       headerLength = (6 + numFiles * MixEntry.Size + (blockSize - 1)) & ~(blockSize - 1);

            // Decrypt full header
            reader.Position = 84;
            return(Decrypt(ReadUints(reader, headerLength / 4), fish));
        }
예제 #16
0
파일: ArcINT.cs 프로젝트: tenyuhuang/GARbro
        /// <summary>
        /// Parse certain executable resources for encryption passphrase.
        /// Returns null if no passphrase found.
        /// </summary>
        public static string GetPassFromExe(string filename)
        {
            var exe = NativeMethods.LoadLibraryEx(filename, IntPtr.Zero, 0x20);  // LOAD_LIBRARY_AS_IMAGE_RESOURCE

            if (IntPtr.Zero == exe)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            try
            {
                var code = GetResource(exe, "DATA", "V_CODE2");
                if (null == code || code.Length < 8)
                {
                    return(null);
                }
                var key = GetResource(exe, "KEY", "KEY_CODE");
                if (null != key)
                {
                    for (int i = 0; i < key.Length; ++i)
                    {
                        key[i] ^= 0xCD;
                    }
                }
                else
                {
                    key = Encoding.ASCII.GetBytes("windmill");
                }
                var blowfish = new Blowfish(key);
                blowfish.Decipher(code, code.Length / 8 * 8);
                int length = Array.IndexOf <byte> (code, 0);
                if (-1 == length)
                {
                    length = code.Length;
                }
                return(Encodings.cp932.GetString(code, 0, length));
            }
            finally
            {
                NativeMethods.FreeLibrary(exe);
            }
        }
예제 #17
0
        public byte[] Encrypt(byte[] buffer)
        {
            _cipher = new Blowfish(_key);
            var checksum = BitConverter.GetBytes(CalcChecksum(buffer));
            var buff     = new byte[buffer.Length + 4];

            checksum.CopyTo(buff, 0);
            buffer.CopyTo(buff, 4);
            //Why we actually bother to randomise this is beyond me, might as well be 0, oh well.
            var seed = (ushort)((new Random()).Next() >> 16);

            //XOR!
            buffer = XOR(buff, seed);
            //Write seed
            buff = new byte[buffer.Length + 4];
            (BitConverter.GetBytes((seed << 16) + 0x10)).CopyTo(buff, 0);
            buffer.CopyTo(buff, 4);
            //Encrypt
            buffer = Functions.Cipher(buff, ref _key, false);
            return(buffer);
        }
예제 #18
0
        public static PacketResult Process(BinaryReader reader, Blowfish blowfish, out SubPacket subPacket)
        {
            subPacket = null;
            Header header = Header.UnMarshal(reader);

            // not enough data to cover length specified in header
            if (reader.BaseStream.Length - reader.BaseStream.Position < header.Size - Header.Length)
            {
                return(PacketResult.Malformed);
            }

            byte[] payload = reader.ReadBytes((int)(header.Size - Header.Length));

            if (header.Type != SubPacketType.KeepAliveRequest && header.Type != SubPacketType.KeepAliveResponse)
            {
                blowfish?.Decipher(payload, 0, payload.Length);
            }

            using (var stream = new MemoryStream(payload))
            {
                using (var subReader = new BinaryReader(stream))
                {
                    MessageHeader messageHeader = new MessageHeader();
                    if (header.Type == SubPacketType.Message)
                    {
                        messageHeader = MessageHeader.UnMarshal(subReader);

                        Array.Copy(payload, MessageHeader.Length, payload, 0, payload.Length - MessageHeader.Length);
                        Array.Resize(ref payload, payload.Length - (int)MessageHeader.Length);
                        stream.Position = 0L;
                    }

                    subPacket = PacketManager.GetSubPacket(header.Type, (SubPacketClientOpcode)messageHeader.Opcode, SubPacketServerOpcode.None) ?? new SubPacket();
                    subPacket.Initialise(header, messageHeader);
                    subPacket.Read(subReader);
                }
            }

            return(PacketResult.Ok);
        }
예제 #19
0
        static void Main(string[] args)
        {
            int    exit = 1;
            string value;
            string key = "{123ABC9F-AFBC-36DC-8FF8-00BDAFF1584DGFQQ}";
            string encrypted;
            string decipher;

            do
            {
                Console.Clear();
                Console.WriteLine("Input value:    ");
                value = Convert.ToString(Console.ReadLine());
                Blowfish blowfish = new Blowfish(key);
                encrypted = blowfish.Encipher(value);
                Console.WriteLine("Encrypted value:     " + encrypted);
                decipher = blowfish.Decipher(encrypted);
                Console.WriteLine("Decipher value:     " + decipher);
                Console.WriteLine("Input 0 to exit:    ");
                exit = Convert.ToInt32(Console.ReadLine());
            }while (exit != 0);
        }
예제 #20
0
        private static byte[] DetermineKeyByInfoTable(BinReader reader, TellTaleFileStructureInfo fileInfo, IEnumerable <TellTaleKeyInfo> keys)
        {
            byte[] encryptedTable = fileInfo.ReadInfoBlock(reader, null);
            byte[] decryptedTable = new byte[encryptedTable.Length];

            foreach (var info in keys)
            {
                var blowfish = new Blowfish(info.Key, fileInfo.FileVersion >= 7);
                blowfish.Decipher(encryptedTable, decryptedTable, (uint)(encryptedTable.Length / 8) * 8);

                // Now we do our assertions which should be true if the key was right:
                using (MemoryStream infoStream = new MemoryStream(decryptedTable))
                {
                    using (var infoReader = new BinReader(infoStream))
                    {
                        uint folderCount = infoReader.ReadU32LE();
                        // The maximum number of folders is somewhat arbitrary.
                        // In games tested, I haven't seen folder counts this high.
                        if (folderCount > 128)
                        {
                            Trace.TraceInformation("Key check - folder count: {0}", folderCount);
                            continue;
                        }

                        // We just check the first folder:
                        uint nameSize = infoReader.ReadU32LE();
                        if (nameSize > 300)
                        {
                            Trace.TraceInformation("Key check - folder name size: {0}", nameSize);
                            continue;
                        }

                        return(info.Key);
                    }
                }
            }

            return(null);
        }
예제 #21
0
        public static string Decrypt3(string cipherText, string encryptionKey1, string encryptionKey2, out Exception exData)
        {
            exData = null;
            try
            {
                var mainKey = encryptionKey1 + encryptionKey2;

                var blowFish = new Blowfish(mainKey);

                return(blowFish.Decipher(cipherText));
            }
            catch (Exception ex)
            {
                if (InnerExceptionList == null)
                {
                    InnerExceptionList = new List <Exception>();
                }

                InnerExceptionList.Add(ex);
                exData = ex;
                return("NULL");
            }
        }
예제 #22
0
        public byte[] Build(Blowfish blowfish, uint source, uint target)
        {
            SubPacketAttribute attribute = (SubPacketAttribute)Attribute.GetCustomAttribute(GetType(), typeof(SubPacketAttribute));

            byte[] payload;
            using (var stream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(stream))
                    Write(writer);

                payload = stream.ToArray();
            }

            if (attribute.ServerOpcode != SubPacketServerOpcode.None)
            {
                SubMessageHeader = new MessageHeader
                {
                    Unknown1  = 0x14,
                    Opcode    = (ushort)attribute.ServerOpcode,
                    Timestamp = (uint)DateTimeOffset.Now.ToUnixTimeSeconds()
                };

                payload = SubMessageHeader.Marshal().Concat(payload).ToArray();
            }

            blowfish?.Encipher(payload, 0, payload.Length);

            SubHeader = new Header
            {
                Size   = (ushort)(Header.Length + payload.Length),
                Type   = attribute.ServerOpcode != SubPacketServerOpcode.None ? SubPacketType.Message : attribute.Type,
                Source = source,
                Target = target
            };

            return(SubHeader.Marshal().Concat(payload).ToArray());
        }
예제 #23
0
        public void EncryptDecryptArray()
        {
            #region init
            int     dataLength        = 13107200;
            ulong[] dataArray         = new ulong[dataLength];
            ulong[] originalDataArray = new ulong[dataLength];
            int     keyLength         = 56;
            byte[]  key = new byte[keyLength];

            Random rnd = new Random();
            rnd.NextBytes(key);
            for (var i = 0; i < dataLength; i++)
            {
                uint  r = (uint)rnd.Next();
                ulong l = (uint)rnd.Next();
                dataArray[i]         = (l << 32) | r;
                originalDataArray[i] = dataArray[i];
            }
            #endregion

            Blowfish blowfish = new Blowfish(key);

            blowfish.EncryptArray(dataArray);

            for (var i = 0; i < dataLength; i++)
            {
                Assert.IsFalse(dataArray[i] == originalDataArray[i]);
            }

            blowfish.DecryptArray(dataArray);

            for (var i = 0; i < dataLength; i++)
            {
                Assert.IsTrue(dataArray[i] == originalDataArray[i]);
            }
        }
예제 #24
0
        public void DecryptString()
        {
            Blowfish blowfish = new Blowfish(salt);

            Assert.AreEqual(blowfish.Decipher(encrypted), value);
        }
예제 #25
0
 public static void BlowfishTest()
 {
     Console.WriteLine("Enter text: ");
     string text = Console.ReadLine();
     Blowfish b = new Blowfish();
     string encr = b.Encrypt(text);
     Console.WriteLine("Encrypted text " + encr);
     Console.WriteLine("Decrypted text " + b.Decrypt(encr));
     Console.ReadKey();
 }
예제 #26
0
        /// <summary>
        /// bcrypt_pbkdf (pkcs #5 pbkdf2 implementation using the "bcrypt" hash)
        /// </summary>
        /// <param name="pass">password</param>
        /// <param name="salt">salt</param>
        /// <param name="rounds">rounds</param>
        /// <param name="keylen">key length</param>
        /// <returns>key</returns>
        public byte[] BcryptPbkdf(string pass, byte[] salt, uint rounds, int keylen)
        {
            // this code is based on OpenBSD's bcrypt_pbkdf.c

            if (rounds < 1) {
                return null;
            }
            if (pass.Length == 0 || salt.Length == 0 || keylen <= 0 || keylen > 1024) {
                return null;
            }

            byte[] key = new byte[keylen];

            int stride = (keylen + 32 - 1) / 32;
            int amt = (keylen + stride - 1) / stride;

            var blowfish = new Blowfish();
            using (var sha512 = new SHA512CryptoServiceProvider()) {

                // collapse password
                byte[] passData = Encoding.UTF8.GetBytes(pass);
                byte[] sha2pass = sha512.ComputeHash(passData);

                // generate key, sizeof(out) at a time
                byte[] countsalt = new byte[4];
                for (int count = 1; keylen > 0; ++count) {
                    countsalt[0] = (byte)(count >> 24);
                    countsalt[1] = (byte)(count >> 16);
                    countsalt[2] = (byte)(count >> 8);
                    countsalt[3] = (byte)(count);

                    // first round, salt is salt
                    sha512.Initialize();
                    sha512.TransformBlock(salt, 0, salt.Length, null, 0);
                    sha512.TransformFinalBlock(countsalt, 0, countsalt.Length);
                    byte[] sha2salt = sha512.Hash;
                    byte[] tmpout = BcryptHash(blowfish, sha2pass, sha2salt);
                    byte[] output = (byte[])tmpout.Clone();

                    for (uint r = rounds; r > 1; --r) {
                        // subsequent rounds, salt is previous output
                        sha512.Initialize();
                        sha2salt = sha512.ComputeHash(tmpout);
                        tmpout = BcryptHash(blowfish, sha2pass, sha2salt);
                        for (int i = 0; i < output.Length; ++i) {
                            output[i] ^= tmpout[i];
                        }
                    }

                    // pbkdf2 deviation: output the key material non-linearly.
                    amt = Math.Min(amt, keylen);
                    int k;
                    for (k = 0; k < amt; ++k) {
                        int dest = k * stride + (count - 1);
                        if (dest >= key.Length) {
                            break;
                        }
                        key[dest] = output[k];
                    }
                    keylen -= k;
                }
            }

            return key;
        }
예제 #27
0
        public void EncryptString()
        {
            Blowfish blowfish = new Blowfish(salt);

            Assert.AreEqual(blowfish.Encipher(value), encrypted);
        }
예제 #28
0
파일: ArcINT.cs 프로젝트: ziyuejun/GARbro
 public FrontwingArchive(ArcView arc, ArchiveFormat impl, ICollection <Entry> dir, Blowfish cipher)
     : base(arc, impl, dir)
 {
     Encryption = cipher;
 }
예제 #29
0
    static void TestBlowfish()
    {
        if (!Blowfish.SelfTest())
        {
            System.Console.WriteLine("selftest failed.");
            return;
        }

        System.Console.WriteLine("selftest passed.");

        byte[] key = new byte[16];

        for (byte bI = 0; bI < key.Length; bI++)
        {
            key[bI] = bI;
        }

        Blowfish bf = new Blowfish(key);

        System.Console.WriteLine((bf.IsWeakKey) ? "weak key detected." :
                                 "no weak key.");

        String sTest = "this is something to encrypt";

        System.Console.WriteLine(sTest);

        byte[] plainText = StringToBlocks(sTest);

        byte[] cipherText = new byte[plainText.Length];

        bf.Encrypt(plainText, cipherText, 0, 0, plainText.Length);

        System.Console.WriteLine(BlocksToString(cipherText));

        bf.Decrypt(cipherText, cipherText, 0, 0, cipherText.Length);

        System.Console.WriteLine(BlocksToString(cipherText));

        int nI, nSize = Blowfish.BLOCKSIZE * BIGBUFDIM;

        byte[] bigBuf = new byte[nSize];
        for (nI = 0; nI < nSize; nI++)
        {
            bigBuf[nI] = (byte)nI;
        }

        System.Console.WriteLine("benchmark running ...");

        long lTm = DateTime.Now.Ticks;

        for (nI = 0; nI < TESTLOOPS; nI++)
        {
            bf.Encrypt(bigBuf, bigBuf, 0, 0, nSize);

            if ((nI & 0x0f) == 0)
            {
                System.Console.Write(".");
            }
        }

        lTm = DateTime.Now.Ticks - lTm;

        lTm /= 10000;

        System.Console.WriteLine("\n{0} bytes in {1} millisecs",
                                 TESTLOOPS * nSize,
                                 lTm);

        long lSize = (long)nSize * 1000 * TESTLOOPS;

        lSize /= lTm;

        System.Console.WriteLine("(average of {0} bytes per second)", lSize);

        bf.Burn();
    }
예제 #30
0
        /// <summary>
        /// bcrypt_hash
        /// </summary>
        /// <param name="blowfish">blowfish object to use</param>
        /// <param name="sha2pass">SHA512 of password</param>
        /// <param name="sha2salt">SHA512 of salt</param>
        /// <returns></returns>
        private byte[] BcryptHash(Blowfish blowfish, byte[] sha2pass, byte[] sha2salt)
        {
            // this code is based on OpenBSD's bcrypt_pbkdf.c
            const int BLOCKSIZE = 8;

            // key expansion
            blowfish.InitializeState();
            blowfish.ExpandState(sha2pass, sha2salt);
            for (int i = 0; i < 64; ++i) {
                blowfish.ExpandState(sha2salt);
                blowfish.ExpandState(sha2pass);
            }

            // encryption
            byte[] cdata = (byte[])_bcryptCipherText.Clone();
            for (int i = 0; i < 64; ++i) {
                for (int j = 0; j < 32; j += BLOCKSIZE) {
                    blowfish.BlockEncrypt(cdata, j, cdata, j);
                }
            }

            // copy out
            for (int i = 0; i < 32; i += 4) {
                byte b0 = cdata[i + 0];
                byte b1 = cdata[i + 1];
                byte b2 = cdata[i + 2];
                byte b3 = cdata[i + 3];
                cdata[i + 3] = b0;
                cdata[i + 2] = b1;
                cdata[i + 1] = b2;
                cdata[i + 0] = b3;
            }

            return cdata;
        }
예제 #31
0
    public static Ticket EncryptAuthSessionTicket(byte[] ticket, uint time)
    {
        time -= 5;
        time -= time % 60; // Time should be rounded to nearest minute.

        var ticketString   = BitConverter.ToString(ticket).Replace("-", "").ToLower();
        var rawTicketBytes = Encoding.ASCII.GetBytes(ticketString);

        var rawTicket = new byte[rawTicketBytes.Length + 1];

        Array.Copy(rawTicketBytes, rawTicket, rawTicketBytes.Length);
        rawTicket[rawTicket.Length - 1] = 0;

        Log.Debug(Util.ByteArrayToHex(rawTicket));

        var blowfishKey = $"{time:x08}#un@e=x>";

        using var memorySteam  = new MemoryStream();
        using var binaryWriter = new BinaryWriter(memorySteam);

        /* REGULAR SUM + TICKET */
        ushort ticketSum = 0;

        foreach (byte b in rawTicket)
        {
            ticketSum += b;
        }

        binaryWriter.Write(ticketSum);
        binaryWriter.Write(rawTicket);

        /* GARBAGE */
        int castTicketSum = unchecked ((short)ticketSum);

        Log.Information($"{castTicketSum:X}");
        var seed = time ^ castTicketSum;
        var rand = new CrtRand((uint)seed);

        var numRandomBytes = ((ulong)(rawTicket.Length + 9) & 0xFFFFFFFFFFFFFFF8) - 2 - (ulong)rawTicket.Length;
        var garbage        = new byte[numRandomBytes];

        uint fuckedSum = BitConverter.ToUInt32(memorySteam.ToArray(), 0);

        for (var i = 0u; i < numRandomBytes; i++)
        {
            var randChar = FUCKED_GARBAGE_ALPHABET[(int)(fuckedSum + rand.Next()) & 0x3F];
            garbage[i] = (byte)randChar;
            fuckedSum += randChar;
        }

        binaryWriter.Write(garbage);

        memorySteam.Seek(0, SeekOrigin.Begin);
        binaryWriter.Write(fuckedSum);

        Log.Information("[STEAM] time: {Time}, bfKey: {FishKey}, rawTicket.Length: {TicketLen}, ticketSum: {TicketSum}, fuckedSum: {FuckedSum}, seed: {Seed}, numRandomBytes: {NumRandomBytes}", time,
                        blowfishKey, rawTicket.Length, ticketSum, fuckedSum, seed, numRandomBytes);

        /* ENC + SPLIT */
        var finalBytes = memorySteam.ToArray();

        var t = finalBytes[0];

        finalBytes[0] = finalBytes[1];
        finalBytes[1] = t;

        var keyBytes = Encoding.ASCII.GetBytes(blowfishKey);

        Log.Debug(Util.ByteArrayToHex(keyBytes));

        var blowfish = new Blowfish(keyBytes);
        var ecb      = new Ecb <Blowfish>(blowfish);

        Log.Debug(Util.ByteArrayToHex(finalBytes));

        var encBytes = new byte[finalBytes.Length];

        Debug.Assert(encBytes.Length % 8 == 0);

        ecb.Encrypt(finalBytes, encBytes);
        var encString = Util.ToMangledSeBase64(encBytes);

        Log.Debug(Util.ByteArrayToHex(encBytes));

        const int SPLIT_SIZE = 300;
        var       parts      = ChunksUpto(encString, SPLIT_SIZE).ToArray();

        var finalString = string.Join(",", parts);

        return(new Ticket(finalString, finalString.Length - (parts.Length - 1)));
    }
예제 #32
0
    public IRCSession(
        string serverAddress, 
		uint port, 
		string nick, 
		string user, 
		string ident, 
		string channel, 
		byte[] encryptionKey)
    {
        m_ircServerAddress = serverAddress;
        m_ircServerPort = port;
        m_ircPrimaryChannelName = channel;
        m_ircChannelName = m_ircPrimaryChannelName;
        m_ircPrimaryNick = nick;
        m_ircNick = m_ircPrimaryNick;
        m_ircUser = user;
        m_ircFullIdentity = ident;

        m_irc = new IRCEventDispatcher();

        m_irc.AddEventListener(IRCEvent.EVENT_STATUSMESSAGE, StatusMessageEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_SOCKOPEN, SockOpenEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_ERROR, ErrorEventHandler);

        m_irc.AddEventListener(IRCEvent.EVENT_SOCKERROR, SockErrorEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_ACTIVEMESSAGE, ActiveMessageEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_PING, PingEventHandler);

        m_irc.AddEventListener(IRCEvent.EVENT_WELCOME, WelcomeEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_NOTICE, NoticeEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_JOIN, JoinEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_PRIVMSG, PrivmsgEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_TOPIC, TopicEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_MODE, ModeEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_NICK, NickEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_KICK, KickEventHandler);
        m_irc.AddEventListener(IRCEvent.EVENT_QUIT, QuitEventHandler);

        if (encryptionKey != null)
        {
            // TODO: Generate a real random number for IV, pass it to other clients
            // Blowfish needs an initialization vector.
            // Normally this would be a cryptographically secure random number.
            // This value can be transmitted in public somehow, but I don't feel
            // like doing the plumbing for that yet.
            // So, for now, we make a pseudo-random IV seeded by the IRC port.
            System.Random rng = new System.Random((int)port);
            byte[] initialization_vector= new byte[8];

            rng.NextBytes(initialization_vector);
            m_encryptor = new Blowfish(encryptionKey);
            m_encryptor.IV= initialization_vector;

            // The IRC channel key all users use to access the channel is the
            // channel name encrypted using the IRC encryption key in Base64 encoding
            m_ircChannelKey = EncryptAndBase64Encode(channel);
        }
        else
        {
            m_ircChannelKey = "";
        }

        m_outputStreams = new List<OutputStreamDelegate>();
        m_gameEventStreams = new List<GameEventStreamDelegate>();
        m_loggingStreams = new List<LogStreamDelegate>();

        m_state = eState.disconnected;

        ClearIrcNickToCharacterIdMap();
    }
예제 #33
0
 public BlowfishCipher2(byte[] key)
 {
     Debug.Assert(key.Length == 32);
     _bf = new Blowfish();
     _bf.initializeKey(key);
 }
예제 #34
0
		public BlowfishCipher2(byte[] key, byte[] iv) {
			_bf = new Blowfish();
			_bf.SetIV(iv);
			_bf.initializeKey(key);
		}
예제 #35
0
 public BlowfishCipher2(byte[] key, byte[] iv)
 {
     _bf = new Blowfish();
     _bf.SetIV(iv);
     _bf.initializeKey(key);
 }
예제 #36
0
        // Test using test vector
        // https://www.schneier.com/code/vectors.txt
        internal static void Test()
        {
            // Test ECB
            using (var reader = new System.IO.StreamReader(@"vectors.txt")) {
                string line;
                do {
                    line = reader.ReadLine();
                } while (line != null && !line.StartsWith("key bytes"));

                var blowfish = new Blowfish();
                int count = 0;
                while (true) {
                    line = reader.ReadLine();
                    if (line == null) {
                        break;
                    }
                    string[] w = System.Text.RegularExpressions.Regex.Split(line, @"\s\s+");
                    if (w.Length < 3 || w[0].Length != 16 || w[1].Length != 16 || w[2].Length != 16) {
                        break;
                    }
                    byte[] key = BigIntegerConverter.ParseHex(w[0]);
                    byte[] clear = BigIntegerConverter.ParseHex(w[1]);
                    byte[] cipher = BigIntegerConverter.ParseHex(w[2]);

                    ++count;
                    System.Diagnostics.Debug.WriteLine("Test ECB #{0}", count);

                    blowfish.InitializeKey(key);
                    for (int tries = 1; tries <= 3; ++tries) {
                        byte[] encrypted = new byte[cipher.Length];
                        blowfish.BlockEncrypt(clear, 0, encrypted, 0);
                        for (int i = 0; i < cipher.Length; ++i) {
                            if (encrypted[i] != cipher[i]) {
                                throw new Exception("encryption failed");
                            }
                        }
                    }
                    for (int tries = 1; tries <= 3; ++tries) {
                        byte[] decrypted = new byte[clear.Length];
                        blowfish.BlockDecrypt(cipher, 0, decrypted, 0);
                        for (int i = 0; i < cipher.Length; ++i) {
                            if (decrypted[i] != clear[i]) {
                                throw new Exception("decryption failed");
                            }
                        }
                    }
                }
            }

            // Test CBC
            {
                byte[] key = BigIntegerConverter.ParseHex("0123456789ABCDEFF0E1D2C3B4A59687");
                byte[] iv = BigIntegerConverter.ParseHex("FEDCBA9876543210");
                // data: 37363534333231204E6F77206973207468652074696D6520666F722000 (29 bytes) + padding bytes (3 bytes)
                byte[] data = BigIntegerConverter.ParseHex("37363534333231204E6F77206973207468652074696D6520666F722000000000");
                byte[] cipher = BigIntegerConverter.ParseHex("6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC");
                System.Diagnostics.Debug.WriteLine("Test CBC");

                {
                    Blowfish blowfish = new Blowfish();
                    blowfish.InitializeKey(key);
                    blowfish.SetIV(iv);

                    byte[] encrypted = new byte[cipher.Length];
                    blowfish.EncryptCBC(data, 0, data.Length, encrypted, 0);
                    for (int i = 0; i < cipher.Length; ++i) {
                        if (encrypted[i] != cipher[i]) {
                            throw new Exception("encryption failed");
                        }
                    }
                }

                {
                    Blowfish blowfish = new Blowfish();
                    blowfish.InitializeKey(key);
                    blowfish.SetIV(iv);

                    byte[] decrypted = new byte[data.Length];
                    for (int i = 0; i < decrypted.Length; ++i) {
                        decrypted[i] = 0xff;
                    }
                    blowfish.DecryptCBC(cipher, 0, cipher.Length, decrypted, 0);
                    for (int i = 0; i < data.Length; ++i) {
                        if (decrypted[i] != data[i]) {
                            throw new Exception("decryption failed");
                        }
                    }
                }
            }
        }
예제 #37
0
        public override ArcFile TryOpen(ArcView file)
        {
            int version;

            if (file.View.AsciiEqual(4, "1.00"))
            {
                version = 100;
            }
            else if (file.View.AsciiEqual(4, "1.10"))
            {
                version = 110;
            }
            else
            {
                return(null);
            }
            int count = file.View.ReadInt32(0x14);

            if (!IsSaneCount(count))
            {
                return(null);
            }

            int  bucket_count = file.View.ReadInt32(0x18);
            uint index_size   = file.View.ReadUInt32(0x1C);
            uint arc_seed     = file.View.ReadUInt32(0x20);
            long index_offset = version >= 110 ? 0x2C : 0x24;
            long base_offset  = index_offset + index_size;
            var  blowfish     = new Blowfish(IndexKey);
            var  packed_bytes = file.View.ReadBytes(index_offset, index_size);

            blowfish.Decipher(packed_bytes, packed_bytes.Length & ~7);

            using (var input = new MemoryStream(packed_bytes))
                using (var unpacked = new ZLibStream(input, CompressionMode.Decompress))
                    using (var index = new BinaryReader(unpacked))
                    {
                        var file_map  = BuildFileNameMap(arc_seed);
                        var dir_table = new List <TacBucket> (bucket_count);
                        for (int i = 0; i < bucket_count; ++i)
                        {
                            var entry = new TacBucket();
                            entry.Hash  = index.ReadUInt16();
                            entry.Count = index.ReadUInt16();
                            entry.Index = index.ReadInt32();
                            dir_table.Add(entry);
                        }
                        var dir = new List <Entry> (count);
                        for (int i = 0; i < count; ++i)
                        {
                            var entry = new TacEntry();
                            entry.Hash         = index.ReadUInt64();
                            entry.IsPacked     = index.ReadInt32() != 0;
                            entry.UnpackedSize = index.ReadUInt32();
                            entry.Offset       = base_offset + index.ReadUInt32();
                            entry.Size         = index.ReadUInt32();
                            if (!entry.CheckPlacement(file.MaxOffset))
                            {
                                return(null);
                            }
                            dir.Add(entry);
                        }
                        var buffer = new byte[8];
                        foreach (var bucket in dir_table)
                        {
                            for (int i = 0; i < bucket.Count; ++i)
                            {
                                var entry = dir[bucket.Index + i] as TacEntry;
                                entry.Hash = entry.Hash << 16 | bucket.Hash;
                                bool known_name = file_map.ContainsKey(entry.Hash);
                                if (known_name)
                                {
                                    entry.Name = file_map[entry.Hash];
                                    entry.Type = FormatCatalog.Instance.GetTypeFromName(entry.Name);
                                }
                                else
                                {
                                    entry.Name = string.Format("{0:X16}", entry.Hash);
                                }
                                if (entry.IsPacked)
                                {
                                    continue;
                                }
                                entry.Key = Encoding.ASCII.GetBytes(string.Format("{0}_tlib_secure_", entry.Hash));
                                if (!known_name)
                                {
                                    var bf = new Blowfish(entry.Key);
                                    file.View.Read(entry.Offset, buffer, 0, 8);
                                    bf.Decipher(buffer, 8);
                                    var res = AutoEntry.DetectFileType(buffer.ToUInt32(0));
                                    if (res != null)
                                    {
                                        entry.ChangeType(res);
                                    }
                                }
                                if ("image" == entry.Type)
                                {
                                    entry.EncryptedSize = Math.Min(10240, entry.Size);
                                }
                                else
                                {
                                    entry.EncryptedSize = entry.Size;
                                }
                            }
                        }
                        return(new ArcFile(file, this, dir));
                    }
        }
예제 #38
0
		public BlowfishCipher2(byte[] key) {
			Debug.Assert(key.Length==32);
			_bf = new Blowfish();
			_bf.initializeKey(key);
		}