Esempio n. 1
0
        private static DocsPaVO.documento.SignerInfo convertToSignerInfo(DeSign.signer signer)
        {
            //DeSign.signer signer = signerObj as DeSign.signer;
            DocsPaVO.documento.SignerInfo si = new SignerInfo();

            int ErrCode;

            Int32.TryParse(signer.errorCode, out ErrCode);
            byte[] cert       = null;
            string thumbPrint = string.Empty;

            //generazione thumbprint
            if (!String.IsNullOrEmpty(signer.certificate))
            {
                cert       = Convert.FromBase64String(signer.certificate.Replace("-----BEGIN CERTIFICATE-----", string.Empty).Replace("-----END CERTIFICATE-----", string.Empty));
                thumbPrint = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(cert)).Replace("-", "");
            }
            string RevocationStatusDescription = signer.errorMessage;

            if (String.IsNullOrEmpty(RevocationStatusDescription))
            {
                RevocationStatusDescription = "Valido";
            }

            si.CertificateInfo = new CertificateInfo
            {
                SerialNumber                = signer.serial,
                ValidFromDate               = convertSimpleDateTime(signer.certNotBefore),
                ValidToDate                 = convertSimpleDateTime(signer.certNotAfter),
                IssuerName                  = "CN=" + signer.issuer.CN,
                SubjectName                 = signer.subject.CN,
                RevocationStatus            = ErrCode,
                RevocationStatusDescription = RevocationStatusDescription,
                RevocationDate              = convertSimpleDateTime(signer.crlRevocationDate),
                SignatureAlgorithm          = "N.D.",
                ThumbPrint                  = thumbPrint,
                X509Certificate             = cert
            };

            if (si.CertificateInfo.RevocationDate != DateTime.MinValue)
            {
                si.CertificateInfo.RevocationStatus = 4; //Revocato
            }
            string codFisc = signer.subject.SER;

            if (!string.IsNullOrEmpty(codFisc) && codFisc.Contains(":"))
            {
                codFisc = codFisc.Split(':')[1];
            }

            si.SubjectInfo = new SubjectInfo
            {
                Organizzazione = signer.subject.O,
                CommonName     = signer.subject.CN,
                CodiceFiscale  = codFisc,
                Nome           = signer.subject.GIVEN,
                Cognome        = signer.subject.SUR,
                Country        = signer.subject.C,
                SerialNumber   = signer.serial,
                CertId         = signer.subject.DNQUALIF
            };
            si.SignatureAlgorithm = convertOidToString(signer.digestAlgorithm);

            /*
             * logger.Debug("INSERISCO LE INFORMAZIONI SULLO STATO DELLA FIRMA TEST");
             * si.errorCode = signer.errorCode;
             * si.errorMessage = signer.errorMessage;
             * si.status = signer.status;
             */
            if ((signer.signatureTimeStamp != null) && (signer.signatureTimeStamp.timeStampSerial != null) && (signer.signatureTimeStamp.timeStampDate != null))
            {
                List <TSInfo> tsList = new List <TSInfo>();
                TSInfo        tsi    = new TSInfo
                {
                    dataInizioValiditaCert = convertSimpleDateTime(signer.signatureTimeStamp.certNotBefore),
                    dataFineValiditaCert   = convertSimpleDateTime(signer.signatureTimeStamp.certNotAfter),
                    TSdateTime             = convertSimpleDateTime(signer.signatureTimeStamp.timeStampDate),
                    TSimprint      = signer.signatureTimeStamp.timeStampImprint,
                    TSANameIssuer  = signer.signatureTimeStamp.issuer.CN,
                    TSANameSubject = signer.signatureTimeStamp.subject.CN,
                    TSserialNumber = signer.signatureTimeStamp.timeStampSerial,
                    TSType         = TsType.PKCS
                };
                tsList.Add(tsi);
                si.SignatureTimeStampInfo = tsList.ToArray();
            }

            //controfirmatari
            List <SignerInfo> csiLst = new List <SignerInfo>();

            foreach (DeSign.countersigner countersigner in signer.countersigner)
            {
                DocsPaVO.documento.SignerInfo csi = new SignerInfo();
                csi.isCountersigner = true;

                if (!String.IsNullOrEmpty(countersigner.certificate))
                {
                    cert       = Convert.FromBase64String(countersigner.certificate.Replace("-----BEGIN CERTIFICATE-----", string.Empty).Replace("-----END CERTIFICATE-----", string.Empty));
                    thumbPrint = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(cert)).Replace("-", "");
                }
                string csiRevocationStatusDescription = countersigner.errorMessage;
                if (String.IsNullOrEmpty(RevocationStatusDescription))
                {
                    RevocationStatusDescription = "Valido";
                }

                csi.CertificateInfo = new CertificateInfo
                {
                    SerialNumber                = countersigner.serial,
                    ValidFromDate               = convertSimpleDateTime(countersigner.certNotBefore),
                    ValidToDate                 = convertSimpleDateTime(countersigner.certNotAfter),
                    IssuerName                  = "CN=" + countersigner.issuer.CN,
                    SubjectName                 = countersigner.subject.CN,
                    RevocationStatus            = ErrCode,
                    RevocationStatusDescription = RevocationStatusDescription,
                    RevocationDate              = convertSimpleDateTime(countersigner.crlRevocationDate),
                    SignatureAlgorithm          = "N.D.",
                    ThumbPrint                  = thumbPrint,
                    X509Certificate             = cert
                };

                if (csi.CertificateInfo.RevocationDate != DateTime.MinValue)
                {
                    csi.CertificateInfo.RevocationStatus = 4; //Revocato
                }
                codFisc = countersigner.subject.SER;
                if (codFisc.Contains(":"))
                {
                    codFisc = codFisc.Split(':')[1];
                }

                csi.SubjectInfo = new SubjectInfo
                {
                    Organizzazione = countersigner.subject.O,
                    CommonName     = countersigner.subject.CN,
                    CodiceFiscale  = codFisc,
                    Nome           = countersigner.subject.GIVEN,
                    Cognome        = countersigner.subject.SUR,
                    Country        = countersigner.subject.C,
                    SerialNumber   = countersigner.serial,
                    CertId         = countersigner.subject.DNQUALIF
                };
                csi.SignatureAlgorithm = convertOidToString(countersigner.digestAlgorithm);
                if ((countersigner.signatureTimeStamp != null) && (countersigner.signatureTimeStamp.timeStampSerial != null) && (countersigner.signatureTimeStamp.timeStampDate != null))
                {
                    List <TSInfo> ctsList = new List <TSInfo>();
                    TSInfo        tsi     = new TSInfo
                    {
                        dataInizioValiditaCert = convertSimpleDateTime(countersigner.signatureTimeStamp.certNotBefore),
                        dataFineValiditaCert   = convertSimpleDateTime(countersigner.signatureTimeStamp.certNotAfter),
                        TSdateTime             = convertSimpleDateTime(countersigner.signatureTimeStamp.timeStampDate),
                        TSimprint      = countersigner.signatureTimeStamp.timeStampImprint,
                        TSANameIssuer  = countersigner.signatureTimeStamp.issuer.CN,
                        TSANameSubject = countersigner.signatureTimeStamp.subject.CN,
                        TSserialNumber = countersigner.signatureTimeStamp.timeStampSerial,
                        TSType         = TsType.PKCS
                    };
                    ctsList.Add(tsi);
                    csi.SignatureTimeStampInfo = ctsList.ToArray();
                }
                csiLst.Add(csi);
            }
            if (csiLst.Count > 0)
            {
                si.counterSignatures = csiLst.ToArray();
            }

            return(si);
        }
Esempio n. 2
0
 public static string Convierte(byte[] bytearray_a_convertir)
 {
     return (BitConverter.ToString(bytearray_a_convertir)).Replace("-", "").ToLower();
 }
Esempio n. 3
0
 /// <summary>
 /// 字节数组转换为16进制表示的字符串
 /// </summary>
 private static string ByteArrayToHexString(byte[] buf)
 {
     return(BitConverter.ToString(buf).Replace("-", ""));
 }
Esempio n. 4
0
 static string ToHexString(byte[] bytes)
 {
     Preconditions.CheckNotNull(bytes);
     return(BitConverter.ToString(bytes).Replace("-", string.Empty));
 }
Esempio n. 5
0
        /// <summary>
        /// MD5加密
        /// </summary>
        public string MD5Encrypt(string strSource)
        {
            var mD5CryptoServiceProvider = new MD5CryptoServiceProvider();

            return(BitConverter.ToString(mD5CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(strSource))).Replace("-", "").ToUpper());
        }
Esempio n. 6
0
 public override string ToString()
 {
     return("NetworkReader pos=" + Position + " len=" + Length + " buffer=" + BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count));
 }
Esempio n. 7
0
 public string getDataAsString()
 {
     return(BitConverter.ToString(getByteArray(2), 0));
 }
Esempio n. 8
0
        // note: original HLAPI HandleBytes function handled >1 message in a while loop, but this wasn't necessary
        //       anymore because NetworkServer/NetworkClient Update both use while loops to handle >1 data events per
        //       frame already.
        //       -> in other words, we always receive 1 message per Receive call, never two.
        //       -> can be tested easily with a 1000ms send delay and then logging amount received in while loops here
        //          and in NetworkServer/Client Update. HandleBytes already takes exactly one.
        /// <summary>
        /// This function allows custom network connection classes to process data from the network before it is passed to the application.
        /// </summary>
        /// <param name="buffer">The data received.</param>
        internal void TransportReceive(ArraySegment <byte> buffer, int channelId)
        {
            // unpack message
            using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(buffer))
            {
                if (MessagePacker.UnpackMessage(networkReader, out int msgType))
                {
                    // logging
                    if (logger.LogEnabled())
                    {
                        logger.Log("ConnectionRecv " + this + " msgType:" + msgType + " content:" + BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count));
                    }

                    // try to invoke the handler for that message
                    if (InvokeHandler(msgType, networkReader, channelId))
                    {
                        lastMessageTime = Time.time;
                    }
                }
                else
                {
                    logger.LogError("Closed connection: " + this + ". Invalid message header.");
                    Disconnect();
                }
            }
        }
Esempio n. 9
0
        internal static bool VERIFY_Central_File_Config_Hash(string HTTP_File_Path, string Local_File_Path)
        {
            string HTTPFileHash;
            string LocalFileHash;

            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.CheckCertificateRevocationList = false;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

                using (CustomWebClient response = new CustomWebClient())
                {
                    //string Web_Config_File_Contents = response.DownloadString(HTTP_File_Path);
                    if (Settings.Central_Config_Hashs.ContainsKey(HTTP_File_Path) == true)//determine if we use cache version
                    {
                        HTTPFileHash = Settings.Central_Config_Hashs[HTTP_File_Path];
                    }
                    else//no cache version get from network
                    {
                        Uri uri = new Uri(HTTP_File_Path);
                        Central_Config_File_Web_Cache = Crypto_Operation.CONVERT_To_String_From_Bytes(response.DownloadData(uri), 2);//get file has from Network
                        using (var sha256 = SHA256.Create())
                        {
                            HTTPFileHash = BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(Central_Config_File_Web_Cache)));
                        }
                        if (Settings.Central_Config_Hashs.ContainsKey(HTTP_File_Path) == false)
                        {
                            Settings.Central_Config_Hashs.Add(HTTP_File_Path, HTTPFileHash);
                        }
                    }
                    using (var sha2562 = SHA256.Create())//Get local file hash
                    {
                        if (File_Operation.CHECK_if_File_Exists(Local_File_Path) == false)
                        {
                            return(false);//no local file
                        }
                        else
                        {
                            LocalFileHash = BitConverter.ToString(sha2562.ComputeHash(Encoding.UTF8.GetBytes(File_Operation.READ_AllText(Local_File_Path))));
                        }
                    }

                    if (HTTPFileHash == LocalFileHash)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                if ((!e.Message.Contains("The operation has timed out") || !e.Message.Contains("The remote name could not be resolved: ")) || (Settings.Logging_Level_To_Report.ToLower() == "informataion" || Settings.Logging_Level_To_Report.ToLower() == "verbose"))
                {
                    Error_Operation.Log_Error("VERIFY_Central_File_Config_Hash()", e.Message.ToString() + " " + HTTP_File_Path + " " + Local_File_Path, e.StackTrace.ToString(), Error_Operation.LogSeverity.Informataion);
                }
                return(false);
            }
            finally
            {
                Wclient.Dispose();
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Decodes information from a broadcast services data packet.
        /// </summary>
        /// <param name="packet">The teletext packet to be decoded.</param>
        private void DecodeBroadcastServiceData(Packet packet)
        {
            // Get the designation byte
            byte designationByte = Decode.Hamming84(packet.Data[0]);

            // Check the designation byte does not have unrecoverable errors, and if it does ignore the packet
            if (designationByte == 0xff)
            {
                return;
            }
            // Decode the designation code and multiplex status
            bool multiplexed = Convert.ToBoolean(designationByte & 0x01);
            int  designation = designationByte >> 1;

            // Check the designation code is 0 (format 1) or 1 (format 2), otherwise ignore the packet
            if (designation > 1)
            {
                return;
            }
            // Set the multiplexed status
            Multiplexed = !multiplexed;
            // If the packet is format 1, decode the network identification code
            if (designation == 0)
            {
                byte[] networkID = { packet.Data[7], packet.Data[8] };
                NetworkID = BitConverter.ToString(networkID).Replace("-", "");
            }
            // Get the status display
            byte[] statusCharacters = new byte[packet.Data.Length - 20];
            for (int i = 20; i < packet.Data.Length; i++)
            {
                statusCharacters[i - 20] = Decode.OddParity(packet.Data[i]);
            }
            StatusDisplay = Encoding.ASCII.GetString(statusCharacters);
            // Decode the digits for the inital page number
            byte pageUnits = Decode.Hamming84(packet.Data[1]);
            byte pageTens  = Decode.Hamming84(packet.Data[2]);
            // Decode the bytes for the initial subcode
            byte subcode1 = Decode.Hamming84(packet.Data[3]);
            byte subcode2 = Decode.Hamming84(packet.Data[4]);
            byte subcode3 = Decode.Hamming84(packet.Data[5]);
            byte subcode4 = Decode.Hamming84(packet.Data[6]);

            // If the subcode bytes containing the magazine number contains errors, stop processing
            if (subcode2 == 0xff || subcode4 == 0xff)
            {
                return;
            }
            // If the page number digits don't contain errors, set the initial page number
            if (pageUnits != 0xff && pageTens != 0xff)
            {
                // Get the magazine number, changing 0 to 8
                byte magazineNumber = (byte)((subcode2 >> 3) | ((subcode4 & 0x0C) >> 1));
                if (magazineNumber == 0)
                {
                    magazineNumber = 8;
                }
                // Set the initial page number
                InitialPage = magazineNumber.ToString("X1") + ((pageTens << 4) | pageUnits).ToString("X2");
            }
            // If the remaining subcode bytes don't contain any errors, set the subcode
            if (subcode1 != 0xff && subcode3 != 0xff)
            {
                byte[] fullSubcode = { (byte)(((subcode4 & 0x03) << 4) | subcode3), (byte)(((subcode2 & 0x07) << 4) | subcode1) };
                InitialSubcode = BitConverter.ToString(fullSubcode).Replace("-", "");
            }
        }
Esempio n. 11
0
        public async Task GetCommandTestGoodContent()
        {
            var(size, content, messageError) = await client.GetCommand(path + "/TestFile.txt");

            Assert.AreEqual("EF-BB-BF-46-69-6C-65-20-66-6F-72-20-74-65-73-74-20-70-72-6F-6A-65-63-74", BitConverter.ToString(content));
            server.Stop();
            client.Close();
        }
Esempio n. 12
0
 public string GetUrlEncodedHash(byte[] value)
 {
     return("%" + BitConverter.ToString(SHA1.Create().ComputeHash(value)).Replace("-", "%").ToLower());
 }
Esempio n. 13
0
 public string GetHash(byte[] value)
 {
     return(BitConverter.ToString(SHA1.Create().ComputeHash(value)).Replace("-", ""));
 }
Esempio n. 14
0
        public void Render()
        {
            //   TO DO: REWRITE THIS CLASS! and maybe the whole process of
            //          getting data from the lower classes, why convert buffers
            //          to XML just to convert them again in this Render method?
            //  ALSO: this conversion process does not take into account that
            //        the XML data that this class is converted from might
            //        contain more than _CX characters in a line, since the
            //        previous conversion to XML converts '<' to "&lt;" and
            //        the like, which will also cause shifts in character positions.
            //
            // Reset cache
            //
            _stringValueCache = null;
            //
            if (_CX == 0 || _CY == 0)
            {
                // TODO: Need to fix this
                _CX = 132;
                _CY = 43;
            }

            // CFCJr 2008/07/11
            if (_CX < 80)
            {
                _CX = 80;
            }
            if (_CY < 25)
            {
                _CY = 25;
            }


            // CFCJr 2008/07/11
            if (_CX < 80)
            {
                _CX = 80;
            }
            if (_CY < 25)
            {
                _CY = 25;
            }

            UserIdentified      = null;
            MatchListIdentified = null;
            //
            // Render text image of screen
            //
            //
            mScreenBuffer = new char[_CX * _CY];
            mScreenRows   = new string[_CY];

            // CFCJr 2008/07/11
            // The following might be much faster:
            //
            //   string str = "".PadRight(_CX*_CY, ' ');
            //   mScreenBuffer = str.ToCharArray();
            //     ........do operations on mScreenBuffer to fill it......
            //   str = string.FromCharArray(mScreenBuffer);
            //   for (int r = 0; r < _CY; r++)
            //        mScreenRows[i] = str.SubString(r*_CY,_CX);
            //
            //  ie, fill mScreenBuffer with the data from Unformatted and Field, then
            //   create str (for the hash) and mScreenRows[]
            //   with the result.
            int i;

            for (i = 0; i < mScreenBuffer.Length; i++)              // CFCJr. 2008.07/11 replase _CX*CY with mScreenBuffer.Length
            {
                mScreenBuffer[i] = ' ';
            }
            //

            int chindex;

            if (Field == null || Field.Length == 0 &&
                (Unformatted == null || Unformatted.Text == null))
            {
                if ((Unformatted == null || Unformatted.Text == null))
                {
                    Console.WriteLine("XMLScreen:Render: **BUGBUG** XMLScreen.Unformatted screen is blank");
                }
                else
                {
                    Console.WriteLine("XMLScreen:Render: **BUGBUG** XMLScreen.Field is blank");
                }

                Console.Out.Flush();

                // CFCJr. Move logic for what is in mScreenRows to seperate if logic
                //        this will give unformatted results even if Field==null or 0 length
                //        and vise-a-versa.

                /*
                 *              for (i=0; i<mScreenRows.Length; i++)
                 *              {
                 *                      mScreenRows[i] = new String(' ',_CX);
                 *              }
                 */
            }

            string blankRow = string.Empty;

            blankRow = blankRow.PadRight(_CX, ' ');

            if ((Unformatted == null || Unformatted.Text == null))
            {
                // CFCJr. 2008/07/11 initilize a blank row of _CX (80?) spaces

                for (i = 0; i < mScreenRows.Length; i++)
                {
                    //mScreenRows[i] = "                                                                                              ".Substring(0, _CX);
                    // CFCJr. 2008/07/11 replace above method of 80 spaces with following
                    mScreenRows[i] = blankRow;
                }
            }
            else
            {
                for (i = 0; i < Unformatted.Text.Length; i++)
                {
                    string text = Unformatted.Text[i];

                    // CFCJr, make sure text is not null

                    if (string.IsNullOrEmpty(text))
                    {
                        text = string.Empty;
                    }

                    // CFCJr, replace "&lt;" with '<'
                    text = text.Replace("&lt;", "<");

                    // CFCJr, Remove this loop to pad text
                    // and use text.PadRight later.
                    // This will help in not processing more
                    // characters than necessary into mScreenBuffer
                    // below

                    //while (text.Length < _CX)
                    //	text+=" ";

                    //
                    int p;
                    //for (p=0; p<_CX; p++)
                    for (p = 0; p < text.Length; p++)  // CFC,Jr.
                    {
                        if (text[p] < 32 || text[p] > 126)
                        {
                            text = text.Replace(text[p], ' ');
                        }
                    }
                    //
                    //for (chindex=0; chindex<Unformatted.Text[i].Length; chindex++)
                    // CFCJr, 2008/07/11 use text.length instead of Unformatted.Text[i].Length
                    // since we only pad text with 80 chars but if Unformatted.Text[i]
                    // contains XML codes (ie, "&lt;") then it could be longer than
                    // 80 chars (hence, longer than text).
                    // Also, I replace "&lt;" above with "<".

                    for (chindex = 0; chindex < text.Length; chindex++)
                    {
                        // CFCJr, calculate mScreenBuffer index only once
                        int bufNdx = chindex + (i * _CX);

                        if (bufNdx < mScreenBuffer.Length)
                        {
                            mScreenBuffer[bufNdx] = text[chindex];
                        }
                    }
                    // CFCJr, make sure we don't overflow the index of mScreenRows
                    //        since i is based on the dimensions of Unformatted.Text
                    //        instead of mScreenRows.Length
                    if (i < mScreenRows.Length)
                    {
                        text           = text.PadRight(_CX, ' '); // CFCJr. 2008/07/11 use PadRight instead of loop above
                        mScreenRows[i] = text;
                    }
                }
            }

            // CFCJr, lets make sure we have _CY rows in mScreenRows here
            // since we use Unformated.Text.Length for loop above which
            // could possibly be less than _CY.

            for (i = 0; i < mScreenRows.Length; i++)
            {
                if (string.IsNullOrEmpty(mScreenRows[i]))
                {
                    mScreenRows[i] = blankRow;
                }
            }

            //==============
            // Now process the Field (s)

            if (Field != null && Field.Length > 0)
            {
                //
                // Now superimpose the formatted fields on the unformatted base
                //
                for (i = 0; i < Field.Length; i++)
                {
                    XMLScreenField field = Field[i];
                    if (field.Text != null)
                    {
                        for (chindex = 0; chindex < field.Text.Length; chindex++)
                        {
                            char ch = field.Text[chindex];
                            if (ch < 32 || ch > 126)
                            {
                                ch = ' ';
                            }
                            // CFCJr, 2008/07/11 make sure we don't get out of bounds
                            //        of the array m_ScreenBuffer.
                            int bufNdx = chindex + field.Location.left + field.Location.top * _CX;
                            if (bufNdx >= 0 && bufNdx < mScreenBuffer.Length)
                            {
                                mScreenBuffer[bufNdx] = ch;
                            }
                        }
                    }
                }

                // CFCJr, 2008/07/11
                // SOMETHING needs to be done in this method to speed things up.
                // Above, in the processing of the Unformatted.Text, Render()
                // goes to the trouble of loading up mScreenBuffer and mScreenRows.
                // now here, we replace mScreenRows with the contents of mScreenBuffer.
                // Maybe, we should only load mScreenBuffer and then at the end
                // of Render(), load mScreenRows from it (or vise-a-vera).
                // WE COULD ALSO use
                //   mScreenRows[i] = string.FromCharArraySubset(mScreenBuffer, i*_CX, _CX);
                //  inside this loop.

                for (i = 0; i < _CY; i++)
                {
                    string temp = string.Empty;                     // CFCJr, 2008/07/11 replace ""

                    for (int j = 0; j < _CX; j++)
                    {
                        temp += mScreenBuffer[i * _CX + j];
                    }
                    mScreenRows[i] = temp;
                }
            }

            // now calculate our screen's hash
            //
            // CFCJr, dang, now we're going to copy the data again,
            //   this time into a long string.....(see comments at top of Render())
            //   I bet there's a easy way to redo this class so that we use just
            //   one buffer (string or char[]) instead of all these buffers.
            // WE COULD also use
            //   string hashStr = string.FromCharArray(mScreenBuffer);
            // instead of converting mScreenRows to StringBuilder
            // and then converting it to a string.

            HashAlgorithm hash    = (HashAlgorithm)CryptoConfig.CreateFromName("MD5");
            StringBuilder builder = new StringBuilder();

            for (i = 0; i < mScreenRows.Length; i++)
            {
                builder.Append(mScreenRows[i]);
            }
            byte[] myHash = hash.ComputeHash(new UnicodeEncoding().GetBytes(builder.ToString()));
            this.Hash        = BitConverter.ToString(myHash);
            this._ScreenGuid = Guid.NewGuid();
        }
Esempio n. 15
0
        /// \brief Reads and interprets data reported by the Wii Remote.
        /// \return On success, > 0, < 0 on failure, 0 if nothing has been recieved.
        ///
        /// Wii Remote reads function similarly to a Queue, in FIFO (first in, first out) order.
        /// For example, if two reports were sent since the last \c ReadWiimoteData() call,
        /// this call will only read and interpret the first of those two (and "pop" it off
        /// of the queue).  So, in order to make sure you don't fall behind the Wiimote's update
        /// frequency, you can do something like this (in a game loop for example):
        ///
        /// \code
        /// Wii Remote wiimote;
        /// int ret;
        /// do
        /// {
        ///     ret = wiimote.ReadWiimoteData();
        /// } while (ret > 0);
        /// \endcode
        public int ReadWiimoteData()
        {
            byte[] buf    = new byte[22];
            int    status = WiimoteManager.RecieveRaw(hidapi_handle, buf);

            if (status <= 0)
            {
                return(status);         // Either there is some sort of error or we haven't recieved anything
            }
            int typesize = GetInputDataTypeSize((InputDataType)buf[0]);

            byte[] data = new byte[typesize];
            for (int x = 0; x < data.Length; x++)
            {
                data[x] = buf[x + 1];
            }

            if (WiimoteManager.Debug_Messages)
            {
                Debug.Log("Recieved: [" + buf[0].ToString("X").PadLeft(2, '0') + "] " + BitConverter.ToString(data));
            }

            // Variable names used throughout the switch/case block
            byte[] buttons;
            byte[] accel;
            byte[] ext = null;
            byte[] ir;

            switch ((InputDataType)buf[0])  // buf[0] is the output ID byte
            {
            case InputDataType.STATUS_INFO: // done.
                buttons = new byte[] { data[0], data[1] };
                byte flags         = data[2];
                byte battery_level = data[5];

                Button.InterpretData(buttons);

                bool old_ext_connected = Status.ext_connected;

                byte[] total = new byte[] { flags, battery_level };
                Status.InterpretData(total);

                if (expecting_status_report)
                {
                    expecting_status_report = false;
                }
                else                                        // We haven't requested any data report type, meaning a controller has connected.
                {
                    SendDataReportMode(last_report_type);   // If we don't update the data report mode, no updates will be sent
                }

                if (Status.ext_connected != old_ext_connected && Type != WiimoteType.PROCONTROLLER)
                {
                    if (Status.ext_connected)                // The Wii Remote doesn't allow reading from the extension identifier
                    {                                        // when nothing is connected.
                        Debug.Log("An extension has been connected.");
                        if (current_ext != ExtensionController.MOTIONPLUS)
                        {
                            ActivateExtension();
                            RequestIdentifyExtension();         // Identify what extension was connected.
                        }
                        else
                        {
                            ExpectingWiiMotionPlusSwitch = false;
                        }
                    }
                    else
                    {
                        if (!ExpectingWiiMotionPlusSwitch)
                        {
                            _current_ext = ExtensionController.NONE;
                        }
                        Debug.Log("An extension has been disconnected.");
                    }
                }
                break;

            case InputDataType.READ_MEMORY_REGISTERS: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                if (CurrentReadData == null)
                {
                    Debug.LogWarning("Recived Register Read Report when none was expected.  Ignoring.");
                    return(status);
                }

                byte size  = (byte)((data[2] >> 4) + 0x01);
                byte error = (byte)(data[2] & 0x0f);
                // Error 0x07 means reading from a write-only register
                // Offset 0xa600fa is for the Wii Motion Plus.  This error code can be expected behavior in this case.
                if (error == 0x07)
                {
                    if (CurrentReadData.Offset != 0xa600fa)
                    {
                        Debug.LogError("Wiimote reports Read Register error 7: Attempting to read from a write-only register (" + CurrentReadData.Offset.ToString("x") + ").  Aborting read.");
                    }

                    CurrentReadData = null;
                    return(status);
                }
                // lowOffset is reversed because the Wii Remote reports are in Big Endian order
                ushort lowOffset = BitConverter.ToUInt16(new byte[] { data[4], data[3] }, 0);
                ushort expected  = (ushort)CurrentReadData.ExpectedOffset;
                if (expected != lowOffset)
                {
                    Debug.LogWarning("Expected Register Read Offset (" + expected + ") does not match reported offset from Wii Remote (" + lowOffset + ")");
                }
                byte[] read = new byte[size];
                for (int x = 0; x < size; x++)
                {
                    read[x] = data[x + 5];
                }

                CurrentReadData.AppendData(read);
                if (CurrentReadData.ExpectedOffset >= CurrentReadData.Offset + CurrentReadData.Size)
                {
                    CurrentReadData = null;
                }

                break;

            case InputDataType.ACKNOWLEDGE_OUTPUT_REPORT:
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);
                // TODO: doesn't do any actual error handling, or do any special code about acknowledging the output report.
                break;

            case InputDataType.REPORT_BUTTONS: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);
                break;

            case InputDataType.REPORT_BUTTONS_ACCEL: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                accel = new byte[] { data[0], data[1], data[2], data[3], data[4] };
                Accel.InterpretData(accel);
                break;

            case InputDataType.REPORT_BUTTONS_EXT8: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                ext = new byte[8];
                for (int x = 0; x < ext.Length; x++)
                {
                    ext[x] = data[x + 2];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_BUTTONS_ACCEL_IR12: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                accel = new byte[] { data[0], data[1], data[2], data[3], data[4] };
                Accel.InterpretData(accel);

                ir = new byte[12];
                for (int x = 0; x < 12; x++)
                {
                    ir[x] = data[x + 5];
                }
                Ir.InterpretData(ir);
                break;

            case InputDataType.REPORT_BUTTONS_EXT19: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                ext = new byte[19];
                for (int x = 0; x < ext.Length; x++)
                {
                    ext[x] = data[x + 2];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_BUTTONS_ACCEL_EXT16: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                accel = new byte[] { data[0], data[1], data[2], data[3], data[4] };
                Accel.InterpretData(accel);

                ext = new byte[16];
                for (int x = 0; x < ext.Length; x++)
                {
                    ext[x] = data[x + 5];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_BUTTONS_IR10_EXT9: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                ir = new byte[10];
                for (int x = 0; x < 10; x++)
                {
                    ir[x] = data[x + 2];
                }
                Ir.InterpretData(ir);

                ext = new byte[9];
                for (int x = 0; x < 9; x++)
                {
                    ext[x] = data[x + 12];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_BUTTONS_ACCEL_IR10_EXT6: // done.
                buttons = new byte[] { data[0], data[1] };
                Button.InterpretData(buttons);

                accel = new byte[] { data[0], data[1], data[2], data[3], data[4] };
                Accel.InterpretData(accel);

                ir = new byte[10];
                for (int x = 0; x < 10; x++)
                {
                    ir[x] = data[x + 5];
                }
                Ir.InterpretData(ir);

                ext = new byte[6];
                for (int x = 0; x < 6; x++)
                {
                    ext[x] = data[x + 15];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_EXT21: // done.
                ext = new byte[21];
                for (int x = 0; x < ext.Length; x++)
                {
                    ext[x] = data[x];
                }

                if (_Extension != null)
                {
                    _Extension.InterpretData(ext);
                }
                break;

            case InputDataType.REPORT_INTERLEAVED:
                if (!ExpectingSecondInterleavedPacket)
                {
                    ExpectingSecondInterleavedPacket = true;
                    InterleavedDataBuffer            = data;
                }
                else if (WiimoteManager.Debug_Messages)
                {
                    Debug.LogWarning(
                        "Recieved two REPORT_INTERLEAVED (" + InputDataType.REPORT_INTERLEAVED.ToString("x") + ") reports in a row!  "
                        + "Expected REPORT_INTERLEAVED_ALT (" + InputDataType.REPORT_INTERLEAVED_ALT.ToString("x") + ").  Ignoring!"
                        );
                }

                break;

            case InputDataType.REPORT_INTERLEAVED_ALT:
                if (ExpectingSecondInterleavedPacket)
                {
                    ExpectingSecondInterleavedPacket = false;

                    buttons = new byte[] { data[0], data[1] };
                    Button.InterpretData(buttons);

                    byte[] ir1 = new byte[18];
                    byte[] ir2 = new byte[18];

                    for (int x = 0; x < 18; x++)
                    {
                        ir1[x] = InterleavedDataBuffer[x + 3];
                        ir2[x] = data[x + 3];
                    }

                    Ir.InterpretDataInterleaved(ir1, ir2);
                    Accel.InterpretDataInterleaved(InterleavedDataBuffer, data);
                }
                else if (WiimoteManager.Debug_Messages)
                {
                    Debug.LogWarning(
                        "Recieved two REPORT_INTERLEAVED_ALT (" + InputDataType.REPORT_INTERLEAVED_ALT.ToString("x") + ") reports in a row!  "
                        + "Expected REPORT_INTERLEAVED (" + InputDataType.REPORT_INTERLEAVED.ToString("x") + ").  Ignoring!"
                        );
                }
                break;
            }

            if (ext == null)
            {
                _RawExtension = null;
            }
            else
            {
                _RawExtension = new ReadOnlyArray <byte>(ext);
            }

            return(status);
        }
Esempio n. 16
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //Notificación On-Line
            var strDs_Merchant_MerchantURL = _webHelper.GetStoreLocation(false) + "Plugins/PaymentSermepa/Return";

            //URL OK
            var strDs_Merchant_UrlOK = _webHelper.GetStoreLocation(false) + "checkout/completed";

            //URL KO
            var strDs_Merchant_UrlKO = _webHelper.GetStoreLocation(false) + "Plugins/PaymentSermepa/Error";

            //Numero de pedido
            //You have to change the id of the orders table to begin with a number of at least 4 digits.
            var strDs_Merchant_Order = postProcessPaymentRequest.Order.Id.ToString("0000");

            //Nombre del comercio
            var strDs_Merchant_MerchantName = _sermepaPaymentSettings.NombreComercio;

            //Importe
            var amount = ((int)Convert.ToInt64(postProcessPaymentRequest.Order.OrderTotal * 100)).ToString();
            var strDs_Merchant_Amount = amount;

            //Código de comercio
            var strDs_Merchant_MerchantCode = _sermepaPaymentSettings.FUC;

            //Moneda
            var strDs_Merchant_Currency = _sermepaPaymentSettings.Moneda;

            //Terminal
            var strDs_Merchant_Terminal = _sermepaPaymentSettings.Terminal;

            //Tipo de transaccion (0 - Autorización)
            var strDs_Merchant_TransactionType = "0";

            //Clave
            var clave = _sermepaPaymentSettings.Pruebas ? _sermepaPaymentSettings.ClavePruebas : _sermepaPaymentSettings.ClaveReal;

            //Calculo de la firma
            var sha = string.Format("{0}{1}{2}{3}{4}{5}{6}",
                                    strDs_Merchant_Amount,
                                    strDs_Merchant_Order,
                                    strDs_Merchant_MerchantCode,
                                    strDs_Merchant_Currency,
                                    strDs_Merchant_TransactionType,
                                    strDs_Merchant_MerchantURL,
                                    clave);

            SHA1 shaM         = new SHA1Managed();
            var  shaResult    = shaM.ComputeHash(Encoding.Default.GetBytes(sha));
            var  shaResultStr = BitConverter.ToString(shaResult).Replace("-", "");

            //Creamos el POST
            var remotePostHelper = new RemotePost
            {
                FormName = "form1",
                Url      = GetSermepaUrl()
            };

            remotePostHelper.Add("Ds_Merchant_Amount", strDs_Merchant_Amount);
            remotePostHelper.Add("Ds_Merchant_Currency", strDs_Merchant_Currency);
            remotePostHelper.Add("Ds_Merchant_Order", strDs_Merchant_Order);
            remotePostHelper.Add("Ds_Merchant_MerchantCode", strDs_Merchant_MerchantCode);
            remotePostHelper.Add("Ds_Merchant_TransactionType", strDs_Merchant_TransactionType);
            remotePostHelper.Add("Ds_Merchant_MerchantURL", strDs_Merchant_MerchantURL);
            remotePostHelper.Add("Ds_Merchant_MerchantSignature", shaResultStr);
            remotePostHelper.Add("Ds_Merchant_Terminal", strDs_Merchant_Terminal);
            remotePostHelper.Add("Ds_Merchant_MerchantName", strDs_Merchant_MerchantName);
            remotePostHelper.Add("Ds_Merchant_UrlOK", strDs_Merchant_UrlOK);
            remotePostHelper.Add("Ds_Merchant_UrlKO", strDs_Merchant_UrlKO);

            remotePostHelper.Post();
        }
Esempio n. 17
0
 public static string ByteArrayToString(byte[] bytes)
 {
     return(BitConverter.ToString(bytes).Replace("-", ""));
 }
Esempio n. 18
0
        public static void Main()
        {
#if NETDUINO3_WIFI
            // Arduino D7->PD7
            int chipSelectPinNumber = PinNumber('A', 1);
#endif
            Debug.WriteLine("devMobile.IoT.nRf24L01.ModuleSPI starting");

            Debug.WriteLine(Windows.Devices.Spi.SpiDevice.GetDeviceSelector());

            try
            {
                GpioController gpioController = GpioController.GetDefault();

                var settings = new SpiConnectionSettings(chipSelectPinNumber)
                {
                    ClockFrequency = 2000000,
                    Mode           = SpiMode.Mode0,
                    SharingMode    = SpiSharingMode.Shared,
                };

                using (SpiDevice device = SpiDevice.FromId(SpiBusId, settings))
                {
                    Debug.WriteLine("nrf24L01Device Device...");
                    if (device == null)
                    {
                        Debug.WriteLine("nrf24L01Device == null");
                    }

                    Thread.Sleep(100);

                    Debug.WriteLine("ConfigureSpiPort Done...");
                    Debug.WriteLine("");

                    Thread.Sleep(500);
                    try
                    {
                        // Read the Address width
                        Debug.WriteLine("Read address width");
                        byte[] txBuffer1 = new byte[] { SETUP_AW | R_REGISTER, 0x0 };
                        byte[] rxBuffer1 = new byte[txBuffer1.Length];

                        Debug.WriteLine(" nrf24L01Device.TransferFullDuplex...SETUP_AW");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer1));
                        device.TransferFullDuplex(txBuffer1, rxBuffer1);
                        Debug.WriteLine(" rxBuffer:" + BitConverter.ToString(rxBuffer1));

                        // Extract then adjust the address width
                        byte addressWidthValue = rxBuffer1[1];
                        addressWidthValue &= 0b00000011;
                        addressWidthValue += 2;
                        Debug.WriteLine($"Address width 0x{SETUP_AW:x2} - Value 0X{rxBuffer1[1]:x2} Value adjusted {addressWidthValue}");
                        Debug.WriteLine("");

                        // Write Pipe0 Receive address
                        Debug.WriteLine($"Write Pipe0 Receive Address {P0_Address}");
                        byte[] txBuffer2 = new byte[addressWidthValue + 1];
                        byte[] rxBuffer2 = new byte[txBuffer2.Length];
                        txBuffer2[0] = RX_ADDR_P0 | W_REGISTER;
                        Array.Copy(Encoding.UTF8.GetBytes(P0_Address), 0, txBuffer2, 1, addressWidthValue);

                        Debug.WriteLine(" nrf24L01Device.Write...RX_ADDR_P0");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer2));
                        device.TransferFullDuplex(txBuffer2, rxBuffer2);
                        Debug.WriteLine("");

                        // Read Pipe0 Receive address
                        Debug.WriteLine("Read Pipe0 Receive address");
                        byte[] txBuffer3 = new byte[addressWidthValue + 1];
                        txBuffer3[0] = RX_ADDR_P0 | R_REGISTER;
                        byte[] rxBuffer3 = new byte[txBuffer3.Length];

                        Debug.WriteLine(" nrf24L01Device.TransferFullDuplex...RX_ADDR_P0");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer3));
                        device.TransferFullDuplex(txBuffer3, rxBuffer3);
                        Debug.WriteLine(" rxBuffer:" + BitConverter.ToString(rxBuffer3));
                        Debug.WriteLine($"Address 0x{RX_ADDR_P0:x2} Address {UTF8Encoding.UTF8.GetString(rxBuffer3, 1, addressWidthValue)}");
                        Debug.WriteLine("");

                        // Read the RF Channel
                        Debug.WriteLine("RF Channel read 1");
                        byte[] txBuffer4 = new byte[] { RF_CH | R_REGISTER, 0x0 };
                        byte[] rxBuffer4 = new byte[txBuffer4.Length];

                        Debug.WriteLine(" nrf24L01Device.TransferFullDuplex...RF_CH");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer4));
                        device.TransferFullDuplex(txBuffer4, rxBuffer4);
                        Debug.WriteLine(" rxBuffer:" + BitConverter.ToString(rxBuffer4));

                        byte rfChannel1 = rxBuffer4[1];
                        Debug.WriteLine($"RF Channel 1 0x{RF_CH:x2} - Value 0X{rxBuffer4[1]:x2} - Value adjusted {rfChannel1+2400}");
                        Debug.WriteLine("");

                        // Write the RF Channel
                        Debug.WriteLine("RF Channel write");
                        byte[] txBuffer5 = new byte[] { RF_CH | W_REGISTER, rfChannel1 += 1 };
                        byte[] rxBuffer5 = new byte[txBuffer5.Length];

                        Debug.WriteLine(" nrf24L01Device.Write...RF_CH");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer5));
                        //device.Write(txBuffer5);
                        device.TransferFullDuplex(txBuffer5, rxBuffer5);
                        Debug.WriteLine("");

                        // Read the RF Channel
                        Debug.WriteLine("RF Channel read 2");
                        byte[] txBuffer6 = new byte[] { RF_CH | R_REGISTER, 0x0 };
                        byte[] rxBuffer6 = new byte[txBuffer6.Length];

                        Debug.WriteLine(" nrf24L01Device.TransferFullDuplex...RF_CH");
                        Debug.WriteLine(" txBuffer:" + BitConverter.ToString(txBuffer6));
                        device.TransferFullDuplex(txBuffer6, rxBuffer6);
                        Debug.WriteLine(" rxBuffer:" + BitConverter.ToString(rxBuffer6));

                        byte rfChannel2 = rxBuffer6[1];
                        Debug.WriteLine($"RF Channel 2 0x{RF_CH:x2} - Value 0X{rxBuffer6[1]:x2} - Value adjusted {rfChannel2+2400}");
                        Debug.WriteLine("");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Configure Port0 " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Esempio n. 19
0
 public string getDataAsString(int size)
 {
     return(BitConverter.ToString(getByteArray(size), 0));
 }
Esempio n. 20
0
 /// <summary>
 /// Convert an IBuffer to a hex string.
 /// </summary>
 /// <param name="buffer">The buffer.</param>
 /// <returns>A hex string.</returns>
 public static string ToHexString(IBuffer buffer)
 {
     CryptographicBuffer.CopyToByteArray(buffer, out byte[] data);
     return(BitConverter.ToString(data));
 }
Esempio n. 21
0
 private string HexEncode(byte[] bytes)
 {
     return(BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant());
 }
Esempio n. 22
0
 // 4
 /// <summary>
 /// Mã hóa chuỗi theo dạng MD5 ( chuỗi đầu vào: 123456 ->Chuỗi trả về e10adc3949ba59abbe56e057f20f883e)
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static string EncryptData(string data)
 {
     return(BitConverter.ToString(encrypt(data)).Replace("-", "").ToLower());
 }
Esempio n. 23
0
        private string Get16ByteMd5(string str)
        {
            MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider();

            return(BitConverter.ToString(mD5CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(str)), 4, 8).Replace("-", "").ToUpper());
        }
Esempio n. 24
0
 /// <summary>
 /// 将字节数组转换为没有分隔符的十六进制字符串。
 /// </summary>
 /// <param name="array">要转换的字节数组</param>
 /// <returns></returns>
 public static string ToStringNoSymbol(this byte[] array)
 {
     return(BitConverter.ToString(array).Replace("-", ""));
 }
Esempio n. 25
0
        private void HandleConnection()
        {
            byte[] bytes = new byte[300];

            try {
                try {
                    connecting = true;

                    try {
                        // Connect to a remote device.
                        ConnectSocketWithTimeout();

                        DebugLog("Socket connected to " + socket.RemoteEndPoint.ToString());

                        if (autostart)
                        {
                            socket.Send(STARTDT_ACT_MSG);
                            statistics.SentMsgCounter++;
                        }

                        running     = true;
                        socketError = false;
                        connecting  = false;

                        if (connectionHandler != null)
                        {
                            connectionHandler(connectionHandlerParameter, ConnectionEvent.OPENED);
                        }
                    } catch (SocketException se) {
                        DebugLog("SocketException: " + se.ToString());

                        running       = false;
                        socketError   = true;
                        lastException = se;

                        if (connectionHandler != null)
                        {
                            connectionHandler(connectionHandlerParameter, ConnectionEvent.CONNECT_FAILED);
                        }
                    }

                    if (running)
                    {
                        bool loopRunning = running;

                        while (loopRunning)
                        {
                            bool suspendThread = true;

                            try {
                                // Receive a message from from the remote device.
                                int bytesRec = receiveMessage(socket, bytes);

                                if (bytesRec > 0)
                                {
                                    DebugLog("RCVD: " + BitConverter.ToString(bytes, 0, bytesRec));

                                    statistics.RcvdMsgCounter++;

                                    bool handleMessage = true;

                                    if (recvRawMessageHandler != null)
                                    {
                                        handleMessage = recvRawMessageHandler(recvRawMessageHandlerParameter, bytes, bytesRec);
                                    }

                                    if (handleMessage)
                                    {
                                        if (checkMessage(socket, bytes, bytesRec) == false)
                                        {
                                            /* close connection on error */
                                            loopRunning = false;
                                        }
                                    }

                                    if (unconfirmedReceivedIMessages >= parameters.W)
                                    {
                                        lastConfirmationTime = SystemUtils.currentTimeMillis();

                                        unconfirmedReceivedIMessages = 0;
                                        SendSMessage();
                                    }

                                    suspendThread = false;
                                }
                                else if (bytesRec == -1)
                                {
                                    loopRunning = false;
                                }


                                if (handleTimeouts() == false)
                                {
                                    loopRunning = false;
                                }

                                if (isConnected() == false)
                                {
                                    loopRunning = false;
                                }

                                if (useSendMessageQueue)
                                {
                                    if (SendNextWaitingASDU() == true)
                                    {
                                        suspendThread = false;
                                    }
                                }

                                if (suspendThread)
                                {
                                    Thread.Sleep(10);
                                }
                            }
                            catch (SocketException) {
                                loopRunning = false;
                            }
                        }

                        DebugLog("CLOSE CONNECTION!");

                        // Release the socket.
                        try {
                            socket.Shutdown(SocketShutdown.Both);
                        }
                        catch (SocketException) {
                        }

                        socket.Close();

                        if (connectionHandler != null)
                        {
                            connectionHandler(connectionHandlerParameter, ConnectionEvent.CLOSED);
                        }
                    }
                } catch (ArgumentNullException ane) {
                    connecting = false;
                    DebugLog("ArgumentNullException: " + ane.ToString());
                } catch (SocketException se) {
                    DebugLog("SocketException: " + se.ToString());
                } catch (Exception e) {
                    DebugLog("Unexpected exception: " + e.ToString());
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            running    = false;
            connecting = false;
        }
Esempio n. 26
0
        public static Hashes CalculateHashes_here(string strPath, OnHashProgress onHashProgress, bool getCRC32,
                                                  bool getMD5,
                                                  bool getSHA1)
        {
            bool getED2k = true;

            logger.Trace("Using C# code to has file: {0}", strPath);

            FileStream fs;
            Hashes     rhash = new Hashes();
            FileInfo   fi    = new FileInfo(strPath);

            fs = fi.OpenRead();
            int lChunkSize = 9728000;

            long nBytes = fs.Length;

            long nBytesRemaining = fs.Length;
            int  nBytesToRead    = 0;

            long nBlocks    = nBytes / lChunkSize;
            long nRemainder = nBytes % lChunkSize; //mod

            if (nRemainder > 0)
            {
                nBlocks++;
            }

            byte[] baED2KHash = new byte[16 * nBlocks];

            if (nBytes > lChunkSize)
            {
                nBytesToRead = lChunkSize;
            }
            else
            {
                nBytesToRead = (int)nBytesRemaining;
            }

            onHashProgress?.Invoke(strPath, 0);

            MD4   md4   = MD4.Create();
            MD5   md5   = MD5.Create();
            SHA1  sha1  = SHA1.Create();
            Crc32 crc32 = new Crc32();

            byte[] ByteArray = new byte[nBytesToRead];

            long iOffSet     = 0;
            long iChunkCount = 0;

            while (nBytesRemaining > 0)
            {
                iChunkCount++;

                //logger.Trace("Hashing Chunk: " + iChunkCount.ToString());

                int nBytesRead = fs.Read(ByteArray, 0, nBytesToRead);

                if (getED2k)
                {
                    byte[] baHash = md4.ComputeHash(ByteArray, 0, nBytesRead);
                    int    j      = (int)((iChunkCount - 1) * 16);
                    for (int i = 0; i < 16; i++)
                    {
                        baED2KHash[j + i] = baHash[i];
                    }
                }

                if (getMD5)
                {
                    md5.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0);
                }
                if (getSHA1)
                {
                    sha1.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0);
                }
                if (getCRC32)
                {
                    crc32.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0);
                }

                int percentComplete = (int)(iChunkCount / (float)nBlocks * 100);
                onHashProgress?.Invoke(strPath, percentComplete);

                iOffSet        += lChunkSize;
                nBytesRemaining = nBytes - iOffSet;
                if (nBytesRemaining < lChunkSize)
                {
                    nBytesToRead = (int)nBytesRemaining;
                }
            }
            if (getMD5)
            {
                md5.TransformFinalBlock(ByteArray, 0, 0);
            }
            if (getSHA1)
            {
                sha1.TransformFinalBlock(ByteArray, 0, 0);
            }
            if (getCRC32)
            {
                crc32.TransformFinalBlock(ByteArray, 0, 0);
            }


            fs.Close();

            onHashProgress?.Invoke(strPath, 100);

            if (getED2k)
            {
                //byte[] baHashFinal = md4.ComputeHash(baED2KHash);
                //rhash.ed2k = BitConverter.ToString(baHashFinal).Replace("-", string.Empty).ToUpper();
                rhash.ED2K = nBlocks > 1
                    ? BitConverter.ToString(md4.ComputeHash(baED2KHash)).Replace("-", string.Empty).ToUpper()
                    : BitConverter.ToString(baED2KHash).Replace("-", string.Empty).ToUpper();
            }
            if (getCRC32)
            {
                rhash.CRC32 = BitConverter.ToString(crc32.Hash).Replace("-", string.Empty).ToUpper();
            }
            if (getMD5)
            {
                rhash.MD5 = BitConverter.ToString(md5.Hash).Replace("-", string.Empty).ToUpper();
            }
            if (getSHA1)
            {
                rhash.SHA1 = BitConverter.ToString(sha1.Hash).Replace("-", string.Empty).ToUpper();
            }
            return(rhash);
        }
Esempio n. 27
0
 public string GetHexString(string data, DataItem dataItem)
 {
     return(BitConverter.ToString(MapBytes(data, dataItem)));
 }
        [Category("NotWorking")]  // bug #79499
        public void LongMultipleGetBytes()
        {
            // based on http://bugzilla.ximian.com/show_bug.cgi?id=79499
            PasswordDeriveBytes pd = new PasswordDeriveBytes("mono", new byte[20]);
            string key             = BitConverter.ToString(pd.GetBytes(32));

            Assert.AreEqual("88-0A-AE-0A-41-61-02-78-FD-E2-70-9F-25-13-14-28-1F-C7-D9-72-9A-AE-CA-3F-BD-31-B4-F0-BD-8E-5B-98", key, "key");
            string iv = BitConverter.ToString(pd.GetBytes(16));

            Assert.AreEqual("FD-E2-70-9F-25-13-14-28-4D-3F-9B-F8-EE-AA-95-ED", iv, "iv");
            pd.Reset();
            // bytes from 32-40 are different from calling GetBytes separately
            Assert.AreEqual(key + "-F6-55-6C-3E-54-8B-F3-73-4D-3F-9B-F8-EE-AA-95-ED", BitConverter.ToString(pd.GetBytes(48)), "same");
        }
Esempio n. 29
0
 /// <summary>
 /// sha1加密
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string SHA1(string str)
 {
     byte[] cleanBytes  = Encoding.Default.GetBytes(str);
     byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
     return(BitConverter.ToString(hashedBytes).Replace("-", "").ToLower());
 }
Esempio n. 30
0
        public EsitoVerifica VerificaCertificato(byte[] certificateDER, byte[] certificateCAPEM, FirmaDigitale.FirmaDigitalePortTypeClient client)
        {
            logger.Debug("INIZIO");
            List <string> addiData = new List <string>();
            EsitoVerifica ev       = new EsitoVerifica();
            // FirmaDigitale.DettaglioFirmaDigitaleType ret = null;
            CertificateInfo ciInfo           = new CertificateInfo();
            sbyte?          controlloCRLCert = 0;
            sbyte?          controlloCRLCa   = 1;

            ciInfo.X509Certificate = certificateDER;
            ciInfo.ThumbPrint      = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(certificateDER)).Replace("-", "");

            controlloCRLCert = null;
            int statusInt = -1;

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Ssl3;
            DateTime dataverifica;

            try
            {
                logger.DebugFormat("len {0}", certificateDER.Length);
                FirmaDigitale.CertificatoType certOut = client.VerificaCertificato(certificateDER, certificateCAPEM, controlloCRLCert, controlloCRLCa, out dataverifica);
                logger.Debug("verificaOK");
                ciInfo    = convertFromCertificatoType(certOut);
                statusInt = 0;
            }

            catch (FaultException <FirmaDigitale.WarningCertificatoType> w)
            {
                string status = w.Detail.status;
                string errMsg = w.Detail.errorMsg;
                logger.Debug(status);
                logger.Debug(errMsg);
                addiData.Add(status);
                addiData.Add(errMsg);
                ciInfo = convertFromWarningCertificatoType(w.Detail);
                Int32.TryParse(w.Detail.status, out statusInt);
                ciInfo.RevocationStatus = statusInt;

                ev.errorCode = w.Detail.status.ToString();
                if (errMsg.ToLower().Contains("revoc"))
                {
                    ev.status = EsitoVerificaStatus.Revoked;
                }
                else
                {
                    ev.status = EsitoVerificaStatus.NotTimeValid;
                }
            }
            catch (Exception e)
            {
                logger.ErrorFormat("errore {0} {1}", e.Message, e.StackTrace);
                ev.message = e.Message;
            }

            // ciInfo.ThumbPrint = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(certificateDER)).Replace("-", "");
            ev.additionalData = addiData.ToArray();

            //quarda che devo fare per restituire il certificateinfo
            List <SignerInfo>    retSI = new List <SignerInfo>();
            List <PKCS7Document> p7doc = new List <PKCS7Document>();

            retSI.Add(new SignerInfo {
                CertificateInfo = ciInfo
            });
            p7doc.Add(new PKCS7Document {
                SignersInfo = retSI.ToArray()
            });
            ev.VerifySignatureResult = new VerifySignatureResult {
                StatusCode = statusInt, PKCS7Documents = p7doc.ToArray()
            };

            return(ev);
        }