Esempio n. 1
1
        private static void Main() {
            // Establish Smartcard context
            using (var context = new SCardContext()) {
                context.Establish(SCardScope.System);

                var readerNames = context.GetReaders();
                if (readerNames == null || readerNames.Length < 1) {
                    Console.WriteLine("You need at least one reader in order to run this example.");
                    Console.ReadKey();
                    return;
                }

                var readerName = ChooseReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var isoReader = new IsoReader(context, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) {
                    
                    // Build a GET CHALLENGE command 
                    var apdu = new CommandApdu(IsoCase.Case2Short, isoReader.ActiveProtocol) {
                        CLA = 0x00, // Class
                        Instruction = InstructionCode.GetChallenge,
                        P1 = 0x00,  // Parameter 1
                        P2 = 0x00,  // Parameter 2
                        Le = 0x08   // Expected length of the returned data
                    };

                    Console.WriteLine("Send APDU with \"GET CHALLENGE\" command: {0}", BitConverter.ToString(apdu.ToArray()));
                    var response = isoReader.Transmit(apdu);

                    Console.WriteLine("SW1 SW2 = {0:X2} {1:X2}", response.SW1, response.SW2);

                    if (!response.HasData) {
                        Console.WriteLine("No data. (Card does not understand \"GET CHALLENGE\")");
                    } else {
                        var data = response.GetData();
                        Console.WriteLine("Challenge: {0}", BitConverter.ToString(data));
                    }
                }
            }
            Console.ReadKey();
        }
Esempio n. 2
0
        static void Main() {
            // Establish Smartcard context
            using (var context = new SCardContext()) {
                context.Establish(SCardScope.System);

                var readerNames = context.GetReaders();
                if (readerNames == null || readerNames.Length < 1) {
                    Console.WriteLine("You need at least one reader in order to run this example.");
                    Console.ReadKey();
                    return;
                }

                var readerName = ChooseReader(readerNames);
                if (readerName == null) {
                    return;
                }

                using (var isoReader = new IsoReader(context, readerName, SCardShareMode.Shared, SCardProtocol.Any, false)) {
                    var card = new MifareCard(isoReader);

                    var loadKeySuccessful = card.LoadKey(
                        KeyStructure.NonVolatileMemory, 
                        0x00, // first key slot
                        new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } // key
                    );

                    if (!loadKeySuccessful) {
                        throw new Exception("LOAD KEY failed.");
                    }

                    var authSuccessful = card.Authenticate(MSB, LSB, KeyType.KeyA, 0x00);
                    if (!authSuccessful) {
                        throw new Exception("AUTHENTICATE failed.");
                    }

                    var result = card.ReadBinary(MSB, LSB, 16);
                    Console.WriteLine("Result (before BINARY UPDATE): {0}", 
                        (result != null) 
                        ? BitConverter.ToString(result) 
                        : null);

                    var updateSuccessful = card.UpdateBinary(MSB, LSB, DATA_TO_WRITE);

                    if (!updateSuccessful) {
                        throw new Exception("UPDATE BINARY failed.");
                    }

                    result = card.ReadBinary(MSB, LSB, 16);
                    Console.WriteLine("Result (after BINARY UPDATE): {0}", 
                        (result != null) 
                        ? BitConverter.ToString(result) 
                        : null);
                }
            }
            Console.ReadKey();
        }
Esempio n. 3
0
 public IsoReader TryConnect(String cardName)
 {
   try
   {
     IsoReader card = new IsoReader(this.reader);
     card.Connect(cardName, SCardShareMode.Shared, SCardProtocol.Any);
     return card;
   }
   catch (PCSCException)
   {
     return null;
   }
 }
    public ABC4TrustSmartCard(String cardName)
    {
      this.cardName = cardName;
      sIO = new SmartCardIO();
      card = sIO.TryConnect(cardName);
      pStatus = ProofStatus.NOTSET;
      this.doProfile = ParseConfigManager.DoTimeProfile();
      if (doProfile)
      {
        pInfo = ParseConfigManager.profileInfo;
      }

    }
Esempio n. 5
0
        public byte[] GetCardId(IsoReader reader)
        {
            var command = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any)
            {
                CLA = 0xFF,
                Instruction = InstructionCode.GetData,
                P1 = 0x00,
                P2 = 0x00,
                Le = 0x00
            };

            var response = reader.Transmit(command);

            return response.GetData();
        }
Esempio n. 6
0
        private void WriteAllCardBytes(IsoReader isoReader, byte[] bytes, int packetSize)
        {
            var bytesToWrite = new List<byte>(bytes);

            //while (bytesToWrite.Count < 38 * 4)
            //    bytesToWrite.Add(0x00);

            while (bytesToWrite.Count % packetSize != 0)
                bytesToWrite.Add(0x00);

            for (int i = 0; i < bytesToWrite.Count / packetSize; i++)
            {
                var updateBinaryCmd = new CommandApdu(IsoCase.Case3Short, SCardProtocol.Any)
                {
                    CLA = 0xFF,
                    Instruction = InstructionCode.UpdateBinary,
                    P1 = 0x00,
                    P2 = (byte)((16 / packetSize) + i),
                    Data = bytesToWrite.Skip(i * packetSize).Take(packetSize).ToArray()
                };

                var response = isoReader.Transmit(updateBinaryCmd);

                Console.WriteLine("UpdateBinary: {0},{1}", response.SW1, response.SW2);
            }
        }
Esempio n. 7
0
        private ReaderStatus GetReaderStatus(IsoReader reader)
        {
            var readerName = new string[0];
            var cardState = SCardState.Unknown;
            var protocol = SCardProtocol.Unset;
            var atr = new byte[0];

            var error = reader.Reader.Status(out readerName, out cardState, out protocol, out atr);

            return new ReaderStatus { ReaderName = readerName, CardState = cardState, Protocol = protocol, Atr = atr };
        }
Esempio n. 8
0
        public string Write()
        {
            Log.Debug("Card write");

            try
            {
                using (var reader = new IsoReader(CardContext, GetReader(), SCardShareMode.Shared, SCardProtocol.Any, false))
                {
                    var status = GetReaderStatus(reader);

                    Log.Debug(String.Format("Card State: {0}", status.CardState));

                    if (!status.CardState.HasFlag(SCardState.Present))
                        return null;

                    var id = GetCardId(reader);
                    var cardName = GetCardName(status.Atr);
                    var cardType = GetInt16(cardName);

                    var isMifare = cardType == CardReader.Mifare1KCard || cardType == CardReader.Mifare4KCard;
                    var isMifareUltralight = cardType == CardReader.MifareUltralightCard;

                    Log.Debug(String.Format("Card Id: {0}", BitConverter.ToString(id)));

                    var cardString = BitConverter.ToString(cardName.Concat(id).ToArray()).Replace("-", "");

                    if (isMifareUltralight)
                    {
                        var msg = new NdefMessage { new NdefUriRecord { Uri = CardReader.CardUri + "/#/" + cardString } };
                        var data = msg.ToByteArray();
                        var buffer = new List<byte>(new byte[] { 0x03, (byte)data.Length }.Concat(data));

                        WriteAllCardBytes(reader, buffer.ToArray(), isMifareUltralight ? 4 : 16);
                    }

                    return BitConverter.ToString(cardName.Concat(id).ToArray()).Replace("-", "");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

            return null;
        }
Esempio n. 9
0
        private byte[] GetAllCardBytes(IsoReader reader, int packetSize)
        {
            try
            {
                var firstDataBlock = 16 / packetSize;
                var readSize = 16;
                var bytesToRead = 0;
                var buffer = new List<byte>();

                while (true)
                {
                    var blockToRead = (byte)(firstDataBlock + (buffer.Count / packetSize));

                    var readBinaryCmd = new CommandApdu(IsoCase.Case2Short, SCardProtocol.Any)
                    {
                        CLA = 0xFF,
                        Instruction = InstructionCode.ReadBinary,
                        P1 = 0x00,
                        P2 = blockToRead,
                        Le = readSize
                    };

                    var response = reader.Transmit(readBinaryCmd);

                    var data = response.GetData();

                    if (buffer.Count == 0)
                        bytesToRead = data[1] + 1 + 1;

                    buffer.AddRange(data.Take(bytesToRead - buffer.Count < readSize ? bytesToRead - buffer.Count : readSize).ToArray());
                    if (buffer.Count >= bytesToRead)
                        break;
                }

                Log.Debug(String.Format("ReadBinary: {0}", BitConverter.ToString(buffer.ToArray())));
                Log.Debug(String.Format("Buffersize: Reported: {0}, Actual: {1}", bytesToRead, buffer.Count));

                return buffer.ToArray();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

            return new byte[0];
        }
Esempio n. 10
0
        private void CardInserted(object sender, CardStatusEventArgs e)
        {
            Log.Debug("Card inserted");

            try
            {
                using (var reader = new IsoReader(CardContext, GetReader(), SCardShareMode.Shared, SCardProtocol.Any, false))
                {
                    var id = GetCardId(reader);
                    var status = GetReaderStatus(reader);

                    var cardName = GetCardName(status.Atr);
                    var cardType = GetInt16(cardName);

                    var isMifare = cardType == Mifare1KCard || cardType == Mifare4KCard;
                    var isMifareUltralight = cardType == MifareUltralightCard;

                    //var bytes = GetAllCardBytes(reader, isMifareUltralight ? 4 : 16);
                    var isShopCard = true; // IsShopCard(bytes);

                    Log.Debug(String.Format("Card Id: {0}, Shop Card: {1}", BitConverter.ToString(id), isShopCard));

                    if (isShopCard)
                    {
                        var cardString = BitConverter.ToString(cardName.Concat(id).ToArray()).Replace("-", "");

                        EventAggregator.Publish(new CardInserted { CardId = cardString });
                    }
                    else
                    {
                        EventAggregator.Publish(new InvalidCardInserted { });
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                EventAggregator.Publish(new InvalidCardInserted { });
            }
        }
        private void CreateContextAndReader()
        {
            context = new SCardContext();
            context.Establish(scope);
            context.EnsureOK();

            reader = new IsoReader(context);
        }
        public void Dispose()
        {
            if (reader != null)
            {
                if (IsCardOpened)
                {
                    try
                    {
                        CloseCard();
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex);
                    }
                }

                try
                {
                    reader.Dispose();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                finally { reader = null; }
            }

            if (context != null)
            {
                try
                {
                    context.Dispose();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                finally { context = null; }
            }
        }