public void ConstructorDefaultTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            Common.AreEqual(Base64Encoder.StandardAlphabet, decoder.Alphabet);
            Assert.AreEqual(Base64Encoder.StandardPadding, decoder.Padding);
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public override byte[] GetBytes(ReadOnlySpan <char> chars)
        {
            // GetBytes converts in two passes so that it can perform a single allocation
            // for the final array of bytes...

            int bytesRequired = GetByteCount(chars);

            if (bytesRequired == 0)
            {
                return(Array.Empty <byte>());
            }

            var outputBytes = new byte[bytesRequired];

            var decoder       = new Base64Decoder(Settings);
            var convertStatus = decoder.ConvertData(chars, 0, chars.Length,
                                                    outputBytes.AsSpan(), 0, outputBytes.Length,
                                                    true,
                                                    out var inputUsed,
                                                    out var outputUsed);

            System.Diagnostics.Debug.Assert(convertStatus);
            System.Diagnostics.Debug.Assert(inputUsed == chars.Length);
            System.Diagnostics.Debug.Assert(outputUsed == outputBytes.Length);

            return(outputBytes);
        }
Ejemplo n.º 3
0
        /// <inheritdoc/>
        public override int GetByteCount(ReadOnlySpan <char> chars)
        {
            var         decoder      = new Base64Decoder(Settings);
            Span <byte> outputBuffer = stackalloc byte[1024];

            int           inputOffset  = 0;
            int           inputCount   = chars.Length;
            int           outputLength = 0;
            ConvertStatus convertStatus;

            do
            {
                convertStatus = decoder.ConvertData(chars, inputOffset, inputCount,
                                                    outputBuffer, 0, outputBuffer.Length,
                                                    true,
                                                    out var inputUsed,
                                                    out var outputUsed);

                outputLength += outputUsed;
                inputOffset  += inputUsed;
                inputCount   -= inputUsed;
            } while (!convertStatus);

            return(outputLength);
        }
Ejemplo n.º 4
0
    static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Console.WriteLine("A single argument should be provided:");
            Console.WriteLine("dotnet decode-base64 SGVsbG8gV29ybGQh");
            return;
        }

        try
        {
            var decodedString = Base64Decoder.Decode(args[0]);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Decoded string:");
            Console.ResetColor();
            Console.WriteLine(decodedString);
        }
        catch (FormatException e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.ResetColor();
        }
    }
Ejemplo n.º 5
0
 public static byte[] Decode(string input)
 {
     char[] data=input.ToCharArray();
     Base64Decoder myDecoder=new Base64Decoder(data);
     byte[] temp=myDecoder.GetDecoded();
     return temp;
 }
Ejemplo n.º 6
0
        public void TestBase64DecodePatterns()
        {
            var decoder = new Base64Decoder();
            var output  = new byte[4096];

            Assert.AreEqual(ContentEncoding.Base64, decoder.Encoding);

            for (int i = 0; i < base64EncodedPatterns.Length; i++)
            {
                decoder.Reset();
                var buf    = Encoding.ASCII.GetBytes(base64EncodedPatterns[i]);
                int n      = decoder.Decode(buf, 0, buf.Length, output);
                var actual = Encoding.ASCII.GetString(output, 0, n);
                Assert.AreEqual(base64DecodedPatterns[i], actual, "Failed to decode base64EncodedPatterns[{0}]", i);
            }

            for (int i = 0; i < base64EncodedLongPatterns.Length; i++)
            {
                decoder.Reset();
                var buf = Encoding.ASCII.GetBytes(base64EncodedLongPatterns[i]);
                int n   = decoder.Decode(buf, 0, buf.Length, output);

                for (int j = 0; j < n; j++)
                {
                    Assert.AreEqual(output[j], (byte)(j + i), "Failed to decode base64EncodedLongPatterns[{0}]", i);
                }
            }
        }
    public void GivenMinusAndUnderscore_WhenDecode_ThenReturnDecodedString(string input, string expected)
    {
        // Act
        var actual = Base64Decoder.Decode(input);

        // Assert
        Assert.Equal(expected, actual);
    }
    public void GivenRemovedPadding_WhenDecode_ThenReturnDecodedString(string input, string expected)
    {
        // Act
        var actual = Base64Decoder.Decode(input);

        // Assert
        Assert.Equal(expected, actual);
    }
        public void PaddingTest()
        {
            Base64Decoder decoder     = new Base64Decoder();
            char          testPadding = '?';

            decoder.Padding = testPadding;
            Assert.AreEqual(testPadding, decoder.Padding);
        }
        public void GetInputEncodingTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            System.Text.Encoding encoding = decoder.GetInputEncoding();
            Assert.IsNotNull(encoding);
            Assert.AreEqual(System.Text.Encoding.ASCII, encoding);
        }
        public void GetEncoderTest()
        {
            Base64Decoder decoder = new Base64Decoder();
            Encoder       encoder = decoder.GetEncoder();

            Assert.IsNotNull(encoder);
            Assert.IsInstanceOf(typeof(Base64Encoder), encoder);
        }
Ejemplo n.º 12
0
 public void GetDecodedTest()
 {
     char[] input = {'t', 'e', 's', 't', '\0'};
     var target = new Base64Decoder(input);
     byte[] expected = {181, 235, 45};
     byte[] actual = target.GetDecoded();
     CollectionAssert.AreEqual(expected, actual, "Kfd.Tools.Base64Decoder.GetDecoded did not return the expected value.");
 }
 //Decode a base64 string to common string
 public static string DecodeString4base(string EncodedString)
 {
     char[] data = EncodedString.ToCharArray();
     Base64Decoder myDecoder = new Base64Decoder(data);
     StringBuilder sb = new StringBuilder();
     byte[] temp = myDecoder.GetDecoded();
     sb.Append(System.Text.UTF8Encoding.UTF8.GetChars(temp));
     return sb.ToString();
 }
        public CatFactsTests()
        {
            var encodedUsername = ConfigurationManager.AppSettings["username"];
            var encodedPassword = ConfigurationManager.AppSettings["password"];

            var base64Decoder = new Base64Decoder();

            _username = base64Decoder.DecodeBase64String(encodedUsername);
            _password = base64Decoder.DecodeBase64String(encodedPassword);
        }
        public void ConstructorAlphabetTest()
        {
            char[] testAlphabet = new char[] {
                'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '1', '2', '3', '4', '5', '6',
                'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '7', '8', '9', '0', '[', ']'
            };
            Base64Decoder decoder = new Base64Decoder(testAlphabet);

            Common.AreEqual(testAlphabet, decoder.Alphabet);
            Assert.AreEqual(Base64Encoder.StandardPadding, decoder.Padding);
        }
    public void GivenValidBase64String_WhenDecode_ThenReturnDecodedString()
    {
        // Arrange
        const string input    = "SGVsbG8gV29ybGQh";
        const string expected = "Hello World!";

        // Act
        var actual = Base64Decoder.Decode(input);

        // Assert
        Assert.Equal(expected, actual);
    }
Ejemplo n.º 17
0
        public void TestGetEncoded03()
        {
            Base64Decoder baseDecoder = new Base64Decoder("testingwithoutequal".ToCharArray());

            byte[]        decodedbyte = baseDecoder.GetDecoded();
            Base64Encoder baseEncoder = new Base64Encoder(decodedbyte);

            //Test Procedure Call
            char[] encodedstr = baseEncoder.GetEncoded();
            //Post Condition Check
            //Assert.AreEqual("testing=", encodedstr.ToString());
        }
Ejemplo n.º 18
0
        public void TestBase64Decode()
        {
            using (var original = new MemoryStream()) {
                using (var file = File.OpenRead("../../TestData/encoders/photo.jpg"))
                    file.CopyTo(original, 4096);

                using (var decoded = new MemoryStream()) {
                    using (var file = File.OpenRead("../../TestData/encoders/photo.b64")) {
                        using (var filtered = new FilteredStream(file)) {
                            filtered.Add(DecoderFilter.Create(ContentEncoding.Base64));
                            filtered.CopyTo(decoded, 4096);
                        }
                    }

                    var buf0 = original.GetBuffer();
                    var buf1 = decoded.GetBuffer();
                    int n    = (int)original.Length;

                    Assert.AreEqual(original.Length, decoded.Length, "Decoded length is incorrect.");

                    for (int i = 0; i < n; i++)
                    {
                        Assert.AreEqual(buf0[i], buf1[i], "The byte at offset {0} does not match.", i);
                    }
                }
            }

            var decoder = new Base64Decoder();
            var output  = new byte[4096];

            Assert.AreEqual(ContentEncoding.Base64, decoder.Encoding);

            for (int i = 0; i < base64EncodedPatterns.Length; i++)
            {
                decoder.Reset();
                var buf    = Encoding.ASCII.GetBytes(base64EncodedPatterns[i]);
                int n      = decoder.Decode(buf, 0, buf.Length, output);
                var actual = Encoding.ASCII.GetString(output, 0, n);
                Assert.AreEqual(base64DecodedPatterns[i], actual, "Failed to decode base64EncodedPatterns[{0}]", i);
            }

            for (int i = 0; i < base64EncodedLongPatterns.Length; i++)
            {
                decoder.Reset();
                var buf = Encoding.ASCII.GetBytes(base64EncodedLongPatterns[i]);
                int n   = decoder.Decode(buf, 0, buf.Length, output);

                for (int j = 0; j < n; j++)
                {
                    Assert.AreEqual(output[j], (byte)(j + i), "Failed to decode base64EncodedLongPatterns[{0}]", i);
                }
            }
        }
Ejemplo n.º 19
0
        public void TestByteToChar01()
        {
            Base64Decoder baseDecoder = new Base64Decoder("testing".ToCharArray());

            byte[]        decodedbyte         = baseDecoder.GetDecoded();
            Base64Encoder baseEncoder         = new Base64Encoder(decodedbyte);
            Accessor      baseEncoderAccessor = ReflectionAccessor.Wrap(baseEncoder);
            //Test Procedure Call
            byte bb         = 89;
            char encodedstr = (char)baseEncoderAccessor.Call("ByteToChar", bb);
            //Post Condition Check
            //Assert.AreEqual("testing=", encodedstr.ToString());
        }
Ejemplo n.º 20
0
        public static Byte[] DecodeBase64(String data)
        {
            Byte[] buffer = Encoding.ASCII.GetBytes(data);

            Base64Decoder decoder = new Base64Decoder();

            Byte[] output = new Byte[decoder.EstimateOutputLength(buffer.Length)];

            Int32 length = decoder.Decode(buffer, 0, buffer.Length, output);

            MemoryStream stream = new MemoryStream(output, 0, length);

            return(stream.ToArray());
        }
Ejemplo n.º 21
0
        public void log(MaratonLog json)
        {
            if (json.errorMask != 0)
            {
                return;
            }

            using (MDB mdb = new MDB())
            {
                DbLog log = mdb.Find <DbLog>(x =>
                                             x.TaskID == json.taskID &&
                                             x.SubtaskID == json.subtaskID &&
                                             x.ServantID == json.servantID).FirstOrDefault();

                bool isNew = false;
                if (log == null)
                {
                    isNew = true;
                    log   = new DbLog();
                }

                log.ErrorMask = json.errorMask;

                Base64Decoder b64d            = new Base64Decoder();
                byte[]        encodingContent = b64d.GetDecoded(json.content);
                log.Content   = System.Text.ASCIIEncoding.Default.GetString(encodingContent);
                log.TaskID    = json.taskID;
                log.SubtaskID = json.subtaskID;
                log.ServantID = json.servantID;

                if (isNew)
                {
                    mdb.Insert <DbLog>(log);
                }
                else
                {
                    mdb.UpdateOne <DbLog>(x =>
                                          x.TaskID == json.taskID &&
                                          x.SubtaskID == json.subtaskID &&
                                          x.ServantID == json.servantID, log);
                }
            }
        }
Ejemplo n.º 22
0
        public bool SyncMailsFromServer(User user)
        {
            // ToDo create this Method Async
            this.user = UserRepository.Instance.GetUser(user.Email);
            this.user.GmailService = GoogleService.Instance;

            List <Message> messageList = this.LoadAllMessagesFromServer();


            messageList.ForEach((Message msg) =>
            {
                try
                {
                    // Loading Body Message of Mail
                    String body = Base64Decoder.Decode(msg.Payload.Parts[0].Parts[0].Body.Data);

                    // Deserialize Body to Ticket
                    Ticket ticket = DeserializeTicket.Deserialize(body);

                    // Save Ticket to local user List
                    this.user.TicketList.Add(ticket);
                }
                catch (FormatException e)
                {
                    //ToDo catch Deserialize Exception and inform Client
                    Console.WriteLine(e.Message);
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine(e.Message);
                }
            });

            // Updating DataBase with new Tickets
            if (DBService.Instance.UpdateUser(this.user))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 23
0
        public void TestOneOffDecoding(bool padded)
        {
            var(inputs, correctOutput) = GetData();
            if (!padded)
            {
                var padding = Encoding.ASCII
                              .GetBytes("=")
                              .First();
                inputs[0] = inputs[0]
                            .TakeWhile(x => x != padding)
                            .ToArray();
            }

            long length  = 0;
            var  state   = 0;
            var  decoder = new Base64Decoder();
            var  output  = new byte[decoder.RequiredBufferSize(inputs[0].Length)];

            decoder.ProcessBlock(inputs[0], output, ref length, ref state);
            length = (int)decoder.Finalize(output, length, state);
            output = output[..(int)length];
Ejemplo n.º 24
0
        public static string Decrypt(string text)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyBytes = encoding.GetBytes(HexMD5.Encode(KeyPairs.KEY_PAIR_2));

            byte[]        encodedTextBytes = encoding.GetBytes(text);
            Base64Decoder base64Decoder    = new Base64Decoder(encoding.GetChars(encodedTextBytes));

            byte[] decodedBytes = base64Decoder.GetDecoded();



            int length = decodedBytes.Length > keyBytes.Length ? keyBytes.Length : decodedBytes.Length;

            for (int i = 0; i < length; i++)
            {
                decodedBytes[i] -= keyBytes[i];
            }

            string decodedText = encoding.GetString(decodedBytes);

            return(decodedText.Substring(0, decodedText.Length - HexMD5.Encode(KeyPairs.KEY_PAIR_1).Length));
        }
Ejemplo n.º 25
0
 private void InitBase64Decoder()
 {
     if (_base64Decoder == null)
     {
         _base64Decoder = new Base64Decoder();
     }
     else
     {
         _base64Decoder.Reset();
     }
     _incReadDecoder = _base64Decoder;
 }
Ejemplo n.º 26
0
        public void TestGetDecoded01()
        {
            Base64Decoder baseDecoder = new Base64Decoder("testing=1".ToCharArray());

            byte[] decodedbyte = baseDecoder.GetDecoded();
        }
Ejemplo n.º 27
0
 void InitBase64Decoder() {
     if ( base64Decoder == null ) {
         base64Decoder = new Base64Decoder();
     }
     else {
         base64Decoder.Reset();
     }
     incReadDecoder = base64Decoder;
 }
Ejemplo n.º 28
0
        // Reads the contents of an element including markup and base64-decodes it into a byte buffer. Wellformedness checks are limited.
        // This method is designed to read base64-encoded large streams of bytes by calling it successively.
        internal int ReadBase64(byte[] array, int offset, int len)
        {
            Debug.Assert(_v1Compat, "XmlTextReaderImpl.ReadBase64 cannot be called on reader created via XmlReader.Create.");
            Debug.Assert(_outerReader is XmlTextReader);

            if (_parsingFunction == ParsingFunction.InIncrementalRead)
            {
                if (_incReadDecoder != _base64Decoder)
                { // mixing ReadBase64 with ReadChars or ReadBinHex
                    InitBase64Decoder();
                }
                return IncrementalRead(array, offset, len);
            }
            else
            {
                if (_curNode.type != XmlNodeType.Element)
                {
                    return 0;
                }
                if (_curNode.IsEmptyElement)
                {
                    _outerReader.Read();
                    return 0;
                }

                if (_base64Decoder == null)
                {
                    _base64Decoder = new Base64Decoder();
                }

                InitIncrementalRead(_base64Decoder);
                return IncrementalRead(array, offset, len);
            }
        }
 public Decoder(Base64Settings settings)
 {
     _codecDecoder = new Base64Decoder(settings);
 }
 internal DigestHeaderExtractor(Base64Decoder base64Decoder, DigestHeaderParser digestHeaderParser)
 {
     this.base64Decoder = base64Decoder;
      this.digestHeaderParser = digestHeaderParser;
 }
Ejemplo n.º 31
0
 public void ConstructorTest()
 {
     char[] input = {'t', 'e', 's', 't'};
     var target = new Base64Decoder(input);
     Assert.AreEqual(input[0], target.GetSource()[0]);
 }
 internal BasicAuthenticationCredentialsExtractor(Base64Decoder decoder, DecodedCredentialsExtractor extractor)
 {
     this.decoder = decoder;
      this.extractor = extractor;
 }
        public void InvalidCharacterTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            decoder.Decode("ABCDE!");
        }
        public string ScanWX()
        {
            {
                string result     = "";
                string postString = string.Empty;
                if (Request.HttpMethod.ToUpper() == "POST")
                {
                    using (Stream stream = System.Web.HttpContext.Current.Request.InputStream)
                    {
                        Byte[] postBytes = new Byte[stream.Length];
                        stream.Read(postBytes, 0, (Int32)stream.Length);
                        postString = Encoding.UTF8.GetString(postBytes);
                        //postBytes = CommonTool.Base64Decoder.GetDecoded(postString);
                        CommonTool.WriteLog.Write("postString: " + postString);
                        if (!string.IsNullOrEmpty(postString))
                        {
                            string SendToWx = string.Empty;

                            Dictionary <string, string> dic = CommonTool.JsonHelper.GetParms2(postString);
                            CommonTool.WriteLog.Write("content === " + dic["content"]);
                            byte[] aryData    = new Base64Decoder().GetDecoded(dic["content"]);
                            string DE_content = Encoding.UTF8.GetString(aryData);

                            int index = DE_content.IndexOf('{');
                            DE_content = DE_content.Substring(index);
                            CommonTool.WriteLog.Write("DE_content === " + DE_content);
                            Dictionary <string, string> dic2 = CommonTool.JsonHelper.GetParms2(DE_content);
                            string device_id   = dic["device_id"];
                            string device_type = dic["device_type"];
                            string msg_id      = dic["msg_id"];
                            string msg_type    = dic["msg_type"];
                            string open_id     = dic["open_id"];
                            string session_id  = dic["session_id"];
                            string bat         = dic2["bat"];
                            string hrs         = dic2["hrs"];
                            string step        = dic2["step"];
                            string lslt        = dic2["lslt"];
                            string dslt        = dic2["dslt"];
                            string btmp        = dic2["btmp"];
                            string hbld        = dic2["hbld"];
                            string lbld        = dic2["lbld"];
                            string oxyg        = dic2["oxyg"];
                            string atmp        = dic2["atmp"];
                            Device dev         = new Device();
                            bool   flag        = dev.saveDeviceInfo(device_id, device_type, msg_id, msg_type, open_id, session_id, bat, hrs, step, lslt, dslt, btmp, hbld, lbld, oxyg, atmp);
                            if (flag)
                            {
                                User user = new User();
                                user.AddUser(device_id, open_id);
                            }
                            //这里写方法解析Xml
                            XmlDocument xml = new XmlDocument();
                            xml.LoadXml(postString);
                            XmlElement xmlElement = xml.DocumentElement;
                            //这里进行判断MsgType
                            switch (xmlElement.SelectSingleNode("//MsgType").InnerText)
                            {
                            case "text":
                                XmlNode content = xmlElement.SelectSingleNode("//Content");
                                CommonTool.WriteLog.Write("content: " + xmlElement.SelectSingleNode("//Content").InnerText);
                                SendToWx = WxText.GetWxTextXml(postString);
                                break;
                            }
                            if (!string.IsNullOrEmpty(SendToWx))
                            {
                                System.Web.HttpContext.Current.Response.Write(SendToWx);
                                System.Web.HttpContext.Current.Response.End();
                            }
                            else
                            {
                                result = "回传数据为空";
                                CommonTool.WriteLog.Write(result);
                            }
                        }
                        else
                        {
                            result = "微信推送的数据为:" + postString;
                            CommonTool.WriteLog.Write(result);
                        }
                    }
                }
                else if (Request.HttpMethod.ToUpper() == "GET")
                {
                    string token = "qweasdzxc";//从配置文件获取Token
                    if (string.IsNullOrEmpty(token))
                    {
                        result = string.Format("微信Token配置项没有配置!");
                        CommonTool.WriteLog.Write(result);
                    }
                    string echoString = System.Web.HttpContext.Current.Request.QueryString["echoStr"];
                    string signature  = System.Web.HttpContext.Current.Request.QueryString["signature"];
                    string timestamp  = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
                    string nonce      = System.Web.HttpContext.Current.Request.QueryString["nonce"];
                    if (CheckSignature(token, signature, timestamp, nonce))
                    {
                        if (!string.IsNullOrEmpty(echoString))
                        {
                            System.Web.HttpContext.Current.Response.Write(echoString);
                            System.Web.HttpContext.Current.Response.End();
                            result = string.Format("微信Token配置成功,你已成为开发者!");
                            CommonTool.WriteLog.Write(result + "\t\nechoString:" + echoString + "  " + signature + "  " + timestamp + "  " + nonce);
                            return(echoString);
                        }
                    }
                }
                result = string.Format("页面被访问,没有请求数据!");
                CommonTool.WriteLog.Write(result);
                return(result);
            }
        }
        public void AlphabetNullTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            decoder.Alphabet = null;
        }
Ejemplo n.º 36
0
        public static void ClientService()
        {
            //
            try
            {
                ClientClass   C        = CC;
                NetworkStream ns       = C.Client.GetStream();
                bool          LoggedIn = false;
                //StreamReader sr = new StreamReader(
                while (true)
                {
                    Thread.Sleep(5);
                    //:D
                    //Console.Write(400);

                    if (C.Client.Available >= 3)
                    {
                        byte[] buffer = new byte[C.Client.Available];
                        //ns.Read(buffer,0,buffer.Length);
                        C.Client.Client.Receive(buffer);
                        Base64Decoder B64 = new Base64Decoder(E.GetChars(buffer));
                        buffer = B64.GetDecoded();
                        string data = E.GetString(buffer);

                        //Console.WriteLine(data);
                        bool o = C.LoggedIn;
                        if (C.Decode(data, out data, EncodingType.CSEnc))
                        {
                        }
                        else
                        {
                            //Limited options for the user to have...
                            string[] la = new string[1];
                            if (data.Contains("|"))
                            {
                                la = data.Replace("||", Convert.ToChar(2).ToString()).Split('|');
                                for (int I = 0; I < la.Length; I++)
                                {
                                    la[I] = la[I].Replace(Convert.ToChar(2).ToString(), "|");
                                }
                            }
                            else
                            {
                                la[0] = data;
                            }
                            if (o)
                            {
                                //Full capability...
                                if (data.StartsWith("cht|") && !(C.Permission.Contains("CB")))
                                {
                                    //Send chat to the other clients...}
                                    foreach (ClientClass a in Clients)
                                    {
                                        a.SendPacket("cht|(" + DateTime.Now.Hour + DateTime.Now.Minute + ") " + C.name + "[" + C.Permission + "]: " + la[1], EncodingType.CSEnc);
                                    }
                                }
                                else if (data.StartsWith("file|") && (C.Permission.Contains("DEV")))
                                {
                                    //since we have perm, lets continue...
                                    if (data.StartsWith("file|w|"))
                                    {
                                    }                                    //Write the file
                                }
                                else if (data.StartsWith("sqlq|"))
                                {
                                    //sql query + return
                                    string[] sp  = data.Split('|');
                                    string   CRC = sp[1];
                                    string   dar = "";
                                    string   y   = sp[2];
                                    if (C.CheckPermissions(ref y, true, true))
                                    {
                                        //Console.WriteLine("TEST!");
                                        try
                                        {
                                            Com.CommandText = y;
                                            System.Data.SqlClient.SqlDataReader mcm = Com.ExecuteReader();
                                            while (mcm.Read())
                                            {
                                                string ao = "";
                                                for (int I = 0; I < mcm.FieldCount; I++)
                                                {
                                                    string d = Convert.ToChar(2) + "";
                                                    if (I == mcm.FieldCount - 1)
                                                    {
                                                        d = "";
                                                    }
                                                    if (mcm.IsDBNull(I))
                                                    {
                                                        ao += d;
                                                    }
                                                    else
                                                    {
                                                        ao += Convert.ToString(mcm.GetValue(I)) + d;
                                                    }
                                                }
                                                dar += ao + Convert.ToChar(1);
                                            }
                                            mcm.Close();
                                        }
                                        catch (Exception e) { Console.WriteLine(e.Message); }
                                        try
                                        {
                                            dar = dar.Remove(dar.Length - 1, 1);
                                        }
                                        catch { }
                                        //Console.WriteLine(dar);
                                        C.Client.SendBufferSize = ("sqlq|" + CRC + "|" + dar).Length;
                                        C.SendPacket("sqlq|" + CRC + "|" + dar, EncodingType.CSEnc);
                                    }
                                    else
                                    {
                                        C.SendPacket("sqlq|" + CRC + "|", EncodingType.CSEnc); C.SendPacket("noper", EncodingType.CSEnc);
                                    }
                                }
                                else if (data.StartsWith("sqlc|"))
                                {
                                    //Sql query
                                    string[] sp = data.Split('|');
                                    string   y1 = sp[1];
                                    if (C.CheckPermissions(ref sp[1], true, true))
                                    {
                                        //Com.CommandText = y1;
                                        //Com.ExecuteNonQuery();
                                    }
                                    else
                                    {
                                        C.SendPacket("noper", EncodingType.CSEnc);
                                    }
                                    Com.CommandText = y1;
                                    Com.ExecuteNonQuery();
                                }
                                else if (data.StartsWith("logout|")) //separators...|
                                {
                                    C.name     = "anon";
                                    C.LoggedIn = false;
                                    LoggedIn   = false;
                                }
                                else if (data.StartsWith("DBNames|")) //Client is asking for the set DB names...
                                {
                                    C.SendPacket("DBNames|" + GetSetting("SQLAccDB") + "|" + GetSetting("SQLGameDB"), EncodingType.CSEnc);
                                }
                                else
                                {
                                    if (C.CheckPermissions(ref data, false, false))
                                    {
                                    }
                                    else
                                    {
                                        C.SendPacket("noper", EncodingType.CSEnc);
                                    }
                                }
                            }
                            if (data.StartsWith("login|")) //separators...|
                            {
                                try
                                {
                                    string[] l = data.Split('|');
                                    Com.CommandText = "SELECT * FROM [" + GetSetting("SQLAccDB") + "].[dbo].[account_login] WHERE [name] = '" + l[1] + "'";
                                    System.Data.SqlClient.SqlDataReader dr = Com.ExecuteReader();
                                    bool UserPassed = false, ISGM = false;
                                    if (dr.Read())
                                    {
                                        if (dr.GetString(2) == l[2])
                                        {
                                            //Password has passed also.
                                            UserPassed = true;
                                        }
                                    }
                                    dr.Close();
                                    Com.CommandText = "SELECT * FROM [" + GetSetting("SQLGameDB") + "].[dbo].[account] WHERE [act_name] = '" + l[1] + "'";
                                    dr = Com.ExecuteReader();
                                    if (dr.Read())
                                    {
                                        if (Convert.ToString(dr.GetValue(2)) == "99")
                                        {
                                            ISGM = true;
                                        }
                                    }
                                    dr.Close();
                                    C.GetPermissions(l[1], ISGM);
                                    //Console.ForegroundColor = ConsoleColor.Red;
                                    //Console.WriteLine(C.Permission);
                                    if (UserPassed && !(C.Permission.StartsWith("X"))) //People that still have "X" will not pass!!!
                                    {
                                        C.SendPacket("login|true", EncodingType.CSEnc);
                                        C.LoggedIn = true;
                                        LoggedIn   = true; //this doesn't work? wtf..lol..?
                                        C.name     = l[1];
                                        Console.WriteLine(C.name + " Logged in. IP: " + C.Client.Client.RemoteEndPoint.ToString() + " Perm: " + C.Permission);
                                        LG("Logged_In", DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + DateTime.Now.Year + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + " - User[" + C.name + "] Logs in. IP: " + C.Client.Client.RemoteEndPoint.ToString());
                                    }
                                    else
                                    {
                                        C.SendPacket("login|false", EncodingType.CSEnc);
                                        Console.WriteLine(C.name + " Failed to log in with '" + l[1] + "' as a username. IP: " + C.Client.Client.RemoteEndPoint.ToString());
                                        LG("Logged_Fail", DateTime.Now.Date + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + " - User[" + l[1] + "] Unable to log in. IP: " + C.Client.Client.RemoteEndPoint.ToString());
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// Base64编码解码
        /// </summary>
        /// <param name="srcString">编码字符串</param>
        /// <param name="encoding">系统字符编码方式</param>
        /// <returns>解码字符串</returns>
        public static string Base64Decode(string srcString, System.Text.Encoding encoding)
        {
            if (null == srcString || string.Empty == srcString)
                return string.Empty;

            string result = string.Empty;
            Base64Decoder dc = new Base64Decoder();
            byte[] decodeTemp = dc.GetDecoded(srcString);
            result = encoding.GetString(decodeTemp);

            return result;
        }
Ejemplo n.º 38
0
        private int IncrementalReadHelper(object destBuffer, int destIndex, IncrementalReadType readType, int srcIndex, int count) {
            switch (readType) {
                case IncrementalReadType.Chars:
                    char[] charBuffer = destBuffer as char[];
                    Array.Copy(_achText, srcIndex, charBuffer, destIndex, _nPos - srcIndex);
                    return destIndex + (_nPos - srcIndex);

                case IncrementalReadType.Base64:
                    byte[] base64ByteBuffer = destBuffer as byte[];
                    if (null == _Base64Decoder) {
                        _Base64Decoder = new Base64Decoder();
                    }
                    return destIndex + _Base64Decoder.DecodeBase64(_achText, srcIndex, _nPos, base64ByteBuffer, destIndex, count, false);

                case IncrementalReadType.BinHex:
                    byte[] binhexByteBuffer = destBuffer as byte[];
                    if (null == _BinHexDecoder) {
                        _BinHexDecoder = new BinHexDecoder();
                    }
                    return destIndex + _BinHexDecoder.DecodeBinHex(_achText, srcIndex, _nPos, binhexByteBuffer, destIndex, count, false);
                default:
                    throw new XmlException(Res.Xml_InternalError);
            } // switch

        }
        public void IsCaseSensitiveTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            Assert.IsTrue(decoder.IsCaseSensitive);
        }
Ejemplo n.º 40
0
		public void TestBase64Decode ()
		{
			using (var original = new MemoryStream ()) {
				using (var file = File.OpenRead ("../../TestData/encoders/photo.jpg"))
					file.CopyTo (original, 4096);

				using (var decoded = new MemoryStream ()) {
					using (var file = File.OpenRead ("../../TestData/encoders/photo.b64")) {
						using (var filtered = new FilteredStream (file)) {
							filtered.Add (DecoderFilter.Create (ContentEncoding.Base64));
							filtered.CopyTo (decoded, 4096);
						}
					}

					var buf0 = original.GetBuffer ();
					var buf1 = decoded.GetBuffer ();
					int n = (int) original.Length;

					Assert.AreEqual (original.Length, decoded.Length, "Decoded length is incorrect.");

					for (int i = 0; i < n; i++)
						Assert.AreEqual (buf0[i], buf1[i], "The byte at offset {0} does not match.", i);
				}
			}

			var decoder = new Base64Decoder ();
			var output = new byte[4096];

			Assert.AreEqual (ContentEncoding.Base64, decoder.Encoding);

			for (int i = 0; i < base64EncodedPatterns.Length; i++) {
				decoder.Reset ();
				var buf = Encoding.ASCII.GetBytes (base64EncodedPatterns[i]);
				int n = decoder.Decode (buf, 0, buf.Length, output);
				var actual = Encoding.ASCII.GetString (output, 0, n);
				Assert.AreEqual (base64DecodedPatterns[i], actual, "Failed to decode base64EncodedPatterns[{0}]", i);
			}

			for (int i = 0; i < base64EncodedLongPatterns.Length; i++) {
				decoder.Reset ();
				var buf = Encoding.ASCII.GetBytes (base64EncodedLongPatterns[i]);
				int n = decoder.Decode (buf, 0, buf.Length, output);

				for (int j = 0; j < n; j++)
					Assert.AreEqual (output[j], (byte) (j + i), "Failed to decode base64EncodedLongPatterns[{0}]", i);
			}
		}
        public void AlphabetShortTest()
        {
            Base64Decoder decoder = new Base64Decoder();

            decoder.Alphabet = new char[1];
        }