Example #1
0
        public static void Main()
        {
            byte[]   dataBytes  = new byte[] { 0x30, 0x1E, 0x17, 0x0D, 0x31, 0x32, 0x30, 0x34, 0x32, 0x37, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A, 0x17, 0x0D, 0x32, 0x32, 0x30, 0x34, 0x32, 0x35, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A };
            Asn1Data asn1Reader = Asn1Parser.ParseFromRawData(dataBytes);

            Asn1Logger.LogCurrentNodeValues(asn1Reader, "Validity");

            bool isMovedNext = Asn1Parser.MoveNext(asn1Reader);

            if (isMovedNext)
            {
                Asn1Logger.LogCurrentNodeValues(asn1Reader, "StartDate");
                isMovedNext = Asn1Parser.MoveNext(asn1Reader);
                if (isMovedNext)
                {
                    Asn1Logger.LogCurrentNodeValues(asn1Reader, "EndDate");
                }
                else
                {
                    Logger.writeLog("ERROR-Can not move to EndDate");
                }
            }
            else
            {
                Logger.writeLog("ERROR-Can not move to StartDate");
            }
        }
    public bool parseAsn1Data(byte[] val)
    {
        if (val == null)
        {
            return(false);
        }
        Asn1Parser p      = new Asn1Parser();
        var        stream = new MemoryStream(val);

        try
        {
            p.LoadData(stream);
        }
        catch (Exception e)
        {
            return(false);
        }
        Asn1Node root = p.RootNode;

        if (root == null)
        {
            return(false);
        }
        PurchaseReceipts = new Dictionary <string, AppleInAppPurchaseReceipt>();
        parseNodeRecursive(root);
        return(!string.IsNullOrEmpty(BundleIdentifier));
    }
Example #3
0
        public static void Main()
        {
            byte[] validityDataBytes = new byte[] { 0x30, 0x1E, 0x17, 0x0D, 0x31, 0x32, 0x30, 0x34, 0x32, 0x37, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A, 0x17, 0x0D, 0x32, 0x32, 0x30, 0x34, 0x32, 0x35, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A };
            Storage.Put(Storage.CurrentContext, "Validity Data Encoded", validityDataBytes);

            Asn1Data asn1Data = Asn1Parser.ParseFromRawData(validityDataBytes);

            bool isMovedNext = Asn1Parser.MoveNext(asn1Data);

            if (isMovedNext)
            {
                byte[] notBeforeByte = Asn1Utils.DecodeDateTime(asn1Data);
                Storage.Put(Storage.CurrentContext, "notBefore", notBeforeByte);
                isMovedNext = Asn1Parser.MoveNext(asn1Data);
                if (isMovedNext)
                {
                    byte [] notAfterByte = Asn1Utils.DecodeDateTime(asn1Data);
                    Storage.Put(Storage.CurrentContext, "notAfter", notAfterByte);
                }
                else
                {
                    Logger.writeLog("ERROR-Can not move to EndDate");
                }
            }
            else
            {
                Logger.writeLog("ERROR-Can not move to StartDate");
            }
        }
Example #4
0
        public static void Main()
        {
            byte[] dataBytes = new byte[] { 0x30, 0x1E, 0x17, 0x0D, 0x31, 0x32, 0x30, 0x34, 0x32, 0x37, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A, 0x17, 0x0D, 0x32, 0x32, 0x30, 0x34, 0x32, 0x35, 0x31, 0x30, 0x33, 0x31, 0x31, 0x38, 0x5A };
            Asn1Logger.LogByteArray("Encoded Validity: ", dataBytes);

            Asn1Data asn1Data = Asn1Parser.ParseFromRawData(dataBytes);

            bool isMovedNext = Asn1Parser.MoveNext(asn1Data);

            if (isMovedNext)
            {
                // byte[] notBeforeByte = Asn1Utils.DecodeDateTime(asn1Data);
                Asn1Logger.LogCurrentNodeValues(asn1Data, "notBefore");
                // Asn1Logger.LogByteArray("Validity-NotBefore: ", notBeforeByte);
                isMovedNext = Asn1Parser.MoveNext(asn1Data);
                if (isMovedNext)
                {
                    //  byte[] notAfterByte = Asn1Utils.DecodeDateTime(asn1Data);
                    Asn1Logger.LogCurrentNodeValues(asn1Data, "notAfter");
                    //Asn1Logger.LogByteArray("Validity-NotAfter: ", notAfterByte);
                }
                else
                {
                    Logger.writeLog("ERROR-Can not move to EndDate");
                }
            }
            else
            {
                Logger.writeLog("ERROR-Can not move to StartDate");
            }
        }
Example #5
0
        public static bool IsCertInCRL(byte[] crl, X509Certificate2 cert)
        {
            var asnParser = new Asn1Parser();
            var strCRL    = Asn1Util.BytesToString(crl);

            if (Asn1Util.IsPemFormated(strCRL))
            {
                asnParser.LoadData(Asn1Util.PemToStream(strCRL));
            }
            else
            {
                asnParser.LoadData(new MemoryStream(crl));
            }

            if (7 > asnParser.RootNode.GetChildNode(0).ChildNodeCount)
            {
                return(false); // empty CRL
            }
            var revokedCertificates = asnParser.RootNode.GetChildNode(0).GetChildNode(5);

            // throw revoked certs into a list so someday we eventually cache CRLs
            var revoked = new List <long>();

            for (var i = 0; i < revokedCertificates.ChildNodeCount; i++)
            {
                revoked.Add(Asn1Util.BytesToLong(revokedCertificates.GetChildNode(i)
                                                 .GetChildNode(0)
                                                 .Data
                                                 .Reverse()
                                                 .ToArray()));
            }

            return(revoked.Contains(Asn1Util.BytesToLong(cert.GetSerialNumber())));
        }
Example #6
0
        public void Serializing_and_deserializing_a_private_key_should_result_in_equal_keys()
        {
            // Arrange
            var rsa            = new RSACryptoServiceProvider(2048);
            var rsaParameters  = rsa.ExportParameters(true);
            var asn1Parser     = new Asn1Parser();
            var rsaParser      = new RSAPrivateKeyParser(asn1Parser);
            var asn1Serializer = new Asn1Serializer();
            var asn1Rsa        = new RSAPrivateKey(rsaParameters);

            // Act
            var serializedPEM = asn1Serializer.Serialize(asn1Rsa).ToArray().EncodeAsPEM(PEMExtensions.RSAPrivateKey);
            var parsedRsaKey  = rsaParser.ParsePem(new MemoryStream(Encoding.ASCII.GetBytes(serializedPEM)));

            //TODO this test sometimes has a missing leading '0' byte.


            // Assert
            parsedRsaKey.Key.Exponent.Should().Equal(rsaParameters.Exponent);
            parsedRsaKey.Key.Modulus.Should().Equal(rsaParameters.Modulus);
            parsedRsaKey.Key.P.Should().Equal(rsaParameters.P);
            parsedRsaKey.Key.D.Should().Equal(rsaParameters.D);
            parsedRsaKey.Key.DP.Should().Equal(rsaParameters.DP);
            parsedRsaKey.Key.Q.Should().Equal(rsaParameters.Q);
            parsedRsaKey.Key.DQ.Should().Equal(rsaParameters.DQ);
            parsedRsaKey.Key.InverseQ.Should().Equal(rsaParameters.InverseQ);
        }
Example #7
0
        public static byte[] Decode(byte[] rawData)
        {
            Asn1Data asn1Data = Asn1Parser.ParseFromRawData(rawData);

            //todo: convert byte string to ulong date
            return(Asn1Parser.GetPayload(asn1Data));
        }
Example #8
0
            /// <summary>
            /// Initializes a new instance of the <see cref="MibSource"/> class.
            /// The MIB will be read from the specified URL.
            /// </summary>
            /// <param name="url">The URL to read from</param>
            public MibSource(Uri url)
            {
                this.url = url;

                parser = null;
                input  = null;
                File   = null;
            }
Example #9
0
        public static RSAPrivateKey ParsePem(string pem)
        {
            var asn1Parser = new Asn1Parser();

            var rsaParser = new RSAPrivateKeyParser(asn1Parser);

            return(rsaParser.ParsePem(pem));
        }
Example #10
0
 public static PKCS7 Load(byte[] data)
 {
     using (var stm = new System.IO.MemoryStream(data)) {
         Asn1Parser parser = new Asn1Parser();
         parser.LoadData(stm);
         return(new PKCS7(parser.RootNode));
     }
 }
Example #11
0
            /// <summary>
            /// Initializes a new instance of the <see cref="MibSource"/> class.
            /// The MIB will be read from the specified input reader. The
            /// input reader will be closed after reading the MIB.
            /// </summary>
            /// <param name="input">The input stream to read from</param>
            public MibSource(TextReader input)
            {
                this.input = input;

                parser = null;
                url    = null;
                File   = null;
            }
Example #12
0
            /// <summary>
            /// Initializes a new instance of the <see cref="MibSource"/> class.
            /// The MIB will be read from the specified file.
            /// </summary>
            /// <param name="file">The file to read from</param>
            public MibSource(string file)
            {
                this.File = file;

                parser = null;
                url    = null;
                input  = null;
            }
Example #13
0
            /// <summary>
            /// Parses the MIB input source and returns the MIB modules
            /// found. This method will read the MIB either from file, URL
            /// or input stream.
            /// </summary>
            /// <param name="loader">The MIB loader to use for imports</param>
            /// <param name="log">The MIB log to use for errors</param>
            /// <returns>The list of MIB modules created</returns>
            /// <exception cref="IOException">If the MIB couldn't be found</exception>
            /// <exception cref="MibLoaderException">
            /// If the MIB couldn't be parsed correctly
            /// </exception>
            public IList <Mib> ParseMib(MibLoader loader, MibLoaderLog log)
            {
                string result = string.Empty;

                // Open input stream
                if (this.input != null)
                {
                    result = this.input.ReadToEnd();
                }
                else if (this.url != null)
                {
                    using (var client = new System.Net.WebClient())
                    {
                        result = client.DownloadString(this.url);
                    }
                }
                else
                {
                    using (TextReader reader = System.IO.File.OpenText(this.File))
                    {
                        result = reader.ReadToEnd();
                    }
                }

                using (this.input = new StringReader(result))
                {
                    // Parse input stream
                    MibAnalyzer analyzer = new MibAnalyzer(this.File, loader, log);
                    try
                    {
                        if (parser == null)
                        {
                            Asn1Tokenizer tokenizer = new Asn1Tokenizer(this.input);
                            parser = new Asn1Parser(tokenizer, analyzer);
                            parser.Tokenizer.UseTokenList = true;
                        }
                        else
                        {
                            parser.Reset(this.input, analyzer);
                        }

                        parser.Parse();
                        return(analyzer.Mibs.ToList());
                    }
                    catch (ParserCreationException e)
                    {
                        log.AddInternalError(this.File, "parser creation error in ASN.1 parser: " + e.Message);
                        analyzer.Reset();
                        throw new MibLoaderException(log);
                    }
                    catch (ParserLogException e)
                    {
                        log.AddAll(this.File, e);
                        analyzer.Reset();
                        throw new MibLoaderException(log);
                    }
                }
            }
 public X509Cert(byte[] data)
 {
     using (var stm = new System.IO.MemoryStream(data))
     {
         Asn1Parser parser = new Asn1Parser();
         parser.LoadData(stm);
         ParseNode(parser.RootNode);
     }
 }
Example #15
0
        public void SetText(Asn1Node node, int lineLen)
        {
            this.node             = node;
            this.lineLen          = lineLen;
            textBoxLineWidth.Text = lineLen.ToString();
            string text = Asn1Parser.GetNodeText(node, lineLen);

            richTextBox.Text = text;
        }
        public void GetBsnkType_Succeeds()
        {
            var encryptedIdentity = File.ReadAllText("resources/signed/950053533-3-4-I.txt");
            var encodedData       = Convert.FromBase64String(encryptedIdentity);

            var bsnkType = Asn1Parser.GetBsnkType(encodedData);

            Assert.AreEqual(Constants.SignedEncryptedIdentityName, bsnkType);
        }
        public void GetSignature_Succeeds()
        {
            var encryptedPseudonym = File.ReadAllText("resources/signed/900095222-2-4-P.txt");
            var encodedData        = Convert.FromBase64String(encryptedPseudonym);

            var signature         = Asn1Parser.GetSignature(encodedData);
            var expectedSignature = new Signature(new BigInteger("107553452174033572320097286497696886003190384098237946520654141077292915400099016842332970896155"), new BigInteger("650320884538172458495892042411932561278118502434808303605427167594392943078504317702364621375984"));

            Assert.AreEqual(expectedSignature.ToString(), signature.ToString());
        }
Example #18
0
        public static void Build(KerberosAuthorizeMessage kerberosAuthorizeMessage, byte[] data)
        {
            Asn1Parser   asn1Parser   = new Asn1Parser();
            MemoryStream memoryStream = new MemoryStream(data);

            asn1Parser.LoadData((Stream)memoryStream);
            Asn1Node rootNode = asn1Parser.RootNode;

            KerberosAuthorizeMessageBuilder.BuildRoot(kerberosAuthorizeMessage, rootNode);
        }
Example #19
0
        public static void LogCurrentNodeValues(Asn1Data asn1Data, string nodeType)
        {
            byte[] headerBytes     = Asn1Parser.GetHeader(asn1Data);
            byte[] payloadBytes    = Asn1Parser.GetPayload(asn1Data);
            byte[] tagRawDataBytes = Asn1Parser.GetTagRawData(asn1Data);
            int    nestedNodeCount = Asn1Parser.GetNestedNodeCount(asn1Data);

            Storage.Put(Storage.CurrentContext, "NodeType", nodeType);
            Storage.Put(Storage.CurrentContext, "Header", headerBytes);
            Storage.Put(Storage.CurrentContext, "Payload", payloadBytes);
            Storage.Put(Storage.CurrentContext, "TagRawData", tagRawDataBytes);
            Storage.Put(Storage.CurrentContext, "NestedNodeCount", nestedNodeCount);
        }
        public void GetEncryptedEntity_Identity_Succeeds()
        {
            var encryptedIdentity = File.ReadAllText("resources/signed/950053533-3-4-I.txt");
            var encodedData       = Convert.FromBase64String(encryptedIdentity);

            var payload = Asn1Parser.GetSignedPayload(encodedData);

            var entity = Asn1Parser.GetEncryptedEntity <EncryptedIdentity>(payload, false);

            Assert.AreEqual(1, entity.SchemeVersion);
            Assert.AreEqual(11, entity.SchemeKeyVersion);
            Assert.AreEqual("00000000000000000004", entity.Recipient);
            Assert.AreEqual(44, entity.RecipientKeySetVersion);
        }
        public void GetEncryptedEntity_Pseudonym_Succeeds()
        {
            var encryptedPseudonym = File.ReadAllText("resources/signed/900095222-2-4-P.txt");
            var encodedData        = Convert.FromBase64String(encryptedPseudonym);

            var payload = Asn1Parser.GetSignedPayload(encodedData);

            var pseudonym = Asn1Parser.GetEncryptedEntity <EncryptedPseudonym>(payload, true);

            Assert.AreEqual(1, pseudonym.SchemeVersion);
            Assert.AreEqual(11, pseudonym.SchemeKeyVersion);
            Assert.AreEqual("00000000000000000004", pseudonym.Recipient);
            Assert.AreEqual(44, pseudonym.RecipientKeySetVersion);
        }
Example #22
0
        public void Can_read_a_private_key_from_a_PEM_file()
        {
            // Arrange
            var asn1Parser = new Asn1Parser();
            var sut        = new RSAPrivateKeyParser(asn1Parser);

            // Act
            var rsa = sut.ParsePem(new MemoryStream(Encoding.ASCII.GetBytes(TestPrivateKey)));

            // Assert
            rsa.Key.Exponent.Should().Equal(1, 0, 1);

            rsa.Key.Modulus.Length.Should().Be(256);
            rsa.Key.Modulus[0].Should().Be(0xb2);
            rsa.Key.Modulus[255].Should().Be(0xab);

            rsa.Key.P.Length.Should().Be(128);
        }
Example #23
0
 public void ResizeText()
 {
     try
     {
         this.lineLen = Convert.ToInt32(this.textBoxLineWidth.Text);
         if (lineLen < Asn1Node.minLineLen)
         {
             lineLen = Asn1Node.minLineLen;
             textBoxLineWidth.Text = lineLen.ToString();
         }
         string text = Asn1Parser.GetNodeText(node, lineLen);
         richTextBox.Text = text;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #24
0
        public void Should_install_a_x509_certificate_and_update_bindings()
        {
            // Arrange
            var x509       = new X509Certificate2(Encoding.ASCII.GetBytes(TestCertificate), (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            var sut        = new IISServerConfigurationProvider();
            var asn1Parser = new Asn1Parser();
            var rsaParser  = new PrivateKeyParser(asn1Parser);
            var privateKey = rsaParser.ParsePem(TestPrivateKey).Key;
            var csp        = new CspParameters {
                KeyContainerName = x509.GetCertHashString(), Flags = CspProviderFlags.UseMachineKeyStore
            };
            var rsa2 = new RSACryptoServiceProvider(csp);

            rsa2.ImportParameters(privateKey);
            x509.PrivateKey = rsa2;

            // Act
            sut.ConfigureServer("test.startliste.info", x509.GetCertHash(), "my", null, null);
        }
Example #25
0
        public void Should_parse_integer_to_bytes()
        {
            // Arrange
            var asn1Input = new[]
            {
                new byte[] { 2, 1, 0 },
                new byte[] { 2, 1, 127 },
                new byte[] { 2, 2, 0, 127 },
                new byte[] { 2, 2, 0, 128 },
                new byte[] { 2, 3, 1, 0, 0 },
                new byte[] { 2, 0 },
                new byte[] { 2, 7, 0, 165, 163, 214, 2, 169, 62 }
            }.Select(b => new MemoryStream(b));

            var expectedParsedValues = new[]
            {
                new byte[] { 0 },
                new byte[] { 127 },
                new byte[] { 0, 127 },
                new byte[] { 128 },
                new byte[] { 1, 0, 0 },
                new byte[0],
                new byte[] { 165, 163, 214, 2, 169, 62 }   //TODO as far as I undertand, it is correct that the parser removes the leading zero here. However, when parsing a PEM this must be taken into account and the parser must pad the parsed value with a leading zero
            };

            var sut = new Asn1Parser();

            // Act
            var result = asn1Input.SelectMany(sut.Parse).Cast <Integer>().Select(i => i.UnencodedValue).ToArray();

            // Assert
            result.Length.Should().Be(expectedParsedValues.Length);
            for (int i = 0; i < expectedParsedValues.Length; i++)
            {
                result[i].Should().Equal(expectedParsedValues[i]);
            }
        }
        internal AppleReceipt Parse(byte [] receiptData, out PKCS7 receipt)
        {
            // Avoid Culture-sensitive parsing for the duration of this method
            CultureInfo originalCulture = PushInvariantCultureOnThread();

            try
            {
                // Check to see if this receipt has been parsed before.
                // If so, return the most recent AppleReceipt and PKCS7; do not parse it again.
                if (_mostRecentReceiptData.ContainsKey(k_AppleReceiptKey) &&
                    _mostRecentReceiptData.ContainsKey(k_PKCS7Key) &&
                    _mostRecentReceiptData.ContainsKey(k_ReceiptBytesKey) &&
                    ArrayEquals <byte>(receiptData, (byte[])_mostRecentReceiptData[k_ReceiptBytesKey]))
                {
                    receipt = (PKCS7)_mostRecentReceiptData[k_PKCS7Key];
                    return((AppleReceipt)_mostRecentReceiptData[k_AppleReceiptKey]);
                }

                using (var stm = new System.IO.MemoryStream(receiptData)) {
                    Asn1Parser parser = new Asn1Parser();
                    parser.LoadData(stm);
                    receipt = new PKCS7(parser.RootNode);
                    var result = ParseReceipt(receipt.data);

                    // Cache the receipt info
                    _mostRecentReceiptData[k_AppleReceiptKey] = result;
                    _mostRecentReceiptData[k_PKCS7Key]        = receipt;
                    _mostRecentReceiptData[k_ReceiptBytesKey] = receiptData;
                    return(result);
                }
            }
            finally
            {
                PopCultureOffThread(originalCulture);
            }
        }
Example #27
0
 public RSAPrivateKeyParser(Asn1Parser parser)
 {
     this.parser = parser;
 }
Example #28
0
        public static byt[] Decode(byte[] rawData)
        {
            Asn1Data asn1Data = Asn1Parser.ParseFromRawData(rawData);

            return(Asn1Parser.GetPayload(asn1Data));
        }
Example #29
0
 public RSAPrivateKeyParser(Asn1Parser parser)
 {
     this.parser = parser ?? throw new ArgumentNullException(nameof(parser));
 }
Example #30
0
        /// <summary>
        /// Obtiene el UID de una tarjeta
        /// </summary>
        /// <param name="card">Tarjeta obtenida</param>
        /// <param name="bAtr">ATR de la tarjeta</param>
        /// <param name="config">Configuración de lectura de la tarjeta</param>
        /// <returns>Devuelve el tipo de retorno de la lectura</returns>
        public bool GetCard(out ICard card, byte[] bAtr, ICardReadConfig config)
        {
            card = null;

            if (bAtr == null)
            {
                bAtr = GetAtr(_hCard, _Name, API.SCARD_PCI_T0 | API.SCARD_PCI_T1);
                if (bAtr == null)
                {
                    return(false);
                }
            }
            if (IsDniE(bAtr))
            {
                // Leer el Contenido del DNIe

                //http://delphi.jmrds.com/node/78
                //https://social.msdn.microsoft.com/Forums/es-ES/044965fe-5a3c-4ec9-8d30-3880cc6d420a/traducir-cdigo-c-as-vbnet?forum=vcses
                //https://social.msdn.microsoft.com/Forums/es-ES/24a95872-8207-499c-b158-167991d00343/lector-de-tarjetas?forum=vbes

                using (MemoryStream ms = new MemoryStream())
                {
                    if (SCardReadFile(_hCard, new byte[] { 0x60, 0x04 }, ms))
                    {
                        Asn1Parser a = new Asn1Parser();
                        a.LoadData(ms);

                        Asn1Node pais = a.GetNodeByPath("/2/0/1/0/0/1");
                        Asn1Node niff = a.GetNodeByPath("/2/0/1/1/0/1");
                        Asn1Node fame = a.GetNodeByPath("/2/0/1/2/0/1");
                        Asn1Node xame = a.GetNodeByPath("/2/0/1/3/0/1");
                        Asn1Node name = a.GetNodeByPath("/2/0/1/4/0/1");

                        string snif   = Encoding.UTF8.GetString(niff.Data);
                        string spais  = Encoding.UTF8.GetString(pais.Data);
                        string ssname = Encoding.UTF8.GetString(xame.Data);
                        string fname  = Encoding.UTF8.GetString(fame.Data);
                        string sname  = Encoding.UTF8.GetString(name.Data).Replace("(AUTENTICACIÓN)", "").Trim();

                        card = new CardDnie(bAtr)
                        {
                            Id = snif, Country = spais, CompleteName = sname, Name = ssname, Surname1 = fname
                        };
                    }
                }

                // Leemos el IDESP con la ruta 0006
                // Leemos la version con la ruta 2F03
                // Leemos el CDF con la ruta 5015 6004
            }
            else
            {
                // Buscar tipo de tarjeta Mifare según el ATR

                CardMifare.EMifareType type = CardMifare.EMifareType.Unknown;
                if (bAtr.Length >= 18)
                {
                    if (bAtr[0] == 0x3B)
                    {
                        // http://downloads.acs.com.hk/drivers/en/API-ACR122U-2.02.pdf

                        // Mifare
                        if (bAtr[13] == 0)
                        {
                            switch (bAtr[14])
                            {
                            case 0x01: type = CardMifare.EMifareType.Classic1K; break;

                            case 0x02: type = CardMifare.EMifareType.Classic4K; break;

                            case 0x03: type = CardMifare.EMifareType.UltraLight; break;

                            case 0x26: type = CardMifare.EMifareType.Mini; break;
                            }
                        }
                    }
                }

                ConfigMifareRead cfg = null;
                if (config != null)
                {
                    if (!(config is ConfigMifareRead))
                    {
                        throw (new ArgumentException("Config must be ConfigMifareRead for Mifare Reads", "config"));
                    }

                    cfg = (ConfigMifareRead)config;
                }

                // Get UID command for Mifare cards
                byte[] receivedUID = SendCmd(_hCard, new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 });
                if (receivedUID == null)
                {
                    return(false);
                }

                card = new CardMifare(type, bAtr)
                {
                    Id = NFCHelper.Buffer2Hex(receivedUID, 0, receivedUID.Length - 2).ToUpperInvariant(),
                };

                if (cfg != null && cfg.RequireReadSomething)
                {
                    CardMifare xcard = (CardMifare)card;

                    // Creamos la tarjeta según su tipo
                    xcard.InitCard();

                    byte[] data;

                    // Establecemos las claves en el lector
                    if (cfg.KeysZero != null)
                    {
                        // Cargar la K0
                        data = SendCmd(_hCard, new byte[] { 0xFF, 0x82, 0x00, 0x00, 0x06, }.Concat(cfg.KeysZero).ToArray());
                        if (data == null || data.Length != 2)
                        {
                            return(false);
                        }
                    }

                    if (cfg.KeysOne != null)
                    {
                        // Cargar la K1
                        data = SendCmd(_hCard, new byte[] { 0xFF, 0x82, 0x00, 0x01, 0x06, }.Concat(cfg.KeysOne).ToArray());
                        if (data == null || data.Length != 2)
                        {
                            return(false);
                        }
                    }

                    // Leer los sectores que se precisan
                    //byte blockNum;
                    ConfigMifareReadSector[] readSectors = cfg.ReadSectors;

                    foreach (CardMifare.Sector sector in xcard.Sectors)
                    {
                        ConfigMifareReadSector readCfg = readSectors[sector.SectorNum];
                        if (readCfg == null || !readCfg.ReadSomething)
                        {
                            continue;
                        }

                        // General Authenticate - Peer sector

                        if (readCfg.Login != null)
                        {
                            // Login al primer sector
                            data = SendCmd(_hCard, new byte[] { 0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, sector.DataBlocks[0].BlockNum,
                                                                (byte)(readCfg.Login.KeyType == ConfigMifareRead.EKeyType.A ? 0x60 : 0x61),
                                                                (byte)(readCfg.Login.KeyNum == ConfigMifareRead.EKeyNum.Zero ? 0x00 : 0x01) });
                        }

                        List <CardMifare.Block> bRead = new List <CardMifare.Block>();

                        if (readCfg.ReadDataBlocks)
                        {
                            for (int x = (int)readCfg.ReadDataBlockStart, m = (int)readCfg.ReadDataBlockEnd; x <= m; x++)
                            {
                                bRead.Add(sector.DataBlocks[x]);
                            }
                        }
                        if (readCfg.ReadTrailBlock)
                        {
                            bRead.Add(sector.TrailingBlock);
                        }

                        //if (data != null && data.Length == 2)
                        foreach (CardMifare.Block block in bRead)
                        {
                            //blockNum = block.BlockNum;// byte.Parse(block.BlockNum.ToString().PadLeft(2, '0'), NumberStyles.HexNumber);

                            //if (cfg.Login != null)
                            //{
                            //    data = SendCmd(_hCard, new byte[] { 0xFF, 0x86, 0x00, 0x00, 0x05, 0x01, 0x00, block.BlockNum,
                            //       (byte)(cfg.Login.KeyType == ConfigMifareRead.EKeyType.A ? 0x60 : 0x61),
                            //       (byte)(cfg.Login.KeyNum == ConfigMifareRead.EKeyNum.Zero ? 0x00 : 0x01) });

                            //    if (data == null || data.Length != 2) continue;
                            //}

                            // Read Binary
                            data = SendCmd(_hCard, new byte[] { 0xFF, 0xB0, 0x00, block.BlockNum, 0x10 });
                            if (data != null && data.Length == 18)
                            {
                                block.CopyFrom(data);
                            }
                        }
                    }
                }
            }

            // Eliminar ids vacios
            if (card != null && card.Id.Trim('0') == "")
            {
                card = null;
            }

            return(card != null);
        }