Ejemplo n.º 1
0
        /// <summary>
        /// The function Exchange sends a command APDU to a smart card and returns the response ADPU from the card.
        /// </summary>
        /// <param name="cmdApdu">Hexadecimal  string containing the command APDU.</param>
        /// <param name="expectedSW1SW2">The expected status word SW1SW2.</param>
        /// <returns></returns>
        public RespApdu Exchange(string cmdApdu, ushort?expectedSW1SW2)
        {
            byte[]   responseBuffer = this.Exchange(HexEncoding.GetBytes(cmdApdu), expectedSW1SW2);
            RespApdu respApdu       = new RespApdu(responseBuffer);

            return(respApdu);
        }
Ejemplo n.º 2
0
        private byte[] BuildSelectRcpPacket()
        {
            ByteBuilder bb = new ByteBuilder();
            int         discard;

            byte[] param = new byte[7];

            param[0] = (byte)
                       ((comboBoxSelTarget.SelectedIndex << 5)
                        + (comboBoxSelAction.SelectedIndex << 2)
                        + (comboBoxSelMemBank.SelectedIndex));
            param[1] = 0;
            param[2] = 0;
            param[3] = (byte)((Convert.ToUInt16(tbSelPointer.Text, 16) & 0xFF00) >> 8);
            param[4] = (byte)((Convert.ToUInt16(tbSelPointer.Text, 16) & 0x00FF));
            param[5] = byte.Parse(tbSelLength.Text);
            param[6] = 0;

            bb.Append(param);

            byte[] mask = HexEncoding.GetBytes(tbSelMask.Text, out discard);
            Array.Resize(ref mask, ((param[5] + 7) / 8));

            if (mask.Length > 0)
            {
                bb.Append(mask);
            }

            return(bb.GetByteArray());
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <param name="dataMode"></param>
        /// <returns></returns>
        protected byte[] StringToBytes(string str, Encoding encoding, DataMode dataMode)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            byte[] byteArray = new byte[0];
            switch (dataMode)
            {
            case DataMode.Plain:
                byteArray = encoding.GetBytes(str);
                break;

            case DataMode.Hex:
                byteArray = HexEncoding.GetBytes(str);
                break;

            case DataMode.Base64:
                byteArray = Convert.FromBase64String(str);
                break;
            }

            return(byteArray);
        }
Ejemplo n.º 4
0
 // costruttore aggiunto temporaneamente per eliminare il ricalcolo dell'hash della key ogni volta
 public AncestorThread(Client client, string key)
 {
     thread      = new Thread(Run);
     this.client = client;
     this.keyId  = new PeerId();
     keyId.Id    = HexEncoding.GetBytes(key);
 }
Ejemplo n.º 5
0
            public void WriteHexString(string HexString)
            {
                int _out;

                byte[] _byte = HexEncoding.GetBytes(HexString, out _out);
                WriteArray(_byte);
            }
Ejemplo n.º 6
0
        // TODO: Chiamare key il parametro non è un po' fuorviante?!
        public static PeerId LoadFromString(string key)
        {
            PeerId id = new PeerId();

            //int discarded;
            id.buffer = HexEncoding.GetBytes(key);
            return(id);
        }
 public static EncryptionKey CreateFromSerializedString(String serializedString)
 {
     EncryptionKey retValue = new EncryptionKey();
     var splitted = serializedString.Split('|');
     retValue.Key = HexEncoding.GetBytes(splitted[0]);
     retValue.IV = HexEncoding.GetBytes(splitted[1]);
     return retValue;
 }
Ejemplo n.º 8
0
        public void OddNumberOfHexDigitsShouldRoundTripWithLeadingZero()
        {
            var hex   = "A12F5";
            var bytes = HexEncoding.GetBytes(hex);
            var hex2  = HexEncoding.GetString(bytes);

            Assert.Equal("0" + hex.ToLower(), hex2.ToLower());
        }
Ejemplo n.º 9
0
        public void HexStringsShouldRoundTrip()
        {
            var hex   = "0A12F5";
            var bytes = HexEncoding.GetBytes(hex);
            var hex2  = HexEncoding.GetString(bytes);

            Assert.Equal(hex.ToLower(), hex2.ToLower());
        }
Ejemplo n.º 10
0
        public void NotCaseSensitive()
        {
            var hex      = "0a12F5";
            var expected = new byte[] { 10, 18, 245 };
            var actual   = HexEncoding.GetBytes(hex);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 11
0
        public void LeadingAndTrailingWhiteSpaceIgnored()
        {
            var hex      = "  0A12F5\t\r\n";
            var expected = new byte[] { 10, 18, 245 };
            var actual   = HexEncoding.GetBytes(hex);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 12
0
        public void EvenNumberOfHexDigitsCanBeConvertedToBytes()
        {
            var hex      = "0A12F5";
            var expected = new byte[] { 10, 18, 245 };
            var actual   = HexEncoding.GetBytes(hex);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 13
0
        public void ByteArraysShouldRoundTrip()
        {
            var bytes  = new byte[] { 10, 18, 245 };
            var hex    = HexEncoding.GetString(bytes);
            var bytes2 = HexEncoding.GetBytes(hex);

            Assert.Equal(bytes, bytes2);
        }
        private void protocol(string data)
        {
            try
            {
                string header = data.Substring(1, 2);
                string body   = data.Substring(2);

                switch (header)
                {
                    #region Crypto

                case "AQ":
                case "AP":
                    if (LemonEnvironment.cryptoActive)
                    {
                        return;
                    }

                    // Client key
                    LemonEnvironment.clientKey = body.Substring(5);

                    // Make sure we have the keys from the haxswf - otherwise we'll get a null ref
                    while (LemonEnvironment.decPublicKey == null || LemonEnvironment.encPublicKey == null)
                    {
                        ;
                    }

                    // Send the client key
                    LemonEnvironment.mainWnd.SendClientKey();
                    Thread.Sleep(600);

                    // send our own key
                    data = "_R" + MikeUtils.encodeB64(LemonEnvironment.encPublicKey) + LemonEnvironment.encPublicKey;
                    data = "@" + MikeUtils.encodeB64(data) + data;

                    // Once again, make sure we've got a key to init decryption with
                    // otherwise we'll get a null ref
                    while (LemonEnvironment.sharedKeyDec == null)
                    {
                        ;
                    }
                    LemonEnvironment.RC4D = new Crypto.MikeCrypto(HexEncoding.GetBytes(LemonEnvironment.sharedKeyDec), LemonEnvironment.padding2);

                    break;

                    #endregion

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            server.Send(data);
        }
Ejemplo n.º 15
0
 public void GetBytes_AllLowerCaseHexChars()
 {
     for (byte testByte = 0; testByte < 0xff; testByte++)
     {
         var actual = HexEncoding.GetBytes(testByte.ToString("x2"));
         Assert.AreEqual(1, actual.Length);
         Assert.AreEqual(testByte, actual[0]);
     }
 }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
0
        public void WriteHexString(string hexstring)
        {
            if (hexstring == null)
            {
                return;
            }
            int discarded;

            WriteBytes(HexEncoding.GetBytes(hexstring, out discarded));
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
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));
        }
Ejemplo n.º 21
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));
     }
 }
Ejemplo n.º 22
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");
                }
            }
        }
        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.");
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
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 })));
     }
 }
Ejemplo n.º 26
0
 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;
 }
Ejemplo n.º 27
0
        public void CreateFindValueResponse(string key, string val)
        {
            // Calcolo lunghezza dei dati
            byte[] bkey = HexEncoding.GetBytes(key);
            //byte[] bFakeKey = new byte[Settings.ID_LENGTH];
            //Array.Copy(bkey, bFakeKey, bkey.Length);
            byte[] bval = UTF8Encoding.ASCII.GetBytes(val);

            CreateHeader(Header.EvolutionDHT, Settings.ID_LENGTH + bval.Length);
            finalMessage[1] = (byte)Opcode.FindvalueResponse;

            // Dati
            //bFakeKey.CopyTo(finalMessage, 4);
            bkey.CopyTo(finalMessage, 4);
            bval.CopyTo(finalMessage, Settings.ID_LENGTH + 4);
        }
Ejemplo n.º 28
0
            public static String Decrypt(Byte[] key, Byte[] iv, String data)
            {
                using (MemoryStream ms = new MemoryStream())
                    using (RijndaelManaged crypto = new RijndaelManaged())
                    {
                        Byte[]           rawData = HexEncoding.GetBytes(data);
                        ICryptoTransform ct      = crypto.CreateDecryptor(key, iv);
                        using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
                        {
                            cs.Write(rawData, 0, rawData.Length);
                            cs.Close();
                        }

                        return(Encoding.UTF8.GetString(ms.ToArray()));
                    }
            }
        /// <summary>
        /// Gets the custom WZ IV from settings
        /// </summary>
        /// <returns></returns>
        public byte[] GetCusomWzIVEncryption()
        {
            bool loaded = Load();

            if (loaded)
            {
                string storedCustomEnc = ApplicationSettings.MapleVersion_EncryptionBytes;
                byte[] bytes           = HexEncoding.GetBytes(storedCustomEnc);

                if (bytes.Length == 4)
                {
                    return(bytes);
                }
            }
            return(new byte[4]); // fallback with BMS
        }
Ejemplo n.º 30
0
 public static AsymmetricEncryptionKey CreateFromString(String key, Boolean containsPrivateKey)
 {
     var cspBlob = HexEncoding.GetBytes(key);
     using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
     {
         rsa.ImportCspBlob(cspBlob);
         var publicKey = BitConverter.ToString(rsa.ExportCspBlob(false)).Replace("-", "");
         String privateKey = "";
         if (containsPrivateKey)
         {
             privateKey = BitConverter.ToString(rsa.ExportCspBlob(true)).Replace("-", "");
         }
         return new AsymmetricEncryptionKey() {
             PublicKey = publicKey,
             PrivateKey = privateKey,
         };
     }
 }