예제 #1
0
        /// <summary>
        /// Key B for the sector. This needs to be set when setting the access conditions. Key could not be read from card
        /// </summary>
        ///

        public async Task SetKeyB(string Key)
        {
            int discarded;

            Byte[] keyB = HexEncoding.GetBytes(Key, out discarded);

            DataBlock db = await GetDataBlockInt(GetTrailerBlockIndex());

            Array.Copy(keyB, 0, db.Data, 10, 6);
        }
        public void InHexFormatTest()
        {
            string hexString = string.Empty; // TODO: Initialize to an appropriate value
            bool   expected  = false;        // TODO: Initialize to an appropriate value
            bool   actual;

            actual = HexEncoding.InHexFormat(hexString);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
예제 #3
0
파일: Packet.cs 프로젝트: yihuiliang/GK6X
        public void WriteHexString(string hexstring)
        {
            if (hexstring == null)
            {
                return;
            }
            int discarded;

            WriteBytes(HexEncoding.GetBytes(hexstring, out discarded));
        }
예제 #4
0
        /// <summary>
        /// Gets the specified collection key.
        /// </summary>
        /// <param name="collectionKey">The collection key.</param>
        /// <returns></returns>
        public string Get(string collectionKey)
        {
            byte[] bytes      = HexEncoding.GetBytes(collectionKey);
            string encodedKey = System.Text.Encoding.Default.GetString(bytes);

            //string decryptHexEncoded = _cryptographyService.Decrypt(collectionKey);
            PersistentCollection collection = _persistentCollectionRepository.Get(encodedKey);

            return(collection != null ? collection.Value : string.Empty);
        }
예제 #5
0
        private void DemandAscii(byte[] input, string expected)
        {
            var output = new byte[input.Length * 2];

            HexEncoding.WriteAscii(output, 0, output.Length,
                                   input, 0, input.Length);

            var actual = Encoding.ASCII.GetString(output);

            Assert.AreEqual(expected, actual);
        }
예제 #6
0
        public void ToBytesTest()
        {
            // Arrange
            byte[] expected = { 255, 170, 50 };

            // Act
            var actual = HexEncoding.ToBytes("FFAA32");

            // Assert
            Assert.Equal(expected, actual);
        }
예제 #7
0
        public void GetByteCountTest()
        {
            // Arrange
            var expected = 2;

            // Act
            var actual = HexEncoding.GetByteCount("FFA4");

            // Assert
            Assert.Equal(expected, actual);
        }
        private static string GetUniqCNonce()
        {
            string result = string.Empty;

            RandomNumberGenerator generator = RandomNumberGenerator.Create();

            byte[] data = new byte[8];
            generator.GetBytes(data);

            return(HexEncoding.ToString(data).ToLower());
        }
예제 #9
0
        public void GetBytes_RandomBytes()
        {
            var expected = new byte[1000];

            (new Random()).NextBytes(expected);

            var hexString = BitConverter.ToString(expected).Replace("-", "");
            var actual    = HexEncoding.GetBytes(hexString);

            CollectionAssert.AreEqual(expected, actual);
        }
예제 #10
0
        public void GetString_RandomBytes()
        {
            var buf = new byte[1000];

            (new Random()).NextBytes(buf);

            var expected = BitConverter.ToString(buf).Replace("-", "");
            var actual   = HexEncoding.GetString(buf);

            Assert.AreEqual(expected, actual);
        }
예제 #11
0
        public void GetString_AllByteValues()
        {
            var buf = new byte[1];

            for (byte testByte = 0; testByte < 0xff; testByte++)
            {
                buf[0] = testByte;
                var actual = HexEncoding.GetString(buf);
                Assert.AreEqual(testByte.ToString("X2"), actual);
            }
        }
예제 #12
0
        public void ResetLed(ICollection <string> rfps)
        {
            var unsetBusy = HexEncoding.HexToByte("0102000402010001");

            foreach (var rfp in rfps)
            {
                var rfpIdentifier = new RfpIdentifier(HexEncoding.HexToByte(rfp));
                var write         = WriteAsync(MessageDirection.ToRfp, 0, rfpIdentifier, unsetBusy, CancellationToken.None);
                write.GetAwaiter().GetResult();
            }
        }
예제 #13
0
        /// <summary>
        /// Takes an encrypted key in the form of a string as input
        /// and applies the DES encryption algorithm to produce an
        /// unencrypted byte array
        /// </summary>
        /// <param name="strEncryptedKey">Encrypted security key</param>
        /// <returns></returns>
        //  Revision History
        //  MM/DD/YY Who Version Issue# Description
        //  -------- --- ------- ------ -------------------------------------------
        //  06/21/13 RCG 2.70.77        Copied from CENTRON_AMI

        private byte[] DecryptHANKey(string strEncryptedKey)
        {
            int Discarded;

            SecureDataStorage        DataStorage     = null;
            DESCryptoServiceProvider Crypto          = null;
            MemoryStream             EncryptedStream = null;
            MemoryStream             DecryptedStream = null;
            string       strDecryptedKey             = null;
            StreamReader sr = null;

            try
            {
                DataStorage = new SecureDataStorage(SecureDataStorage.DEFAULT_LOCATION);
                Crypto      = new DESCryptoServiceProvider();
                Crypto.Key  = DataStorage.RetrieveSecureData(SecureDataStorage.ZIGBEE_KEY_ID);
                Crypto.IV   = DataStorage.RetrieveSecureData(SecureDataStorage.ZIGBEE_IV_ID);


                byte[] EncryptedKey = HexEncoding.GetBytes(strEncryptedKey, out Discarded);

                //Create a memory stream to the passed buffer.
                EncryptedStream = new MemoryStream(EncryptedKey);
                DecryptedStream = new MemoryStream();

                Encryption.DecryptData(Crypto, EncryptedStream, DecryptedStream);

                //We must rewind the stream
                DecryptedStream.Position = 0;

                // Create a StreamReader for reading the stream.
                sr = new StreamReader(DecryptedStream);

                // Read the stream as a string.
                strDecryptedKey = sr.ReadLine();
            }
            finally
            {
                // Close the streams.
                //Closing sr also closes DecryptedStream
                if (null != sr)
                {
                    sr.Close();
                }
                else
                {
                    DecryptedStream.Close();
                }
                EncryptedStream.Close();
                Crypto.Dispose();
            }
            //Transform the string into a byte array
            return(HexEncoding.GetBytes(strDecryptedKey, out Discarded));
        }
예제 #14
0
 public void GetBytes_ShouldThrowArgumentNullException_WhenInputIsNotDivisibleByTwo(string value, bool throwsException)
 {
     if (throwsException)
     {
         Assert.Throws <ArgumentException>(() => HexEncoding.GetBytes(value));
     }
     else
     {
         Assert.IsType <byte[]>(HexEncoding.GetBytes(value));
     }
 }
예제 #15
0
 public void ConvertCharToByte_ShouldThrowArgumentOutOfRangeException_WhenInputIsNotValid(char c, bool throwsException)
 {
     if (throwsException)
     {
         Assert.Throws <ArgumentOutOfRangeException>(() => HexEncoding.ConvertCharToByte(c));
     }
     else
     {
         Assert.IsType <byte>(HexEncoding.ConvertCharToByte(c));
     }
 }
예제 #16
0
        public static IProxie Create(int transactionId, Trunk trunk, ByteArrayPart toTag)
        {
            int    tag;
            Dialog dialog1 = null;

            if (HexEncoding.TryParseHex8(toTag, out tag))
            {
                dialog1 = trunk.GetDialog1(tag);
            }

            return((dialog1 == null) ? null : new TrunkDialogProxie(transactionId, trunk, tag, dialog1));
        }
예제 #17
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.annoy && this.openFileDialog1.get_FileName() != "")
            {
                try
                {
                    FileStream fileStream = new FileStream(this.openFileDialog1.get_FileName(), 3, 3, 0);
                    if (this.sigentered)
                    {
                        byte[] signature = new byte[4];
                        byte[] array     = new byte[4];
                        byte[] array2    = new byte[4];
                        int    num;

                        // This var takes the sig entered by user and returns an array using HexEncoding class
                        signature = HexEncoding.GetBytes(this.siggy.get_Text(), out num);
                        // array2 is set equal to the array returned by the Magic function which does something w/ it?
                        array2 = this.Magic(signature);
                        // FS is set to 4 bytes before the end of the file
                        fileStream.Seek(fileStream.get_Length() - 4L, 0);
                        // Write array2 to last 4 bytes of the file
                        BinaryWriter binaryWriter = new BinaryWriter(fileStream);
                        binaryWriter.Write(array2);
                        // Pass FS in blocks of 4096 bytes to signMap function - which writes the signature
                        this.signMap(4096, fileStream);

                        // Re-read the signature from map
                        string text = HexEncoding.ToString(this.ReadSig(fileStream));
                        // Put signature in textbox
                        this.label3.set_Text("Map Signature: " + text);
                        // Read signature from map again?????????
                        array = this.ReadSig(fileStream);
                        // Goto last 4 bytes
                        fileStream.Seek(fileStream.get_Length() - 4L, 0);
                        BinaryWriter binaryWriter2 = new BinaryWriter(fileStream);
                        // Write sig to last 4 bytes
                        binaryWriter2.Write(this.Magic(array));
                        // XOr through again at 4096 bytes and write signature to 720
                        this.signMap(4096, fileStream);

                        // Re-re-read the freakin signature and set the label equal to it
                        array = this.ReadSig(fileStream);
                        text  = HexEncoding.ToString(array);
                        this.label3.set_Text("Map Signature: " + text + " Complete!");
                    }
                    fileStream.Close();
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.get_Message(), "Error Accessing File");
                }
            }
        }
예제 #18
0
        public void TestToFromHex()
        {
            byte[] all = new byte[256];
            for (int i = 0; i < all.Length; i++)
            {
                all[i] = (byte)i;
            }

            Assert.AreEqual(AllHex, HexEncoding.EncodeBytes(all));
            Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex)));
            Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex.ToUpper())));
        }
예제 #19
0
        private void LicenseInfoDlg_Load(object sender, EventArgs e)
        {
            string[]      vsMacs = MacAddr.GetMacs();
            StringBuilder sb     = new StringBuilder();

            sb.Append(_sVer);   // version
            sb.Append('|');
            sb.Append(vsMacs.Length.ToString());
            sb.Append('|');
            foreach (string sMac in vsMacs)
            {
                sb.Append(sMac);
                sb.Append('|');
            }
            sb.Append(SystemInformation.ComputerName);

            string str;
            // Attempt to get Windows Registration info
            RegistryKey regKey = Registry.LocalMachine.OpenSubKey(MainFrm.WIN_REG_KEY, true);

            if (regKey != null)
            {
                str = regKey.GetValue("RegisteredOwner") as string;
                sb.Append('|');
                sb.Append(str);
                str = regKey.GetValue("RegisteredOrganization") as string;
                sb.Append('|');
                sb.Append(str);
            }
            else
            {
                sb.Append("||");
            }
            str = sb.ToString();

            Rijndael encryptor = Encryption.GetLicenseEncryptor(MainFrm.ProdKey);

            byte[] vData = Encryption.EncryptString(encryptor, str);
            str = HexEncoding.ToString(vData);

            TxtMachineId.Text = str;

            if (!string.IsNullOrEmpty(MainFrm.TheAppWnd.LicenseInfo.LicName))
            {
                LblRegName.Text = MainFrm.TheAppWnd.LicenseInfo.LicName;
            }

            if (MainFrm.TheAppWnd.LicenseInfo.ExpiryDate > DateTime.MinValue)
            {
                LblExpiryDate.Text = MainFrm.TheAppWnd.LicenseInfo.ExpiryDate.ToShortDateString();
            }
        }
예제 #20
0
            //public bool IsResponseValid(ByteArrayPart username, ByteArrayPart realm,
            //    bool isMd5SessAlgorithm, ByteArrayPart nonce, ByteArrayPart cnonce,
            //    ByteArrayPart qop, ByteArrayPart digestUri, ByteArrayPart nonceCountBytes,
            //    ByteArrayPart method, ArraySegment<byte> body, ByteArrayPart password)
            //{
            //    byte[] ha1 = CalculateHa1(username, realm, isMd5SessAlgorithm, nonce, cnonce, password);
            //    byte[] ha2 = CalculateHa2(qop, digestUri, method, body);
            //    byte[] response = CalculateResponse(nonce, qop, nonceCountBytes, cnonce, ha1, ha2);

            //    HexEncoding.GetLowerHexChars(response, bytes32); // ?? что если ответ будет в upper case
            //    return cred.Response.Equals(bytes32);
            //}

            public byte[] GetResponseHexChars(ByteArrayPart username, ByteArrayPart realm,
                                              bool isMd5SessAlgorithm, ByteArrayPart nonce, ByteArrayPart cnonce,
                                              ByteArrayPart qop, ByteArrayPart digestUri, ByteArrayPart nonceCountBytes,
                                              ByteArrayPart method, ArraySegment <byte> body, ByteArrayPart password)
            {
                byte[] ha1      = CalculateHa1(username, realm, isMd5SessAlgorithm, nonce, cnonce, password);
                byte[] ha2      = CalculateHa2(qop, digestUri, method, body);
                byte[] response = CalculateResponse(nonce, qop, nonceCountBytes, cnonce, ha1, ha2);

                HexEncoding.GetLowerHexChars(response, bytes32);                 // ?? что если ответ будет в upper case

                return(bytes32);
            }
예제 #21
0
        private ulong Read24bits(string value)
        {
            _logger.LogTrace("Enter - value: {value}", value);

            if (string.IsNullOrEmpty(value))
            {
                return(ulong.MaxValue);
            }

            byte[] buffer = HexEncoding.HexStringToByteArray(value + "0000000000"); // todo: fix this quick fix... array length not sufficient for ulong
            //Array.Reverse(buffer);
            return(BitConverter.ToUInt64(buffer, 0));
        }
예제 #22
0
        public void TestWriteHexStream()
        {
            using (Stream mem = new MemoryStream())
            {
                using (Stream io = new HexStream(new NonClosingStream(mem), CryptoStreamMode.Write))
                    io.Write(HexEncoding.DecodeBytes(AllHex), 0, AllHex.Length / 2);

                Assert.AreEqual(AllHex.Length, mem.Position);
                mem.Position = 0;
                string test = new StreamReader(mem).ReadToEnd();
                Assert.AreEqual(AllHex, test);
            }
        }
        public void GetBytesTest()
        {
            string hexString         = string.Empty; // TODO: Initialize to an appropriate value
            int    discarded         = 0;            // TODO: Initialize to an appropriate value
            int    discardedExpected = 0;            // TODO: Initialize to an appropriate value

            byte[] expected = null;                  // TODO: Initialize to an appropriate value
            byte[] actual;
            actual = HexEncoding.GetBytes(hexString, out discarded);
            Assert.AreEqual(discardedExpected, discarded);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
예제 #24
0
        public void ToStringTest()
        {
            // Arrange
            var expected = "FFAA32";

            byte[] bytes = { 255, 170, 50 };

            // Act
            var actual = HexEncoding.ToString(bytes);

            // Arrange
            Assert.Equal(expected, actual);
        }
예제 #25
0
        private void ProccessPublish(AcceptedRequest tu, IncomingMessageEx request)
        {
            StatusCodes statusCode = StatusCodes.OK;

            int expires = request.Reader.GetExpires(600, 900);

            if (request.Reader.IsExpiresTooBrief(60))
            {
                statusCode = StatusCodes.IntervalTooBrief;
            }

            int sipIfMatch = simpleModule.InvalidEtag;

            if (statusCode == StatusCodes.OK)
            {
                if (request.Reader.SipIfMatch.Length == 8)
                {
                    if (HexEncoding.TryParseHex8(request.Reader.SipIfMatch.Bytes, request.Reader.SipIfMatch.Begin, out sipIfMatch) == false)
                    {
                        statusCode = StatusCodes.CallLegTransactionDoesNotExist;
                    }
                }
            }

            if (statusCode == StatusCodes.OK)
            {
                var fromUser = request.Reader.From.AddrSpec.User.ToString();
                var fromHost = request.Reader.From.AddrSpec.Hostport.Host.ToString();
                if (simpleModule.Publish(fromUser + "@" + fromHost, ref sipIfMatch, expires, request.Content) == false)
                {
                    statusCode = StatusCodes.BadRequest;
                }
            }

            var writer = GetWriter();

            if (statusCode == StatusCodes.OK)
            {
                writer.WriteStatusLine(statusCode);
                writer.CopyViaToFromCallIdRecordRouteCSeq(request.Reader, statusCode);
                writer.WriteExpires(expires);
                writer.WriteSipEtag(sipIfMatch);
                writer.WriteCRLF();
            }
            else
            {
                writer.WriteResponse(request.Reader, statusCode);
            }

            SendResponse(request, writer);
        }
예제 #26
0
        // TODO: CreateStoreResponse non serve proprio a niente??

        public void CreateFindValueRequest(string key)
        {
            // Calcolo lunghezza dei dati
            byte[] bkey = HexEncoding.GetBytes(key);
            //byte[] bFakeKey = new byte[Settings.ID_LENGTH];
            //Array.Copy(bkey, bFakeKey, bkey.Length);

            CreateHeader(Header.EvolutionDHT, Settings.ID_LENGTH);
            finalMessage[1] = (byte)Opcode.FindvalueRequest;

            // Dati
            //bFakeKey.CopyTo(finalMessage, 4);
            bkey.CopyTo(finalMessage, 4);
        }
예제 #27
0
 public void GetBytes_ThrowsExceptionForAllInvalidCharacters()
 {
     for (ushort testChar = 0; testChar < ushort.MaxValue; testChar++)
     {
         var c = (char)testChar;
         if (char.IsDigit(c) ||
             c == 'A' || c == 'B' || c == 'C' || c == 'D' || c == 'E' || c == 'F' ||
             c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
         {
             continue; // skip valid chars
         }
         Assert.ThrowsException <FormatException>(() => HexEncoding.GetBytes("0" + new string(new char[] { c })));
     }
 }
        public void IsHexDigitBadValuesTest()
        {
            char[] c = new char[9] {
                'g', 'G', '-', '_', '^', '?', '&', 'q', 'z'
            };
            bool expected = false;

            foreach (var item in c)
            {
                bool actual;
                actual = HexEncoding.IsHexDigit(item);
                Assert.AreEqual(expected, actual, item + " : is not an HEX digit");
            }
        }
        public void IsHexDigitGoodValuesTest()
        {
            char[] c = new char[22] {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'
            };
            bool expected = true;

            foreach (var item in c)
            {
                bool actual;
                actual = HexEncoding.IsHexDigit(item);
                Assert.AreEqual(expected, actual, item + " : is HEX digit");
            }
        }
 public RSACryptoServiceProvider GetProvider()
 {
     RSACryptoServiceProvider retValue = new RSACryptoServiceProvider();
     Byte[] cspBlob;
     if (!String.IsNullOrEmpty(PrivateKey))
     {
         cspBlob = HexEncoding.GetBytes(PrivateKey);
     }
     else
     {
         cspBlob = HexEncoding.GetBytes(PublicKey);
     }
     retValue.ImportCspBlob(cspBlob);
     return retValue;
 }