PeekChar() публичный метод

public PeekChar ( ) : int
Результат int
Пример #1
0
        private static BDictionary ReadDictionary(BinaryReader binaryReader)
        {
            Contract.Requires(binaryReader != null);

            int i = binaryReader.ReadByte();
            if (i != 'd')
            {
                throw Error();
            }

            BDictionary dict = new BDictionary();

            try
            {
                for (int c = binaryReader.PeekChar(); ; c = binaryReader.PeekChar())
                {
                    if (c == -1) throw Error();
                    if (c == 'e')
                    {
                        binaryReader.ReadByte();
                        break;
                    }
                    BString k = ReadString(binaryReader);
                    IBElement v = ReadElement(binaryReader);
                    dict.Add(k, v);
                }
            }
            catch (BencodingException) { throw; }
            catch (Exception e) { throw Error(e); }

            return dict;
        }
Пример #2
0
 public CServerProcessSources(MemoryStream buffer, uint ServerIP, ushort ServerPort)
 {
     byte[] FileHash;
     uint IP;
     ushort Port;
     byte nSources;
     bool moreFiles = true;
     BinaryReader reader = new BinaryReader(buffer);
     do
     {
         FileHash = reader.ReadBytes(16);
         nSources = reader.ReadByte();
         Debug.WriteLine("Received " + nSources.ToString() + " for " + CKernel.HashToString(FileHash));
         while (nSources > 0)
         {
             IP = reader.ReadUInt32();
             Port = reader.ReadUInt16();
             nSources--;
             CKernel.ClientsList.AddClientToFile(IP, Port, ServerIP, ServerPort, FileHash);
         }
         if ((reader.PeekChar() != 0) && (reader.PeekChar() != -1))
         {
             if ((Protocol.ProtocolType)reader.ReadByte() != Protocol.ProtocolType.eDonkey) moreFiles = false;
             if ((reader.PeekChar() == -1) || (reader.ReadByte() != (byte)Protocol.ServerCommandUDP.GlobalFoundSources))
                 moreFiles = false;
         }
         else moreFiles = false;
     }
     while (moreFiles);
     reader.Close();
     buffer.Close();
     reader = null;
     buffer = null;
 }
Пример #3
0
 public CServerSearchResults(MemoryStream buffer, CSearcher search, bool esUDP)
 {
     BinaryReader reader = new BinaryReader(buffer);
     if (!esUDP)
     {
         uint nResultados = reader.ReadUInt32();
         for (uint i = 0; i < nResultados; i++)
         {
             m_ExtractResult(reader, search);
         }
         search.OnTCPSearchEnded();
     }
     else
     {
         m_ExtractResult(reader, search);
         while ((reader.PeekChar() != 0) && (reader.PeekChar() != -1))
         {
             Debug.WriteLine("MoreUDP results in one packet");
             if ((Protocol.ProtocolType)reader.ReadByte() != Protocol.ProtocolType.eDonkey) break;
             if ((reader.PeekChar() == -1) || (reader.ReadByte() != (byte)Protocol.ServerCommandUDP.GlobalSearchResult))
                 break;
             m_ExtractResult(reader, search);
         }
     }
     reader.Close();
     buffer.Close();
     reader = null;
     buffer = null;
 }
        static void Main(string[] args)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly();           

            IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("binPath", FileMode.OpenOrCreate, FileAccess.ReadWrite, isf);

            try
            {
                using (BinaryReader binreader = new BinaryReader(isfs))
                {
                    int BinPeek = binreader.PeekChar();
                    while (BinPeek > 0)
                    {
                        Int64 ID = binreader.ReadInt32();
                        string Name = binreader.ReadString();

                        Console.WriteLine("Readed binary = " + ID.ToString() + " " + Name);
                        BinPeek = binreader.PeekChar();
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                isfs.Close();
                Console.ReadKey();
            }
            
            
            Person p = new Person(2, "Pri", 21, DateTime.Parse("27/11/1990"));
            isfs = new IsolatedStorageFileStream("binPath", FileMode.OpenOrCreate, FileAccess.ReadWrite, isf);

            try
            {
                BinaryWriter binwriter = new BinaryWriter(isfs);

                binwriter.Write(p.ID);
                binwriter.Write(p.Name);
                binwriter.Write(p.Age);
                binwriter.Write(p.Birth.ToString());

                binwriter.Flush();
            }
            catch (Exception ex)
            {                
                Console.WriteLine(ex.Message);                
            }
            finally
            {
                isfs.Close();
                Console.ReadKey();
            }
        }
Пример #5
0
        private static byte[] ReadUntilSeparator( BinaryReader reader )
        {
            var bytes = new List<byte>();

            int peek = reader.PeekChar();
            while( peek != INT_RecordSeparator && peek != INT_EOF)
            {
                bytes.Add( reader.ReadByte() );
                peek = reader.PeekChar();
            }

            return bytes.ToArray();
        }
        public static TapFile ReadTapFile(Stream inputStream, string fileName)
        {
            TapFile resultFile = new TapFile(fileName);

            using (BinaryReader fileReader = new BinaryReader(inputStream, Encoding.GetEncoding("ISO-8859-1")))
            {
                while (fileReader.PeekChar() >= 0)
                {
                    TapDataBlock dataBlock = ReadTapDataBlock(fileReader);
                    resultFile.DataBlocks.Add(dataBlock);

                    TapeSection section = new TapeSection(dataBlock);
                    resultFile.Sections.Add(section);
                }
            }
            TapeSection lastSection = resultFile.Sections[resultFile.Sections.Count-1];
            TapeSoundSequence lastSoundSequence = lastSection.SoundSequences[lastSection.SoundSequences.Count - 1];
            if(lastSoundSequence.GetType() != typeof(PauseSequence))
            {
                lastSection.SoundSequences.Add(new PauseSequence("End of tape", 1));
            }

            foreach (TapeSection section in resultFile.Sections)
            {
                resultFile.Duration += section.Duration;
            }
            resultFile.Description = ""; // Tap file do not contain metadata

            return resultFile;
        }
        public SWFReader(Stream stream)
        {
            Tags = new List<Tag>();
            using (var b = new BinaryReader(stream))
                if (b.PeekChar() == 'C') //Zlib Compressed
                    Uncompress(b);

            if (SWFBinary == null)
                SWFBinary = new BinaryReader(stream);

            ReadSWFHeader();

            bool readEndTag = false;
            while (SWFBinary.BaseStream.Position < SWFBinary.BaseStream.Length && !readEndTag)
            {
                Tag b = ReadTag();
                if (b == null)
                    continue;

                if (b is End)
                    readEndTag = true;

                Tags.Add(b);
            }
        }
 //--Methods
 public UnknownChunk(string id, int size, BinaryReader reader)
     : base(id, size)
 {
     data = reader.ReadBytes(size);
     if (size % 2 == 1 && reader.PeekChar() == 0)
         reader.ReadByte();
 }
Пример #9
0
        public DocumentParser(string path)
        {
            using (var br = new BinaryReader(File.OpenRead(path))) {
                if (br.PeekChar() == '@')
                {
                    List<byte> processed = new List<byte>();

                    while (br.BaseStream.Position != br.BaseStream.Length)
                    {
                        var s = IWantToFiddle(ReadLine(br, 256));
                        if (s != null)
                        {
                            processed.AddRange(s);
                            processed.Add(13);
                            processed.Add(10);
                        }
                    }

                    data = new byte[processed.Count];
                    processed.CopyTo(data);

                    bFiddled = true;
                }
                else
                {
                    data = br.ReadBytes((int)br.BaseStream.Length);
                }
            }
        }
Пример #10
0
        private void button_choose_file_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text files (*.txt)|*.txt";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                BinaryReader sR = new BinaryReader(File.Open(ofd.FileName, FileMode.Open), Encoding.ASCII);
                int i = 0;
                while (sR.PeekChar() != -1)
                {
                    i++;
                  sR.ReadByte();

                }
                sR.Close();
                BinaryReader sR2 = new BinaryReader(File.Open(ofd.FileName, FileMode.Open), Encoding.ASCII);
                fileData = sR2.ReadBytes(i);

                sR2.Close();
            }

            textBox1.Text = ofd.FileName.Split('\\')[ofd.FileName.Split('\\').Length-1];

            textBox2.Enabled = true;
        }
 public List<Book> ReadFrom(string FileName)
 {
     if (FileName.Equals(string.Empty) || FileName == null)
         throw new ArgumentNullException("File name not found!");
     //bookList.Clear();
     try
     {
         List<Book> bookList = new List<Book>();
         BinaryReader read = new BinaryReader(File.Open(FileName, FileMode.OpenOrCreate));
         while (read.PeekChar() > -1)
         {
             string author = read.ReadString();
             string title = read.ReadString();
             int PA = read.ReadInt32();
             string genre = read.ReadString();
             bookList.Add(new Book(author, title, PA, genre));
         }
         read.Close();
         return bookList;
     }
     catch (FileNotFoundException)
     {
         throw new InvalidDataException("File not found!");
     }
 }
Пример #12
0
        public Assembly(Stream s)
        {
            var dict = new Dictionary<byte, Type>();
            var types = typeof (Assembly).Assembly.GetTypes();
            foreach (var t in types)
            {
                if (!t.IsSubclassOf(typeof (Instruction)))
                    continue;
                var instance = (Instruction) Activator.CreateInstance(t);
                var id = instance.Type;
                dict[id] = t;
            }

            using (var reader = new BinaryReader(s))
            {
                ReaderHeader(reader);
                while (reader.PeekChar() > -1)
                {
                    var type = reader.ReadByte();
                    var ins = dict[type];
                    var i = (Instruction) Activator.CreateInstance(ins);
                    i.ReadFrom(reader);
                    _template.Add(i);
                }
            }
        }
Пример #13
0
        /****************************************************************************/
        public static string ReadLine(this System.IO.BinaryReader objReader)
        {
            StringBuilder sbLine = new StringBuilder();
            char          chRead = '\0';

            try
            {
                while (true)
                {
                    chRead = objReader.ReadChar();

                    if (chRead == '\r' || chRead == '\n')
                    {
                        break;
                    }

                    sbLine.Append(chRead);
                }

                if (chRead == '\r' && objReader.PeekChar() == '\n')
                {
                    objReader.ReadChar();
                }
            }
            catch (EndOfStreamException)
            {
            }

            return(sbLine.ToString());
        }
    private bool ValidateCore(string token, Guid userId, ContactChallengePurpose purpose, string stamp) {
      try {
        byte[] unprotectedData = Protector.Unprotect(Convert.FromBase64String(token));
        var ms = new MemoryStream(unprotectedData);
        using (var reader = new BinaryReader(ms, DefaultEncoding, true)) {
          DateTimeOffset creationTime = new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero);
          DateTimeOffset expirationTime = creationTime + TokenLifespan;
          if (expirationTime < DateTimeOffset.UtcNow) {
            return false;
          }

          string tokenUserId = reader.ReadString();
          if (!string.Equals(tokenUserId, userId.ToString(), StringComparison.OrdinalIgnoreCase)) {
            return false;
          }

          var tokenPurpose = reader.ReadString();
          if (!string.Equals(tokenPurpose, purpose.ToString())) {
            return false;
          }

          var tokenStamp = reader.ReadString();
          if (reader.PeekChar() != -1) {
            return false;
          }

          bool isTokenValid = tokenStamp == stamp;
          return isTokenValid;
        }
      } catch {
        // do not leak exception
        return false;
      }
    }
Пример #15
0
		public static List<Product> GetProducts()
		{
			// if the directory doesn't exist, create it
			if (!Directory.Exists(dir))
				Directory.CreateDirectory(dir);

			// create the object for the input stream for a binary file
			BinaryReader binaryIn = 
				new BinaryReader(
				new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

			// create the array list
			List<Product> products = new List<Product>();

			// read the data from the file and store it in the List<Product>
			while (binaryIn.PeekChar() != -1)
			{
				Product product = new Product();
				product.Code = binaryIn.ReadString();
				product.Description = binaryIn.ReadString();
				product.Price = binaryIn.ReadDecimal();
				products.Add(product);
			}

			// close the input stream for the binary file
			binaryIn.Close();

			return products;
		}
Пример #16
0
 public CFileStatus(MemoryStream buffer, bool readHash)
 {
     BinaryReader reader = new BinaryReader(buffer);
     if (readHash) FileHash = reader.ReadBytes(16);
     if (reader.PeekChar() == -1)
         nChunks = 0;
     else
         nChunks = reader.ReadUInt16();
     if (nChunks > 0)
     {
         Chunks = new byte[nChunks];
         short bitProcesados = 0;
         byte bitArray;
         short i;
         while (bitProcesados != nChunks)
         {
             bitArray = reader.ReadByte();
             i = 0;
             do //for (i=0;i!=8;i++)
             {
                 Chunks[bitProcesados] = (((bitArray >> i) & 1) == 1) ? (byte)Protocol.ChunkState.Complete : (byte)Protocol.ChunkState.Empty;
                 bitProcesados++;
                 i++;
             }
             while ((i != 8) & (bitProcesados != nChunks));
         }
     }
     //          reader.Close();
     //          buffer.Close();
     //          reader=null;
     //          buffer=null;
 }
        public static void AddCliloc( string lang )
        {
            StringList list = StringList.GetList( lang );
            if ( list == null )
                list = StringList.AddLanguage( lang );

            string path = Core.FindDataFile( String.Format( "cliloc.{0}", lang ) );

            if ( path == null )
            {
                Console.WriteLine( "Warning: cliloc.{0} not found", lang );
                return;
            }

            using ( BinaryReader bin = new BinaryReader( new FileStream( path, FileMode.Open, FileAccess.Read, FileShare.Read ), Encoding.ASCII ) )
            {
                bin.ReadInt32();
                bin.ReadInt16();

                Encoding utf8 = Encoding.GetEncoding( "UTF-8", new EncoderReplacementFallback(""), new DecoderReplacementFallback("") );

                while ( bin.PeekChar() != -1 )
                {
                    int number = bin.ReadInt32();
                    bin.ReadByte(); //State in Cliloc
                    int length = bin.ReadInt16(); //Max of 65535 characters

                    StringEntry entry = new StringEntry( number, LState.Original, StringList.FormatArguments( utf8.GetString( bin.ReadBytes( length ) ) ) );

                    list.Table[number] = entry;
                }

                bin.Close();
            }
        }
 public StringList(string language)
 {
     this.m_Language = language;
     this.m_Table = new Hashtable();
     string filePath = Client.GetFilePath(string.Format("cliloc.{0}", language));
     if (filePath == null)
     {
         this.m_Entries = new StringEntry[0];
         return;
     }
     ArrayList arrayLists = new ArrayList();
     using (BinaryReader binaryReader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
     {
         binaryReader.ReadInt32();
         binaryReader.ReadInt16();
         while (binaryReader.PeekChar() != -1)
         {
             int num = binaryReader.ReadInt32();
             binaryReader.ReadByte();
             int num1 = binaryReader.ReadInt16();
             if (num1 > (int)StringList.m_Buffer.Length)
             {
                 StringList.m_Buffer = new byte[num1 + 1023 & -1024];
             }
             binaryReader.Read(StringList.m_Buffer, 0, num1);
             string str = Encoding.UTF8.GetString(StringList.m_Buffer, 0, num1);
             arrayLists.Add(new StringEntry(num, str));
             this.m_Table[num] = str;
         }
     }
     this.m_Entries = (StringEntry[])arrayLists.ToArray(typeof(StringEntry));
 }
Пример #19
0
        public static List<Customer> GetCustomers()
        {
            // if the directory doesn't exist, create it
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            // create the array list for customers
            List<Customer> customers = new List<Customer>();

            // create the object for the input stream for a binary file
            BinaryReader binaryIn =
                new BinaryReader(
                new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

            // read the data from the file and store it in the List<>
            while (binaryIn.PeekChar() != -1)
            {
                Customer c = new Customer();
                c.FirstName = binaryIn.ReadString();
                c.LastName = binaryIn.ReadString();
                c.Email = binaryIn.ReadString();
                customers.Add(c);
            }

            binaryIn.Close();

            return customers;
        }
Пример #20
0
        public IEnumerable<Packet> ReadPackets(string file)
        {
            using (var gr = new BinaryReader(new FileStream(file, FileMode.Open, FileAccess.Read), Encoding.ASCII))
            {
                gr.ReadBytes(3); // PKT
                gr.ReadBytes(2); // 0x02, 0x02
                gr.ReadByte(); // 0x06
                Build = gr.ReadUInt16(); // build
                gr.ReadBytes(4); // client locale
                gr.ReadBytes(20); // packet key
                gr.ReadBytes(64); // realm name

                var packets = new List<Packet>();
                while (gr.PeekChar() >= 0)
                {
                    Direction direction = gr.ReadByte() == 0xff ? Direction.Server : Direction.Client;
                    uint unixtime = gr.ReadUInt32();
                    uint tickcount = gr.ReadUInt32();
                    uint size = gr.ReadUInt32();
                    OpCodes opcode = (direction == Direction.Client) ? (OpCodes)gr.ReadUInt32() : (OpCodes)gr.ReadUInt16();
                    byte[] data = gr.ReadBytes((int)size - ((direction == Direction.Client) ? 4 : 2));

                    packets.Add(new Packet(direction, opcode, data, unixtime, tickcount));
                }
                return packets;
            }
        }
Пример #21
0
 public WkbBinaryReader(Stream stream)
 {
     _reader = new BinaryReader(stream);
     HasData = _reader.PeekChar() != -1;
     if (HasData)
         Encoding = (WkbEncoding)_reader.ReadByte();
 }
Пример #22
0
        private void ValidateDisposedExceptions(BinaryReader binaryReader)
        {
            byte[] byteBuffer = new byte[10];
            char[] charBuffer = new char[10];

            Assert.Throws<ObjectDisposedException>(() => binaryReader.PeekChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(byteBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(charBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBoolean());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBytes(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChars(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDecimal());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDouble());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt64());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSingle());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadString());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt64());
        }
 public StringList(string language)
 {
     this.m_Language = language;
       this.m_Table = new Hashtable();
       string filePath = Client.GetFilePath(string.Format("cliloc.{0}", (object) language));
       if (filePath == null)
       {
     this.m_Entries = new StringEntry[0];
       }
       else
       {
     ArrayList arrayList = new ArrayList();
     using (BinaryReader binaryReader = new BinaryReader((Stream) new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
     {
       binaryReader.ReadInt32();
       int num1 = (int) binaryReader.ReadInt16();
       while (binaryReader.PeekChar() != -1)
       {
     int number = binaryReader.ReadInt32();
     int num2 = (int) binaryReader.ReadByte();
     int count = (int) binaryReader.ReadInt16();
     if (count > StringList.m_Buffer.Length)
       StringList.m_Buffer = new byte[count + 1023 & -1024];
     binaryReader.Read(StringList.m_Buffer, 0, count);
     string @string = Encoding.UTF8.GetString(StringList.m_Buffer, 0, count);
     arrayList.Add((object) new StringEntry(number, @string));
     this.m_Table[(object) number] = (object) @string;
       }
     }
     this.m_Entries = (StringEntry[]) arrayList.ToArray(typeof (StringEntry));
       }
 }
Пример #24
0
        internal static IBencodingType Decode(BinaryReader inputStream)
        {
            char next = (char)inputStream.PeekChar();

            switch (next)
            {
                case 'i':
                    // Integer
                    return BInt.Decode(inputStream);

                case 'l':
                    // List
                    return BList.Decode(inputStream);

                case 'd':
                    // List
                    return BDict.Decode(inputStream);

                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    // String
                    return BString.Decode(inputStream);
            }

            return null;
        }
Пример #25
0
        public SWFReader(string SWFFile)
        {
            Tags = new List<Tag>();
            using (BinaryReader b = new BinaryReader(File.Open(SWFFile, FileMode.Open)))
            {
                if (b.PeekChar() == 'C') //Zlib Compressed
                {
                    Uncompress(b);
                }
            }
            if (SWFBinary == null)
                SWFBinary = new BinaryReader(File.Open(SWFFile, FileMode.Open));

            ReadSWFHeader();

            bool readEndTag = false;
            while (SWFBinary.BaseStream.Position < SWFBinary.BaseStream.Length && !readEndTag)
            {
                Tag b = ReadTag();
                if (b != null)
                {
                    if (b is End)
                        readEndTag = true;
                    Tags.Add(b);
                }
            }
        }
Пример #26
0
        protected void LoadDirectoriesFromStream( BinaryReader reader )
        {
            Directories = new List<DirectoryEntry>();

            while( reader.PeekChar() != INT_RecordSeparator )
            {
                var entry = CreateDirectoryObject();
                char[] buffer = reader.ReadChars( Leader.SizeFieldTag );
                string tag = new string( buffer );
                if( tag == "0000" )
                    entry.Tag = DirectoryDataType.Filename;
                else if( tag == "0001" )
                    entry.Tag = DirectoryDataType.DDFRecordIdentifier;
                else
                    entry.Tag = (DirectoryDataType)Enum.Parse( typeof( DirectoryDataType ), tag );
                if( entry.Tag == DirectoryDataType.Unknown )
                    throw new InvalidDataException( String.Format("Unknown tag {0}", tag) );
                buffer = reader.ReadChars( Leader.SizeFieldLength );
                entry.Length = int.Parse( new string( buffer ) );
                buffer = reader.ReadChars( Leader.SizeFieldPos );
                entry.Position = int.Parse( new string( buffer ) );
                Directories.Add( entry );
            }
            reader.Read();
        }
        public int CheckTopScore()
        {
            BinaryReader br = new BinaryReader(new FileStream("ScoreData.txt", FileMode.Open));
            while (br.PeekChar() != -1)
            {
                SavePlayerScore sps = new SavePlayerScore(br.ReadString(), br.ReadInt32());
                SPSArrayList.Add(sps);
            }
            br.Close();

            SortOnPlayerScore sops = new SortOnPlayerScore();
            SPSArrayList.Sort(sops);

            int Listsize = 0;

            foreach (SavePlayerScore ba in SPSArrayList)
            {
                Listsize++;
                Console.WriteLine("{0}", ba.GetScore());
            }
            int[] WhoIsTheTop = new int[Listsize];

            int count2 = 0;
            foreach (SavePlayerScore ba in SPSArrayList)
            {
                WhoIsTheTop[count2] = ba.GetScore();
                count2++;
            }

            if (Listsize >= 1)
                return WhoIsTheTop[0];
            else
                return 0;
        }
Пример #28
0
        public void Decrypt(string inputFile, string outputFile, string password)
        {
            byte[] byteKeys = this.GetKey(password);
            byte[] ivBytes = this.GetIV();

            var decryptor = _symmetricAlgorithm.CreateDecryptor(byteKeys, ivBytes);
            int blockSize = _symmetricAlgorithm.BlockSize / 8;

            using (var binaryReader = new BinaryReader(File.OpenRead(inputFile), new ASCIIEncoding()))
            {
                using (var resultFile = File.Create(outputFile))
                {
                    using (var cryptoStream = new CryptoStream(resultFile, decryptor, CryptoStreamMode.Write))
                    {
                        using (var binaryWriter = new BinaryWriter(cryptoStream))
                        {
                            while (binaryReader.PeekChar() != -1)
                            {
                                binaryWriter.Write(binaryReader.ReadBytes(blockSize));
                            }
                        }
                    }
                }
            }
        }
Пример #29
0
        public IEnumerable<IAsn1Element> Parse(Stream asn1Stream)
        {
            using (var reader = new BinaryReader(asn1Stream))
            {
                while (reader.PeekChar() > -1)
                {
                    var element = GetAsn1ParsedElement(reader);

                    switch (element.Tag)
                    {
                        case 2:
                            yield return ParseInteger(element);
                            break;
                        case 4:
                            yield return ParseOctetString(element);
                            break;
                        case 48:
                            yield return ParseSequence(element);
                            break;
                        default:
                            yield return new Asn1UnknownElement(element.Tag, element.Data);
                            break;
                    }
                }
            }
        }
Пример #30
0
        private List<KeyValuePair<DDRDirectoryEntry, byte[]>> GetRowData( BinaryReader reader )
        {
            var rowData = new List<KeyValuePair<DDRDirectoryEntry, byte[]>>();
            foreach( DirectoryEntry entry in Directories.OrderBy( dir => dir.Position ) )
            {
                int peek = reader.PeekChar();
                if( peek == INT_RecordSeparator || peek == INT_EOF )
                    break;
                var fieldDescDir = DescriptiveRecord.Directories.OfType<DDRDirectoryEntry>().FirstOrDefault( ddrEntry => ddrEntry.Fields.First() == entry.Tag.GetDescription() );

                byte[] block;
                if( fieldDescDir.SubFields != null && fieldDescDir.SubFields.Any( field => field.Type == FieldType.Binary ) )
                    block = reader.ReadBytes( entry.Length - 1 );
                else
                    block = ReadUntilSeparator( reader );
                reader.Read();

                if( fieldDescDir.Type == DDRDirectoryEntryType.ArrayFieldList )
                {
                    int dataLength = fieldDescDir.SubFields.Sum( field => field.Length.Value );
                    for( int i = 0; i < block.Length / dataLength; i++ )
                    {
                        byte[] subBlock = new byte[ dataLength ];
                        Array.Copy( block, i * dataLength, subBlock, 0, dataLength );
                        rowData.Add( new KeyValuePair<DDRDirectoryEntry, byte[]>( fieldDescDir, subBlock ) );
                    }
                }
                else
                {
                    rowData.Add( new KeyValuePair<DDRDirectoryEntry, byte[]>( fieldDescDir, block ) );
                }
            }
            return rowData;
        }
Пример #31
0
        public static GSDump LoadDump(String FileName)
        {
            GSDump dmp = new GSDump();

            BinaryReader br = new BinaryReader(System.IO.File.Open(FileName, FileMode.Open));
            dmp.CRC = br.ReadInt32();

            Int32 ss = br.ReadInt32();
            dmp.StateData = br.ReadBytes(ss);

            dmp.Registers = br.ReadBytes(8192);

            while (br.PeekChar() != -1)
            {
                GSType id = (GSType)br.ReadByte();
                switch (id)
                {
                    case GSType.Transfer:
                        GSTransfer data = new GSTransfer();

                        byte index = br.ReadByte();

                        data.id = id;
                        data.Path = (GSTransferPath)index;

                        Int32 size = br.ReadInt32();

                        List<byte> Data = new List<byte>();
                        Data.AddRange(br.ReadBytes(size));
                        data.data = Data.ToArray();
                        dmp.Data.Add(data);
                        break;
                    case GSType.VSync:
                        GSData dataV = new GSData();
                        dataV.id = id;
                        dataV.data = br.ReadBytes(1);
                        dmp.Data.Add(dataV);
                        break;
                    case GSType.ReadFIFO2:
                        GSData dataR = new GSData();
                        dataR.id = id;
                        Int32 sF = br.ReadInt32();
                        dataR.data = BitConverter.GetBytes(sF);
                        dmp.Data.Add(dataR);
                        break;
                    case GSType.Registers:
                        GSData dataRR = new GSData();
                        dataRR.id = id;
                        dataRR.data = br.ReadBytes(8192);
                        dmp.Data.Add(dataRR);
                        break;
                    default:
                        break;
                }
            }
            br.Close();

            return dmp;
        }
Пример #32
0
        public Material(System.IO.BinaryReader br)
        {
            m_ambientColor = new Vec4(br);
            m_diffuseColor = new Vec4(br);
            m_name         = br.ReadString();
            bool isOpacityMapNull = br.ReadBoolean();

            if (isOpacityMapNull)
            {
                this.m_opacityMap = null;
            }
            else
            {
                this.m_opacityMap = MaterialMap.Load(br);
            }

            this.m_shininess     = (float)br.ReadDouble();
            this.m_specularColor = new Vec4(br);
            int count = br.ReadInt32();

            if (count > 0)
            {
                for (int i = 0; i < count; ++i)
                {
                    AddMaterialMap(MaterialMap.Load(br));
                }
            }

            this.Transparency = (float)br.ReadDouble();
            this.m_twoSided   = br.ReadBoolean();
            this.m_scale      = (float)br.ReadDouble();
            if (this.m_scale != 1)
            {
                this.hasTexTransform = true;
            }
            if (br.ReadBoolean())
            {
                remapUV    = new Vec2[2];
                remapUV[0] = Vec2.Load(br);
                remapUV[1] = Vec2.Load(br);
            }
            else
            {
                remapUV = null;
            }
            if (br.PeekChar() == '~')
            {
                br.ReadChar();
                count = br.ReadInt32();
                for (int i = 0; i < count; ++i)
                {
                    AddShader(Shader.Load(br));
                }
            }
        }
Пример #33
0
 static public int PeekChar(IntPtr l)
 {
     try {
         System.IO.BinaryReader self = (System.IO.BinaryReader)checkSelf(l);
         var ret = self.PeekChar();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #34
0
        public static bool IsAllowedExtension(Stream fileStream, FileExtension[] fileEx)
        {
            int fileLen = (Int32)fileStream.Length;

            byte[] imgArray = new byte[fileLen];
            imgArray = ImageToByteHelper.StreamToBytes(fileStream);
            MemoryStream ms = new MemoryStream(imgArray);

            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass          = "";
            byte   buffer;

            try
            {
                if (br.PeekChar() > -1)//避免长度为0的文件,再次抛出异常
                {
                    buffer     = br.ReadByte();
                    fileclass  = buffer.ToString();
                    buffer     = br.ReadByte();
                    fileclass += buffer.ToString();
                }
                else
                {
                    return(false);
                }
            }
            catch (EndOfStreamException ex)
            {
                return(false);//EndOfStreamException 无法在流的结尾之外进行读取。可以通过判断if(br.PeekChar()>-1)来判断,是否可以继续读取文件流
            }
            catch (Exception ex2)
            {
                return(false);
            }
            finally
            {
                br.Close();
                ms.Close();
            }

            //注意将文件流指针还原
            fileStream.Seek(0, SeekOrigin.Begin);
            foreach (FileExtension fe in fileEx)
            {
                if (Int32.Parse(fileclass) == (int)fe)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #35
0
        public void LoadProgramFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            System.IO.BinaryReader br;
            System.IO.FileStream   fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);

            br = new System.IO.BinaryReader(fs);

            var Magic1 = br.ReadByte();
            var Magic2 = br.ReadByte();
            var Magic3 = br.ReadByte();

            if (Magic1 != 'B' && Magic2 != '3' && Magic3 != '2')
            {
                throw new ArgumentException("This is not a valid B32 file!");
            }

            _startAddress     = br.ReadUInt16();
            _executionAddress = br.ReadUInt16();
            ushort Counter = 0;

            while ((br.PeekChar() != -1))
            {
                B32Memory[(_startAddress + Counter)] = br.ReadByte();
                Counter++;
            }

            br.Close();
            fs.Close();

            _instructionPointer = _executionAddress;

            ExecuteProgram(_startAddress, Counter);
        }
Пример #36
0
        private void f16_ButtonReadKeyword_Click(object sender, EventArgs e)
        {
            byte[]         tmp        = new byte[8];
            int            byteNumber = 0;
            int            code;
            OpenFileDialog Load = new OpenFileDialog();

            if (Load.ShowDialog() == DialogResult.OK)
            {
                System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default);
                while ((code = reader.PeekChar()) > -1 && byteNumber < 8)
                {
                    tmp[byteNumber] = reader.ReadByte();
                    byteNumber++;
                }
                reader.Close();
                if (code == -1 && byteNumber == 8)
                {
                    Key = tmp;
                    f16_fieldKeyword.Text = "Source: " + Load.FileName;
                }
                else
                {
                    if (code == -1)
                    {
                        MessageBox.Show("Слишком короткий ключ в файле", "Ошибка");
                    }
                    if (byteNumber == 8)
                    {
                        MessageBox.Show("Слишком длинный ключ в файле", "Ошибка");
                    }
                    f16_fieldKeyword.Text = null;
                    Key = new byte[0];
                }
            }
        }
Пример #37
0
        private Boolean FindFile(String filename, ref Byte track, ref Byte sector, ref Byte index)
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            Boolean fileMatchFound = false;

            Byte dirTrack  = 20;
            Byte dirSector = 4;

            Byte nextDirTrack  = 20;
            Byte nextDirSector = 4;

            while ((nextDirTrack != 0 && nextDirSector != 0) && fileMatchFound == false)
            {
                // Read current Directory Sector
                Byte[] directory = base.ReadSector(dirTrack, dirSector);

                nextDirTrack  = directory[0x00];
                nextDirSector = directory[0x01];

                index = 0;

                // Scan thru each file in the current directory
                System.IO.MemoryStream memStream    = new System.IO.MemoryStream(directory, 0, directory.Length);
                System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(memStream);

                // Move to first entry
                memStream.Seek(0x10, SeekOrigin.Begin);

                while (!fileMatchFound && index < 15)
                {
                    if (binaryReader.PeekChar() != 0x00)
                    {
                        Byte[] fileName  = binaryReader.ReadBytes(9);
                        Byte[] extension = binaryReader.ReadBytes(3);

                        String dirFilename  = enc.GetString(fileName).Trim();
                        String dirExtension = enc.GetString(extension).Trim();

                        String pathname = String.Format("{0}.{1}", dirFilename, dirExtension);

                        if (pathname == filename)
                        {
                            fileMatchFound = true;
                        }
                        else
                        {
                            index++;
                        }
                    }

                    binaryReader.ReadBytes(4);
                }

                if (!fileMatchFound)
                {
                    dirTrack  = nextDirTrack;
                    dirSector = nextDirSector;
                }
                else
                {
                    track  = dirTrack;
                    sector = dirSector;

                    index++;
                }
            }

            return(fileMatchFound);
        }
Пример #38
0
        private OricFileInfo[] ReadSedOricDirectory()
        {
            OricFileInfo[] diskDirectory = null;

            //int noOfFiles = 0;

            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            ArrayList diskCatalog = new ArrayList();

            Byte bNextTrack  = Convert.ToByte(20);
            Byte bNextSector = Convert.ToByte(4);

            Byte bCurrTrack  = bNextTrack;
            Byte bCurrSector = bNextSector;

            Boolean MoreDirectories = true;

            while (MoreDirectories)
            {
                // Read the first directory sector
                Byte[] directory = base.ReadSector(bCurrTrack, bCurrSector);

                if (directory[0] == 0x00 && directory[1] == 0x00)
                {
                    MoreDirectories = false;
                }
                else
                {
                    bCurrTrack  = directory[0];
                    bCurrSector = directory[1];
                }

                // Scan thru all 15 entries to build the directory
                UInt16 DirectoryIndex = 0;

                System.IO.MemoryStream stm = new System.IO.MemoryStream(directory, 0, 256);
                System.IO.BinaryReader rdr = new System.IO.BinaryReader(stm);
                stm.Seek(0x10, SeekOrigin.Begin);

                do
                {
                    if (rdr.PeekChar() != 0x00)
                    {
                        // Read the filename
                        String Filename = enc.GetString(rdr.ReadBytes(9)).Trim();

                        // Read the file extension
                        String FileExtension = enc.GetString(rdr.ReadBytes(3)).Trim();

                        // Read the file descriptor track
                        Byte FileDescTrack = rdr.ReadByte();

                        // Read the file descriptor sector
                        Byte FileDescSector = rdr.ReadByte();

                        // Read the no. of sectors used by file (includes file descriptor)
                        Byte SectorsUsed = rdr.ReadByte();

                        // Read the files protection status
                        Byte ProtectionStatus = rdr.ReadByte();

                        OricFileInfo diskFileInfo = new OricFileInfo();
                        diskFileInfo.MediaType = OricExplorer.MediaType.DiskFile;

                        //diskFileInfo.m_bDosFormat = OricDisk.DOSFormat.SedOric;

                        diskFileInfo.Folder     = base.diskFolder;
                        diskFileInfo.ParentName = base.diskPathname;

                        diskFileInfo.ProgramName = Filename;
                        diskFileInfo.Extension   = FileExtension;

                        if (FileExtension.Length > 0)
                        {
                            diskFileInfo.ProgramName = String.Format("{0}.{1}", Filename, FileExtension);
                        }
                        else
                        {
                            diskFileInfo.ProgramName = Filename;
                        }

                        diskFileInfo.FirstTrack    = FileDescTrack;
                        diskFileInfo.FirstSector   = FileDescSector;
                        diskFileInfo.LengthSectors = SectorsUsed;

                        if (ProtectionStatus == 0xC0)
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Protected;
                        }
                        else if (ProtectionStatus == 0x40)
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected;
                        }
                        else
                        {
                            diskFileInfo.Protection = OricProgram.ProtectionStatus.Unprotected;
                        }

                        Byte[] FileDescriptor = base.ReadSector(FileDescTrack, FileDescSector);

                        System.IO.MemoryStream stmFileDescriptor = new System.IO.MemoryStream(FileDescriptor, 0, FileDescriptor.Length);
                        System.IO.BinaryReader rdrFileDescriptor = new System.IO.BinaryReader(stmFileDescriptor);

                        stmFileDescriptor.Seek(0x03, SeekOrigin.Begin);

                        Byte FileType = rdrFileDescriptor.ReadByte();

                        if ((FileType & 0x08) == 0x08)
                        {
                            // We have a direct access file
                            diskFileInfo.m_ui16NoOfRecords  = rdrFileDescriptor.ReadUInt16();
                            diskFileInfo.m_ui16RecordLength = rdrFileDescriptor.ReadUInt16();

                            diskFileInfo.StartAddress = 0x0000;
                            diskFileInfo.EndAddress   = (ushort)(diskFileInfo.m_ui16NoOfRecords * diskFileInfo.m_ui16RecordLength);
                        }
                        else if ((FileType & 0x10) == 0x10)
                        {
                            // We have a sequential file
                            diskFileInfo.StartAddress = 0x0000;
                            diskFileInfo.EndAddress   = (ushort)((diskFileInfo.LengthSectors - 1) * 256);
                        }
                        else
                        {
                            diskFileInfo.StartAddress = rdrFileDescriptor.ReadUInt16();
                            diskFileInfo.EndAddress   = rdrFileDescriptor.ReadUInt16();
                        }

                        diskFileInfo.ExeAddress = rdrFileDescriptor.ReadUInt16();

                        if ((FileType & 0x08) == 0x08)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.DirectAccessFile;
                        }
                        else if ((FileType & 0x10) == 0x10)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.SequentialFile;
                        }
                        else if ((FileType & 0x20) == 0x20)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.WindowFile;
                        }
                        else if ((FileType & 0x40) == 0x40)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile;
                        }
                        else if ((FileType & 0x80) == 0x80)
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.BasicProgram;
                        }
                        else
                        {
                            diskFileInfo.Format = OricProgram.ProgramFormat.UnknownFile;
                        }

                        if (diskFileInfo.Format == OricProgram.ProgramFormat.CodeFile)
                        {
                            switch (diskFileInfo.StartAddress)
                            {
                            case 0xBB80:
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile;
                                }
                                else
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen;
                                }
                                break;

                            case 0xBBA8:
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HLP"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HelpFile;
                                }
                                else
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.TextScreen;
                                }
                                break;

                            case 0xA000: diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen; break;

                            case 0xB500: diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet; break;

                            default: diskFileInfo.Format = OricProgram.ProgramFormat.CodeFile; break;
                            }

                            if (diskFileInfo.StartAddress >= 0xA000 && diskFileInfo.StartAddress <= 0xBF3F)
                            {
                                // Possibly a HIRES screen
                                if (diskFileInfo.ProgramName.ToUpper().EndsWith(".HRS"))
                                {
                                    diskFileInfo.Format = OricProgram.ProgramFormat.HiresScreen;
                                }
                            }

                            if (diskFileInfo.ProgramName.ToUpper().EndsWith(".CHS"))
                            {
                                diskFileInfo.Format = OricProgram.ProgramFormat.CharacterSet;
                            }
                        }

                        if ((FileType & 0x01) == 0x01)
                        {
                            diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Enabled;
                        }
                        else
                        {
                            diskFileInfo.AutoRun = OricProgram.AutoRunFlag.Disabled;
                        }

                        diskCatalog.Add(diskFileInfo);
                    }

                    DirectoryIndex++;
                } while (DirectoryIndex < 15);
            }

            diskDirectory = new OricFileInfo[diskCatalog.Count];
            diskCatalog.CopyTo(diskDirectory);

            return(diskDirectory);
        }
Пример #39
0
        public static void ExecuteProgram(string path)
        {
            Uri uri = new Uri(Path.Combine(Directory.GetCurrentDirectory(), path));

            path = Path.GetFullPath(uri.AbsolutePath);

            BizMemory  = new byte[65535];
            StartAddr  = 0;
            ExecAddr   = 0;
            Register_A = 0;
            Register_B = 0;
            Register_D = 0;
            Register_X = 0;
            Register_Y = 0;
            UpdateRegisterStatus();

            ScreenMemoryLocation = 0xA000;
            m_ScreenMemory       = new byte[4000];
            for (int i = 0; i < 4000; i += 2)
            {
                m_ScreenMemory[i]     = 32;
                m_ScreenMemory[i + 1] = 7;
            }

            BinaryReader br;

            System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Open);
            br = new System.IO.BinaryReader(fs);

            // Check the magic header
            byte Magic1 = br.ReadByte();
            byte Magic2 = br.ReadByte();
            byte Magic3 = br.ReadByte();

            if (Magic1 != 'B' || Magic2 != 'I' || Magic3 != 'Z')
            {
                MessageDialog md = new MessageDialog(
                    win,
                    DialogFlags.Modal,
                    MessageType.Error,
                    ButtonsType.Ok,
                    "This is not a valid biz file!"
                    );
                md.Run();
                md.Destroy();
                return;
            }

            StartAddr = br.ReadUInt16();
            ExecAddr  = br.ReadUInt16();
            ushort Counter = 0;

            while ((br.PeekChar() != -1))
            {
                BizMemory[(StartAddr + Counter)] = br.ReadByte();
                ++Counter;
            }
            br.Close();
            fs.Close();

            InstructionPointer = ExecAddr;
            InterpretProgram(ExecAddr, Counter);
        }
Пример #40
0
        public Token Scan()
        {
            while (inputStream.PeekChar() != -1)
            {
                char ch = (char)inputStream.PeekChar();

                // Scan individual tokens
                if (IsWhiteSpace(ch))
                {
                    // eat the current char and skip ahead!
                    inputStream.Read();
                }
                else if ('/' == ch &&
                         '/' == inputStream.PeekChar())
                {
                    do
                    {
                        inputStream.Read();
                    } while (inputStream.PeekChar() != '\r' &&
                             inputStream.PeekChar() != '\n' &&
                             inputStream.PeekChar() != -1);
                }
                else if (char.IsLetter(ch) || ch == '_')
                {
                    // keyword or identifier

                    Text.StringBuilder accum = new Text.StringBuilder();

                    while (char.IsLetter(ch) || ch == '_')
                    {
                        accum.Append(ch);
                        inputStream.Read();

                        if (inputStream.PeekChar() == -1)
                        {
                            break;
                        }
                        else
                        {
                            ch = (char)inputStream.PeekChar();
                        }
                    }

                    return(new IdentToken(accum.ToString()));
                }
                else if (ch == '"') // string literal
                {
                    Text.StringBuilder accum = new Text.StringBuilder();

                    inputStream.Read(); // skip the '"'

                    if (inputStream.PeekChar() == -1)
                    {
                        throw new System.Exception("unterminated string literal");
                    }

                    while ((ch = (char)inputStream.PeekChar()) != '"')
                    {
                        accum.Append(ch);
                        inputStream.Read();

                        if (inputStream.PeekChar() == -1)
                        {
                            throw new System.Exception("unterminated string literal");
                        }
                    }

                    // skip the terminating "
                    inputStream.Read();

                    return(new StrToken(accum.ToString()));
                }
                else if (char.IsDigit(ch))
                {
                    // numeric literal

                    Text.StringBuilder accum = new Text.StringBuilder();

                    while (char.IsDigit(ch))
                    {
                        accum.Append(ch);
                        inputStream.Read();

                        if (inputStream.PeekChar() == -1)
                        {
                            break;
                        }
                        else
                        {
                            ch = (char)inputStream.PeekChar();
                        }
                    }
                    return(new IntToken(accum.ToString()));
                }
                // 运算符
                else if (ch == '<')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '=')
                    {
                        inputStream.Read();
                        return(new Token("<="));
                    }

                    return(new Token(ch));
                }
                else if (ch == '>')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '=')
                    {
                        inputStream.Read();
                        return(new Token(">="));
                    }
                    return(new Token(ch));
                }
                else if (ch == '=')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '=')
                    {
                        inputStream.Read();
                        return(new Token("=="));
                    }
                    return(new Token(ch));
                }
                else if (ch == '!')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '=')
                    {
                        inputStream.Read();
                        return(new Token("!="));
                    }
                    return(new Token(ch));
                }
                else if (ch == '+')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '+')
                    {
                        inputStream.Read();
                        return(new Token("++"));
                    }
                    return(new Token(ch));
                }
                else if (ch == '-')
                {
                    inputStream.Read();
                    if (inputStream.PeekChar() == '-')
                    {
                        inputStream.Read();
                        return(new Token("--"));
                    }
                    return(new Token(ch));
                }
                else if (ch == '\r')
                {
                    // 继续扫描下一个Token
                    inputStream.Read();
                }
                else if (ch == '\n')
                {
                    inputStream.Read();
                    return(Token.EOL);
                }
                else
                {
                    inputStream.Read();
                    // 其他字符直接作为OpToken返回
                    return(new Token(ch));
                }
            }
            return(Token.EOF);
        }
Пример #41
0
        /// <summary>
        /// Encrypt a token with an RSA public key
        /// </summary>
        /// <param name="plainText">Plaintext string</param>
        /// <returns>Encrypted string</returns>
        public string Encrypt(string plainText)
        {
            //// read pem public key
            Stream s = System.Reflection.Assembly.GetExecutingAssembly().
                       GetManifestResourceStream("KountRisSdk.kount.rsa.public.key");

            System.IO.StreamReader reader = new System.IO.StreamReader(s, Encoding.UTF8);
            string pem = reader.ReadToEnd();

            string header = String.Format("-----BEGIN PUBLIC KEY-----");
            string footer = String.Format("-----END PUBLIC KEY-----");
            int    start  = pem.IndexOf(header, StringComparison.Ordinal) + header.Length;
            int    end    = pem.IndexOf(footer, start, StringComparison.Ordinal) - start;

            byte[] key = Convert.FromBase64String(pem.Substring(start, end));

            UnicodeEncoding converter = new UnicodeEncoding();

            byte[] plainBytes = converter.GetBytes(plainText);

            RSACryptoServiceProvider rsa = null;

            //// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] seqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };

            byte[] seq = new byte[15];

            //// Read the asn.1 encoded SubjectPublicKeyInfo blob
            System.IO.MemoryStream mem  = new System.IO.MemoryStream(key);
            System.IO.BinaryReader binr = new System.IO.BinaryReader(mem);
            byte   bt       = 0;
            ushort twobytes = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                {
                    //// data read as little endian order
                    //// (actual data order for Sequence is 30 81)
                    binr.ReadByte(); //// advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16(); //// advance 2 bytes
                }
                else
                {
                    return(null);
                }

                seq = binr.ReadBytes(15); //// read the Sequence OID
                if (!this.CompareBytearrays(seq, seqOID))
                {
                    //// make sure Sequence for OID is correct
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103)
                {
                    //// data read as little endian order (actual data order for Bit String is 03 81)
                    binr.ReadByte(); //// advance 1 byte
                }
                else if (twobytes == 0x8203)
                {
                    binr.ReadInt16(); //// advance 2 bytes
                }
                else
                {
                    return(null);
                }

                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    //// expect null byte next
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                {
                    //// data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte(); //// advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16(); //// advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                byte lowbyte  = 0x00;
                byte highbyte = 0x00;

                if (twobytes == 0x8102)
                {
                    //// data read as little endian order
                    //// (actual data order for Integer is 02 81)
                    lowbyte = binr.ReadByte();  //// read next bytes which is bytes in modulus
                }
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //// advance 2 bytes
                    lowbyte  = binr.ReadByte();
                }
                else
                {
                    return(null);
                }

                byte[] modint =
                {
                    lowbyte, highbyte, 0x00, 0x00
                };

                int modsize = BitConverter.ToInt32(modint, 0);

                int firstbyte = binr.PeekChar();
                if (firstbyte == 0x00)
                {
                    //// if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte(); //// skip this null byte
                    modsize -= 1;    //// reduce modulus buffer size by 1
                }

                byte[] modulus = binr.ReadBytes(modsize); //// read the modulus bytes
                if (binr.ReadByte() != 0x02)
                {
                    //// expect an Integer for the exponent data
                    return(null);
                }

                int    expbytes = (int)binr.ReadByte();
                byte[] exponent = binr.ReadBytes(expbytes);

                //// create RSACryptoServiceProvider instance and initialize public key
                rsa = new RSACryptoServiceProvider();
                RSAParameters rsaKeyInfo = new RSAParameters();
                rsaKeyInfo.Modulus  = modulus;
                rsaKeyInfo.Exponent = exponent;
                rsa.ImportParameters(rsaKeyInfo);
            }
            finally
            {
                binr.Close();
            }

            byte[] encryptedBytes = rsa.Encrypt(plainBytes, false);
            return(Convert.ToBase64String(encryptedBytes));
        }
Пример #42
0
        private void f16_ButtonEncryptFile_Click(object sender, EventArgs e)
        {
            f16_labelPB.Text = "Проверка ключа...";
            f16_labelPB.Update();
            if (Key.Length != 8)
            {
                MessageBox.Show("Необходимо ввести ключ длиной 8 байт", "Ошибка");
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                goto exit_label;
            }
            CheckWeaknessOfKey();
            progressBar.Value = 0;

            LinkedList <byte> File = new LinkedList <byte>();

            f16_labelPB.Text = "Выбор файла...";
            f16_labelPB.Update();
            OpenFileDialog Load = new OpenFileDialog();

            if (Load.ShowDialog() == DialogResult.OK)
            {
                f16_labelPB.Text = "Считываем из файла...";
                f16_labelPB.Update();
                System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default);
                while (reader.PeekChar() > -1)
                {
                    File.AddLast(reader.ReadByte());
                }
                reader.Close();
            }
            else
            {
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                return;
            }

            File.AddLast(0x80);
            while (File.Count % 8 != 0)
            {
                File.AddLast(0x00);
            }

            byte[] Original = File.ToArray();
            File.Clear();
            progressBar.Maximum = Original.Length / 8;
            f16_labelPB.Text    = "Зашифровываем...";
            f16_labelPB.Update();
            byte[] Ciphertext;
            Cryption(true, ref Original, out Ciphertext);

            SaveFileDialog Save = new SaveFileDialog();

            if (Save.ShowDialog() == DialogResult.OK)
            {
                f16_labelPB.Text = "Сохраняем результат в файл...";
                f16_labelPB.Update();
                System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(Save.FileName, System.IO.FileMode.OpenOrCreate), Encoding.Default);
                foreach (var b in Ciphertext)
                {
                    writer.Write(b);
                }
                writer.Close();
            }
            else
            {
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                return;
            }
            f16_labelPB.Text = "Готово.";
            f16_labelPB.Update();
            exit_label :;
        }
Пример #43
0
        private void f16_ButtonDecryptFile_Click(object sender, EventArgs e)
        {
            f16_labelPB.Text = "Проверка ключа...";
            f16_labelPB.Update();
            if (Key.Length != 8)
            {
                MessageBox.Show("Необходимо ввести ключ длиной 8 байт", "Ошибка");
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                goto exit_label;
            }
            CheckWeaknessOfKey();
            progressBar.Value = 0;

            LinkedList <byte> File = new LinkedList <byte>();

            f16_labelPB.Text = "Выбор файла...";
            f16_labelPB.Update();
            OpenFileDialog Load = new OpenFileDialog();

            if (Load.ShowDialog() == DialogResult.OK)
            {
                f16_labelPB.Text = "Считываем из файла...";
                f16_labelPB.Update();
                System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default);
                while (reader.PeekChar() > -1)
                {
                    File.AddLast(reader.ReadByte());
                }
                reader.Close();
            }
            else
            {
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                return;
            }

            byte[] Ciphertext = File.ToArray();
            File.Clear();
            progressBar.Maximum = Ciphertext.Length / 8;
            f16_labelPB.Text    = "Расшифровываем...";
            f16_labelPB.Update();
            byte[] DecryptText;
            Cryption(false, ref Ciphertext, out DecryptText);

            int count = 0;

            for (int i = DecryptText.Length - 1; i >= DecryptText.Length - 8; i--)
            {
                if (DecryptText[i] == 0x80)
                {
                    count++;
                    break;
                }
                if (DecryptText[i] == 0x00)
                {
                    count++;
                    continue;
                }
            }

            SaveFileDialog Save = new SaveFileDialog();

            if (Save.ShowDialog() == DialogResult.OK)
            {
                f16_labelPB.Text = "Сохраняем результат в файл...";
                f16_labelPB.Update();
                System.IO.BinaryWriter writer = new System.IO.BinaryWriter(System.IO.File.Open(Save.FileName, System.IO.FileMode.OpenOrCreate), Encoding.Default);
                for (int i = 0; i < DecryptText.Length - count; i++)
                {
                    writer.Write(DecryptText[i]);
                }
                writer.Close();
            }
            else
            {
                f16_labelPB.Text = "Готов к работе";
                f16_labelPB.Update();
                return;
            }
            f16_labelPB.Text = "Готово.";
            f16_labelPB.Update();
            exit_label :;
        }