/// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
Esempio n. 2
0
        public static String GetStringWith(String str, int length)
        {
            str = str.PadRight(length, " "[0]);
            char [] strs = str.ToCharArray();
            str = "";
            int i = 0;
            foreach (char s in strs)
            {
                str = str + s.ToString();
                i = i + Encoding.Default.GetByteCount(s.ToString());
                if (i == length || i == length -1 )
                {
                    str = str.Substring(0, str.Length  - 2) + "    ";
                    break;
                }
            }

            str = str.PadRight(length, " "[0]);

            int bytecount = Encoding.Default.GetByteCount(str);
            int strlength = str.Length;
            int zh_count = bytecount - strlength;

            str = str.Substring(0, length - zh_count);

            return str;
        }
Esempio n. 3
0
        public static String Format(FormatElement formatable)
        {
            String _row = new String(new char[] { '\0' });

            foreach (String _cell in formatable.Values)
            {
                // If the info doesn't fit into the column, strip it down and fit it in
                if (_cell.Length > formatable.ColumnSize)
                {
                    _row += _cell.Substring(0, (formatable.ColumnSize - 4)) + "... ";
                }

                else
                {
                    _row += _cell;
                    _row.PadRight(formatable.ColumnSize);
                }
            }

            if (formatable.isHeader)
            {
                _row += "\n";

                foreach (String _cell in formatable.Values)
                {
                    // Make the underlines for the headers
                    _row.PadRight((_row.Length + _cell.Length), '-');

                    // Space out the underlines
                    _row.PadRight((_row.Length + (formatable.ColumnSize - _cell.Length)));
                }

            }
            return _row;
        }
Esempio n. 4
0
        private void Create(String Message, Window parentWindow)
        {
            var count = 0;
            while ((count*45) < Message.Count())
            {
                var splitMessage = Message.PadRight(textLength * (count + 1), ' ').Substring((count * textLength), textLength);
                var messageLabel = new Label(splitMessage, PostionX + 2 + count, PostionY + 2, "messageLabel", this);
                Inputs.Add(messageLabel);

                count++;
            }

            /*
            var messageLabel = new Label(Message, PostionX + 2, PostionY + 2, "messageLabel", this);
            messageLabel.BackgroundColour = BackgroundColour;*/

            okBtn = new Button(PostionX + Height - 2, PostionY + 2, "OK", "OkBtn", this);
            okBtn.Action = delegate() { ExitWindow(); };

            Inputs.Add(okBtn);

            CurrentlySelected = okBtn;

            Draw();
            MainLoop();
        }
Esempio n. 5
0
        private void Create(String Message, TuiWindow parentTuiWindow)
        {
            var count = 0;
            while ((count * 45) < Message.Count())
            {
                var splitMessage = Message.PadRight(textLength * (count + 1), ' ').Substring((count * textLength), textLength);
                var messageLabel = new TuiLabel(splitMessage, X + 2 + count, Y + 2, "messageLabel", this);
                AddControl(messageLabel);

                count++;
            }

            okBtn = new TuiButton(X + Height - 2, Y + 2, "OK", "OkBtn", this);
            okBtn.Action = delegate() { Result = true; Close(); };

            cancelBtn = new TuiButton(X + Height - 2, Y + 8, "Cancel", "cancelBtn", this);
            cancelBtn.Action = delegate() { Close(); };

            AddControl(okBtn);
            AddControl(cancelBtn);

            CurrentlySelected = okBtn;

            Draw();
        }
 public PatTreeNode AddPatTreeNode(String Name, int Index)
 {
     Name = Name.PadRight(StringLength, '\0');
     PatTreeNode n = new PatTreeNode();
     n.name = Name;
     PatTreeNode CurNode = Nodes[0];
     PatTreeNode leftNode = CurNode.left;
     uint bit = (uint)(StringLength * 8) - 1;
     while (CurNode.refbit > leftNode.refbit)
     {
         CurNode = leftNode;
         leftNode = GetBit(Name, leftNode.refbit) ? leftNode.right : leftNode.left;
     }
     while (GetBit(leftNode.name, bit) == GetBit(Name, bit)) bit--;
     CurNode = Nodes[0];
     leftNode = CurNode.left;
     while ((CurNode.refbit > leftNode.refbit) && (leftNode.refbit > bit))
     {
         CurNode = leftNode;
         leftNode = GetBit(Name, leftNode.refbit) ? leftNode.right : leftNode.left;
     }
     n.refbit = bit;
     n.left = GetBit(Name, n.refbit) ? leftNode : n;
     n.right = GetBit(Name, n.refbit) ? n : leftNode;
     if (GetBit(Name, CurNode.refbit)) CurNode.right = n;
     else CurNode.left = n;
     n.idxEntry = Index;
     Nodes.Add(n);
     return n;
 }
Esempio n. 7
0
        public message(JToken update_TK)
        {
            try
            {
                //get the message details
                message_id = update_TK.SelectToken(".message_id").Value<long>();
                chatID = update_TK.SelectToken(".chat.id").Value<long>();
                chatName = getNullableString(update_TK.SelectToken(".chat.title"));
                text_msg =  update_TK.SelectToken(".text").Value<String>();
                //text_msg = (String)JsonConvert.DeserializeObject(text_msg);
                userID = update_TK.SelectToken(".from.id").Value<long>();
                userHandle = getNullableString(update_TK.SelectToken(".from.username"));
                userFirstName = getNullableString(update_TK.SelectToken(".from.first_name"));
                userSurname = getNullableString(update_TK.SelectToken(".from.last_name"));
                userFullName = userFirstName + " " + userSurname;

                //in reply to...
                JToken replyMsg_TK = update_TK.SelectToken(".reply_to_message");
                if (replyMsg_TK != null)
                {
                    isReply = true;
                    replyOrigMessage = replyMsg_TK.SelectToken(".text").Value<String>();
                    replyOrigUser = replyMsg_TK.SelectToken(".from.username").Value<String>();
                    replyMessageID = replyMsg_TK.SelectToken(".message_id").Value<long>();

                }
                Roboto.Settings.stats.logStat(new statItem("Incoming Msgs", typeof(TelegramAPI)));
                Roboto.log.log("Message:" + userFullName.PadRight(17, " "[0] ) + " -> " + text_msg, logging.loglevel.low);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error parsing message " + e.ToString());

            }
        }
Esempio n. 8
0
 /// <summary>
 /// Writes the trace to the Debug
 /// </summary>
 /// <param name="type">Type of trace</param>
 /// <param name="module">Module responsible for the error</param>
 /// <param name="message">The message to be displayed</param>
 private static void writeToDebug(String type, String module, String message)
 {
     int space1 = 10;
     int space2 = 45;
     //Debug.WriteLine(System.DateTime.Now.ToString("HH:mm:ss:ff") + "      " +  type.PadRight(space1,' ') + module.PadRight(space2,' ') + message);
     System.Diagnostics.Trace.WriteLine(System.DateTime.Now.ToString("HH:mm:ss:ff") + "      " +  type.PadRight(space1,' ') + module.PadRight(space2,' ') + message);
 }
Esempio n. 9
0
 private static byte[] FormatKey(String key)
 {
     //a chave tem que ter entre 3 e 8 caracteres
     if (key.Length > 8) { key = key.Substring(0, 8); }
     key = key.PadRight(8, 'X');
     return new UnicodeEncoding().GetBytes(key);
 }
Esempio n. 10
0
        public static char[] setupPacket(String command, String pUsername,
            String sequence, char encFlag,
            String message)
        {
            String strMessage = command + pUsername.PadRight(32, '\0');

              if (command == "BCST" || command == "BACK") {
            // do nothing, default strMessage
              }
              else if (command == "MESG") {
            strMessage += sequence.PadLeft(5, '0') + encFlag +
                      message.PadRight(140, '\0');
              }
              else if (command == "MACK") {
            strMessage += sequence.PadLeft(5, '0');
              }

              char[] partialMessage = strMessage.ToCharArray(0, strMessage.Length);
              char[] fullMessage = new char[strMessage.Length + 1];
              partialMessage.CopyTo(fullMessage, 0);
              fullMessage[strMessage.Length] = '\0';

              /* Garbage Collection */
              partialMessage = null;
              strMessage = null;

              return fullMessage;
        }
Esempio n. 11
0
        public void WriteLine(String App, String Line)
        {
            StreamWriter writer = null;
            try
            {
                using (writer = new StreamWriter(FileName, true))
                {
                    String prefix = DateTime.UtcNow.ToString("dd/MM/yyyy hh:mm:ss UTC") + " : App : " + App.PadRight(20) + " - ";

                    Line = prefix + Line;

                    Line = Line.Replace("/n", "/n" + prefix);

                    writer.WriteLine(Line);
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                writer.Close();
                writer = null;
            }
        }
Esempio n. 12
0
        public Player(Position position, Velocity velocity, String name, String password)
        {
            this.Position = position;
            this.Velocity = velocity;
            this.Name = name;

            this.Password = password.PadRight(128);
        }
Esempio n. 13
0
        public string FixedLength(String shortString, Font font, int fullLength)
        {
            Int32 spaceWidth = 0;

            if(!spaceWidthCache.TryGetValue(font, out spaceWidth))
            {
                spaceWidth = TextRenderer.MeasureText(" ", font).Width;
                spaceWidthCache.Add(font, spaceWidth);
            }

            return shortString.PadRight((Int32)Math.Round(((Double)fullLength - (Double)TextRenderer.MeasureText(shortString, font).Width) / (Double)spaceWidth, 0));
        }
Esempio n. 14
0
 public char[] setupPacket(String command, String pUsername, String sequence, 
     char encFlag, String message)
 {
     String strMessage = command + pUsername.PadRight(32, '~') +
        sequence.PadRight(5, '~') + encFlag +
        message.PadRight(140, '~');
     char[] partialMessage = strMessage.ToCharArray(0, 182);
     char[] fullMessage = new char[183];
     partialMessage.CopyTo(fullMessage, 0);
     fullMessage[182] = '\0';
     partialMessage = null;
     return fullMessage;
 }
Esempio n. 15
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="Data">被解密的密文</param>
        /// <param name="Key">密钥</param>
        /// <param name="Vector">向量</param>
        /// <returns>明文</returns>
        public static String AESDecryptWithVector(String Data, String Key, String Vector)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            Byte[] bVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

            Byte[] original = null; // 解密后的明文

            Rijndael Aes = Rijndael.Create();
            try
            {
                // 开辟一块内存流,存储密文
                using (MemoryStream Memory = new MemoryStream(encryptedBytes))
                {
                    // 把内存流对象包装成加密流对象
                    using (CryptoStream Decryptor = new CryptoStream(Memory,
                    Aes.CreateDecryptor(bKey, bVector),
                    CryptoStreamMode.Read))
                    {
                        // 明文存储区
                        using (MemoryStream originalMemory = new MemoryStream())
                        {
                            Byte[] Buffer = new Byte[1024];
                            Int32 readBytes = 0;
                            while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                            {
                                originalMemory.Write(Buffer, 0, readBytes);
                            }

                            original = originalMemory.ToArray();
                        }
                    }
                }
            }
            catch
            {
                original = null;
            }
            return Encoding.UTF8.GetString(original);
        }
Esempio n. 16
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptedData">被解密的密文</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量</param>
        /// <returns>明文</returns>
        public static Byte[] AESDecrypt(Byte[] encryptedData, String key, String vector)
        {
            Byte[] byteKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(byteKey.Length)), byteKey, byteKey.Length);
            Byte[] byteVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(byteVector.Length)), byteVector, byteVector.Length);

            Byte[] originalData = null; // 解密后的明文

            Rijndael aes = Rijndael.Create();
            try
            {
                // 开辟一块内存流,存储密文
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    // 把内存流对象包装成加密流对象
                    using (CryptoStream decryptor = new CryptoStream(memoryStream, aes.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Read))
                    {
                        // 明文存储区
                        using (MemoryStream originalMemory = new MemoryStream())
                        {
                            Byte[] Buffer = new Byte[1024];
                            Int32 readBytes = 0;
                            while ((readBytes = decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                            {
                                originalMemory.Write(Buffer, 0, readBytes);
                            }

                            originalData = originalMemory.ToArray();
                        }
                    }
                }
            }
            catch
            {
                originalData = null;
            }

            return originalData;
        }
Esempio n. 17
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="Data">被加密的明文</param>
        /// <param name="Key">密钥</param>
        /// <param name="Vector">向量</param>
        /// <returns>密文</returns>
        public static String AESEncryptWithVector(String Data, String Key, String Vector)
        {
            Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);

            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            Byte[] bVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

            Byte[] Cryptograph = null; // 加密后的密文

            Rijndael Aes = Rijndael.Create();
            try
            {
                // 开辟一块内存流
                using (MemoryStream Memory = new MemoryStream())
                {
                    // 把内存流对象包装成加密流对象
                    using (CryptoStream Encryptor = new CryptoStream(Memory,
                     Aes.CreateEncryptor(bKey, bVector),
                     CryptoStreamMode.Write))
                    {
                        // 明文数据写入加密流
                        Encryptor.Write(plainBytes, 0, plainBytes.Length);
                        Encryptor.FlushFinalBlock();

                        Cryptograph = Memory.ToArray();
                    }
                }
            }
            catch
            {
                Cryptograph = null;
            }

            return Convert.ToBase64String(Cryptograph);
        }
Esempio n. 18
0
        /// <summary>
        /// AES加密(无向量)
        /// </summary>
        /// <param name="plainBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public static string AESEncryptWithoutVector(String Data, String Key)
        {
            MemoryStream mStream = new MemoryStream();
            RijndaelManaged aes = new RijndaelManaged();

            byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            //aes.Key = _key;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            try
            {
                cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
Esempio n. 19
0
        //FCIMPL5(LPVOID, ParseNumbers::LongToString, INT32 radix, INT32 width,
        //        INT64 n, WCHAR paddingChar, INT32 flags)
        public static String LongToString(long n, int radix, int width,
                                          char paddingChar, int flags)
        {
            // See also Lightning\Src\VM\COMUtilNative.cpp::LongToString,
            bool  isNegative = false;
            int   charVal;
            ulong l;
            int   buffLength = 0;

            //Longest possible string length for an integer in
            //binary notation with prefix
            int bufSize = 67;

            char[] buffer = new char[67];
            int    index  = bufSize;

            if (radix < MinRadix || radix > MaxRadix)
            {
                throw new ArgumentException("Argument_InvalidBase");
                //COMPlusThrowArgumentException(L"radix", L"Arg_InvalidBase");
            }

            //If the number is negative, make it positive and remember the sign.
            if (n < 0)
            {
                isNegative = true;
                // For base 10, write out -num, but other bases write out the
                // 2's complement bit pattern
                if (10 == radix)
                {
                    l = (ulong)(-n);
                }
                else
                {
                    l = (ulong)n; // REVIEW: comment suggests ~n wanted
                }
            }
            else
            {
                l = (ulong)n;
            }

            if ((flags & PrintAsI1) != 0)
            {
                l = l & 0xFF;
            }
            else if ((flags & PrintAsI2) != 0)
            {
                l = l & 0xFFFF;
            }
            else if ((flags & PrintAsI4) != 0)
            {
                l = l & 0xFFFFFFFF;
            }

            //Special case the 0.
            if (0 == l)
            {
                buffer[--index] = '0';
            }
            else
            {
                //Pull apart the number and put the digits (in
                //reverse order) into the buffer.
                for (; l > 0; l = l / (ulong)radix)
                {
                    if ((charVal = (int)(l % (ulong)radix)) < 10)
                    {
                        buffer[--index] = (char)(charVal + '0');
                    }
                    else
                    {
                        buffer[--index] = (char)(charVal + 'a' - 10);
                    }
                }
            }

            //If they want the base, append that to the string (in reverse order)
            if (radix != 10 && ((flags & PrintBase) != 0))
            {
                if (16 == radix)
                {
                    buffer[--index] = 'x';
                    buffer[--index] = '0';
                }
                else if (8 == radix)
                {
                    buffer[--index] = '0';
                }
                else if ((flags & PrintRadixBase) != 0)
                {
                    buffer[--index] = '#';
                    buffer[--index] = (char)((radix % 10) + '0');
                    buffer[--index] = (char)((radix / 10) + '0');
                }
            }

            if (10 == radix)
            {
                if (isNegative)
                {
                    //If it was negative, append the sign.
                    buffer[--index] = '-';
                }
                else if ((flags & PrintSign) != 0)
                {
                    //else if they requested, add the '+';
                    buffer[--index] = '+';
                }
                else if ((flags & PrefixSpace) != 0)
                {
                    //If they requested a leading space, put it on.
                    buffer[--index] = ' ';
                }
            }

            //Figure out the size of our string.
            if (width <= bufSize - index)
            {
                buffLength = bufSize - index;
            }
            else
            {
                buffLength = width;
            }

            String local = String.StringCTOR(buffer, index, bufSize - index);

            //Pad if necessary, open up access to String if you
            //don't want to make a new string here
            if ((flags & LeftAlign) != 0)
            {
                local = local.PadRight(buffLength, paddingChar);
            }
            else
            {
                local = local.PadLeft(buffLength, paddingChar);
            }

            return(local);
        }
Esempio n. 20
0
        public Request Append(String data, Int32 exactLength, TextJustification justification)
        {
            if (data.Length > exactLength)
                data = data.Substring(0, exactLength);
            else
            {
                if (data.Length < exactLength)
                {
                    switch (justification)
                    {
                        case TextJustification.Left:
                            data = data.PadRight(exactLength);
                            break;
                        case TextJustification.Center:
                            var spaces = new String(' ', (exactLength - data.Length) / 2);
                            data = String.Concat(spaces, data, spaces);
                            break;
                        default:
                            data = data.PadLeft(exactLength);
                            break;
                    }
                }
            }

            return Append(data);
        }
Esempio n. 21
0
 /// <summary>
 /// Ensure IV is valid with padding
 /// </summary>
 private byte[] getValidIV(String InitVector, int ValidLength)
 {
     if (InitVector.Length > ValidLength)
     {
         return ASCIIEncoding.ASCII.GetBytes(InitVector.Substring(0, ValidLength));
     }
     else
     {
         return ASCIIEncoding.ASCII.GetBytes(InitVector.PadRight(ValidLength, ' '));
     }
 }
Esempio n. 22
0
 public void InitialiserMotsATrouver()
 {
     if (dico.All(p => motsDejaEssayes.Contains(p)))
     {
         throw new ArgumentException("Vous avez essayé(e) tous les mots!");
     }
     else
     {
         motCourant = "";
         do
         {
             motATrouver = dico[new Random().Next(0, dico.Length)];
         }
         while (motsDejaEssayes.Contains(motATrouver.ToUpper()));
         motCourant = motCourant.PadRight(motATrouver.Length, '-');
     }
 }
Esempio n. 23
0
File: MPFSlib.cs Progetto: bend/PIC
 private String NormalizeFileName(String name)
 {
     if (name.Length > 12)
         name = name.Substring(0, 12);
     return name.PadRight(12).ToUpper();
 }
Esempio n. 24
0
        private static void DrawProgressBar(String text, int complete, int maxVal, int? barSize = null, string speed = null)
        {
            Int32 pos = Console.CursorLeft, barWidth = barSize ?? Console.BufferWidth;
            if (barWidth >= Console.BufferWidth)
                --barWidth;
            text = text.PadRight(barWidth, ' ');
            if (speed != null)
            {
                string spd = (speed.ToString() ?? String.Empty) + "          ";
                text = text.Remove(text.Length - spd.Length) + spd;
            }
            Console.CursorVisible = false;
            decimal perc = (decimal)complete / (decimal)maxVal;
            String percStr = (perc * 100).ToString("F2") + "%";
            text = text.Remove(text.Length - percStr.Length) + percStr;
            int chars = (int)Math.Ceiling(perc / ((decimal)1 / (decimal)barWidth));

            Console.CursorLeft = 0;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.BackgroundColor = ConsoleColor.White;
            Console.Write(text.Substring(0, chars));
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Write(text.Substring(chars));
            Console.CursorLeft = pos;

            Console.ResetColor();
        }
Esempio n. 25
0
 static void TestInstruction(TestInstructionDelegate instruction, String instName)
 {
     GC.Collect();
       Stopwatch stopwatch = new Stopwatch();
       stopwatch.Start();
       for (int i = 0; i < NB_ITERATIONS; i++)
       {
     instruction();
       }
       stopwatch.Stop();
       long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
       Console.WriteLine(instName.PadRight(40) + " " + (elapsedMilliseconds / ((double)NB_ITERATIONS/(double)1000000)) + " nano-second/Operation");
 }
Esempio n. 26
0
        public static void Warn(string cacheName, String module, String message)
        {
            int space1 = 8;
            int space2 = 40;

            if (module.Length == 0)
                space2 = 4;

            string line = null;

            line = module.PadRight(space2, ' ') + message;

            Warn(cacheName, line);
        }
Esempio n. 27
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="originalData">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量</param>
        /// <returns>密文</returns>
        /// <remarks>
        /// AES算法描述简介:
        /// DES数据加密标准算法由于密钥长度较小(56位),
        /// 已经不适应当今分布式开放网络对数据加密安全性的要求,
        /// 因此1997年NIST公开征集新的数据加密标准,即AES。
        /// 经过三轮的筛选,比利时Joan Daeman和Vincent Rijmen
        /// 提交的Rijndael算法被提议为AES的最终算法。
        /// 此算法将成为美国新的数据加密标准而被广泛应用在各个领域中。
        /// 尽管人们对AES还有不同的看法,但总体来说,
        /// AES作为新一代的数据加密标准汇聚了强安全性、高性能、高效率、易用和灵活等优点。
        /// AES设计有三个密钥长度:128,192,256位,
        /// 相对而言,AES的128密钥比DES的56密钥强1021倍。
        /// </remarks>
        public static Byte[] AESEncrypt(Byte[] originalData, String key, String vector)
        {
            Byte[] byteKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(byteKey.Length)), byteKey, byteKey.Length);
            Byte[] byteVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(vector.PadRight(byteVector.Length)), byteVector, byteVector.Length);

            Byte[] encryptedData = null; // 加密后的密文

            Rijndael aes = Rijndael.Create();
            try
            {
                // 开辟一块内存流
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    // 把内存流对象包装成加密流对象
                    using (CryptoStream encryptor = new CryptoStream(memoryStream, aes.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write))
                    {
                        // 明文数据写入加密流
                        encryptor.Write(originalData, 0, originalData.Length);
                        encryptor.FlushFinalBlock();

                        encryptedData = memoryStream.ToArray();
                    }
                }
            }
            catch
            {
                encryptedData = null;
            }

            return encryptedData;
        }
 /**
   	 * Create a DateTime from a String
   	 * @param value
   	 * @return
   	 */
 public DateTime StringToDateTime(String value)
 {
     value = value.PadRight(23,'0');
     return DateTime.ParseExact(value, DATETIMEFORMAT, CultureInfo.InvariantCulture);
 }
Esempio n. 29
0
        //FCIMPL5(LPVOID, ParseNumbers::IntToString, INT32 n, INT32 radix,
        //        INT32 width, WCHAR paddingChar, INT32 flags);
        public static String IntToString(int n, int radix, int width,
                                         char paddingChar, int flags)
        {
            // See also Lightning\Src\VM\COMUtilNative.cpp::IntToString

            // changed to fill the char[] backwards to call a normal
            // stringCTOR and not have an additional copy

            bool isNegative = false;
            int  charVal;
            int  buffLength;
            uint l;

            // Longest possible string length for an integer in
            // binary notation with prefix
            int bufSize = 66;

            char[] buffer = new char[bufSize];
            int    index  = bufSize;

            if (radix < MinRadix || radix > MaxRadix)
            {
                throw new ArgumentException("Argument_InvalidBase");
                //COMPlusThrowArgumentException(L"radix", L"Arg_InvalidBase");
            }

            //If the number is negative, make it positive and remember the sign.
            //If the number is MIN_VALUE, this will still be negative,
            //so we'll have to special case this later.
            if (n < 0)
            {
                isNegative = true;
                // For base 10, write out -num, but other bases write out the
                // 2's complement bit pattern
                if (10 == radix)
                {
                    l = (uint)(-n);
                }
                else
                {
                    l = (uint)n; // REVIEW: comment suggests ~n wanted
                }
            }
            else
            {
                l = (uint)n;
            }

            //The conversion to a UINT will sign extend the number.  In order to
            //ensure that we only get as many bits as we expect, we chop the
            //number.
            if ((flags & PrintAsI1) != 0)
            {
                l = l & 0xFF;
            }
            else if ((flags & PrintAsI2) != 0)
            {
                l = l & 0xFFFF;
            }
            else if ((flags & PrintAsI4) != 0)
            {
                l = l & 0xFFFFFFFF;
            }

            if (0 == l)   //Special case the 0.
            {
                buffer[--index] = '0';
            }
            else
            {
                do
                {
                    charVal = (int)(l % (uint)radix);
                    l       = l / (uint)radix;
                    if (charVal < 10)
                    {
                        buffer[--index] = (char)(charVal + '0');
                    }
                    else
                    {
                        buffer[--index] = (char)(charVal + 'a' - 10);
                    }
                } while (l != 0);
            }
            //If they want the base, append that to the string (in reverse order)
            if (radix != 10 && ((flags & PrintBase) != 0))
            {
                if (16 == radix)
                {
                    buffer[--index] = 'x';
                    buffer[--index] = '0';
                }
                else if (8 == radix)
                {
                    buffer[--index] = '0';
                }
            }

            if (10 == radix)
            {
                if (isNegative)
                {
                    //If it was negative, append the sign.
                    buffer[--index] = '-';
                }
                else if ((flags & PrintSign) != 0)
                {
                    //else if they requested, add the '+';
                    buffer[--index] = '+';
                }
                else if ((flags & PrefixSpace) != 0)
                {
                    //If they requested a leading space, put it on.
                    buffer[--index] = ' ';
                }
            }

            //Figure out the size of our string.
            if (width <= bufSize - index)
            {
                buffLength = bufSize - index;
            }
            else
            {
                buffLength = width;
            }

            String local = String.StringCTOR(buffer, index, bufSize - index);

            // Pad if necessary, open up access to String if you
            //don't want to make a new string here
            if ((flags & LeftAlign) != 0)
            {
                local = local.PadRight(buffLength, paddingChar);
            }
            else
            {
                local = local.PadLeft(buffLength, paddingChar);
            }

            return(local);
        }
Esempio n. 30
0
 public static void WriteLine(String text, ConsoleColor color)
 {
     Console.ForegroundColor = color;
     Console.WriteLine(text.PadRight(Console.WindowWidth - 1));
     ResetColors();
 }
Esempio n. 31
0
 public AccessCondition(String AccessString)
 {
     this.accessConditionBytes=HexEncoding.GetBytes(AccessString.PadRight(8, '0'));
     this.GetAccessConditions();
 }
Esempio n. 32
0
        public bool VerifyAccessConditions(String str)
        {
            this.isverifyaccess=false;
            this.verifyaccessstring=str.PadRight(8, '0');
            this.accessConditionBytes=HexEncoding.GetBytes(this.verifyaccessstring);

            this.GetAccessConditions();
            this.CalculateAccessBits();
            this.verfyaccesssresult=HexEncoding.ToString(this.accessConditionBytes);
            this.isverifyaccess=(this.verifyaccessstring.Substring(0, 6) == this.verfyaccesssresult.Substring(0, 6));

            return this.isverifyaccess;
        }