示例#1
0
        public byte[] Transceive(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            var sioreq = new SCARD_IO_REQUEST
            {
                dwProtocol  = 0x2,
                cbPciLength = 8
            };
            var rioreq = new SCARD_IO_REQUEST
            {
                cbPciLength = 8,
                dwProtocol  = 0x2
            };

            var receiveBuffer = new byte[255];
            var rlen          = receiveBuffer.Length;

            Debug.WriteLine($"SmartCardConnection.Transceive: hCard = {hCard}, buffer = {buffer.ByteArrayToString()}");
            var retVal = SafeNativeMethods.SCardTransmit(hCard, ref sioreq, buffer, buffer.Length, ref rioreq, receiveBuffer, ref rlen);

            Helpers.CheckError(retVal);


            var retBuf = new byte[rlen];

            Array.Copy(receiveBuffer, retBuf, rlen);

            return(retBuf);
        }
示例#2
0
        internal int TransmitToCard(IntPtr hCard, byte[] sendBuffer, byte[] recvBuffer, Protocol protocol)
        {
            SCARD_IO_REQUEST ioRecv = new SCARD_IO_REQUEST();

            ioRecv.cbPciLength = 255;

            int pcbRecvLength = recvBuffer.Length;
            int cbSendLength  = sendBuffer.Length;

            IntPtr process = pciProcessT0;

            if (protocol == Protocol.T1)
            {
                process = pciProcessT1;
            }
            else if (protocol == Protocol.Raw)
            {
                process = pciProcessRaw;
            }

            ErrorCode ret;

            lock (pcscApiLock)
            {
                ret = (ErrorCode)SCardTransmit(hCard, process, sendBuffer, cbSendLength, ioRecv, recvBuffer, ref pcbRecvLength);
            }
            if (ret != ErrorCode.NoError)
            {
                throw new NFCException("Can not transmit to card:" + ret);
            }

            return(pcbRecvLength);
        }
示例#3
0
 public static extern int SCardTransmit(IntPtr hCard,
                                        ref SCARD_IO_REQUEST pioSendPci,
                                        ref byte[] pbSendBuffer,
                                        int cbSendLength,
                                        ref SCARD_IO_REQUEST pioRecvPci,
                                        ref byte[] pbRecvBuffer,
                                        ref int pcbRecvLength);
示例#4
0
文件: PcscRw.cs 项目: 12019/PcscRw
            public byte[] Transmit(byte[] cmd, int lenCmd)
            {
                byte[] tmpRsp    = new byte[1024];
                int    lenTmpRsp = tmpRsp.Length;

                SCARD_IO_REQUEST pci = null;

                if (this.activeProtocol == SCARD_PROTOCOL_T0)
                {
                    pci = pciT0;
                }
                else if (this.activeProtocol == SCARD_PROTOCOL_T1)
                {
                    pci = pciT1;
                }
                else
                {
                    throw new Exception("unsupported protocol");
                }

                uint res = SCardTransmit(hCard, pci, cmd, lenCmd, null, tmpRsp, ref lenTmpRsp);

                if (res != SUCCESS)
                {
                    throw new Exception("failed to transmit");
                }

                byte[] rsp = new byte[lenTmpRsp];
                Array.Copy(tmpRsp, rsp, lenTmpRsp);

                return(rsp);
            }
示例#5
0
文件: PcscRw.cs 项目: 12019/PcscRw
            public PcscRw()
            {
                //initializetion for member variables
                readerList = new System.Collections.ArrayList();

                this.pciT0 = GetPci(SCARD_PROTOCOL_T0);
                this.pciT1 = GetPci(SCARD_PROTOCOL_T1);


                //enumurate readers
                uint res = 0;

                res = SCardEstablishContext(SCARD_SCOPE_USER, IntPtr.Zero, IntPtr.Zero, out hContext);

                System.Text.StringBuilder readers = new StringBuilder(1024);

                byte[] reader = new byte[1024];

                int lenReaderName = reader.Length;

                res = SCardListReaders(hContext, SCARD_ALL_READERS, reader, ref lenReaderName);

                int lastIndex = 0;

                for (int i = 0; i < lenReaderName - 1; i++)
                {
                    if (reader[i] == 0)
                    {
                        int textCount = i - lastIndex;
                        readerList.Add(Encoding.ASCII.GetString(reader, lastIndex, textCount));
                        lastIndex = i + 1;
                    }
                }
            }
示例#6
0
文件: PcscRw.cs 项目: 12019/PcscRw
            private SCARD_IO_REQUEST GetPci(int T)
            {
                int handle = LoadLibrary("Winscard.dll");

                IntPtr pci = IntPtr.Zero;

                SCARD_IO_REQUEST ret = new SCARD_IO_REQUEST();

                switch (T)
                {
                case SCARD_PROTOCOL_T0:
                    pci = GetProcAddress(handle, "g_rgSCardT0Pci");
                    Marshal.PtrToStructure(pci, ret);
                    break;

                case SCARD_PROTOCOL_T1:
                    pci = GetProcAddress(handle, "g_rgSCardT1Pci");
                    Marshal.PtrToStructure(pci, ret);
                    break;

                default:
                    ret = null;
                    break;
                }

                FreeLibrary(handle);

                return(ret);
            }
示例#7
0
        /// <summary>
        /// Sends an APDU to the smartcard.
        /// </summary>
        /// <param name="apdu">The apdu to send to the smartcard.</param>
        /// <returns>An ApduReply instance, representing the reply from the smartcard.</returns>
        /// <exception cref="ObjectDisposedException">The SmartcardReader has been closed.</exception>
        /// <exception cref="ArgumentNullException"><i>apdu</i> is a null reference.</exception>
        /// <exception cref="SmartcardException">An error occurred while communication with the smartcard reader.</exception>
        public ApduReply SendCommand(ApduCommand apdu)
        {
            if (m_Disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (apdu == null)
            {
                throw new ArgumentNullException("apdu", ResourceController.GetString("Error_ParamNull"));
            }
            if (m_Card == IntPtr.Zero)
            {
                throw new SmartcardException(ResourceController.GetString("Error_SmartcardNotConnected"));
            }
            SCARD_IO_REQUEST sendPci = new SCARD_IO_REQUEST(m_ActiveProtocol, 8);

            byte[] buffer   = new byte[1024];
            int    recvSize = buffer.Length;
            // send the message to the smart card
            int ret = NativeMethods.SCardTransmit(m_Card, ref sendPci, apdu.InternalBytes, apdu.InternalLength, IntPtr.Zero, buffer, ref recvSize);

            if (ret != NativeMethods.SCARD_S_SUCCESS || recvSize < 2)
            {
                throw new SmartcardException(ResourceController.GetString("Error_SmartcardTransmit"), ret);
            }
            byte[] result = new byte[recvSize - 2];
            Array.Copy(buffer, 0, result, 0, result.Length);
            byte[] status = new byte[2];
            Array.Copy(buffer, recvSize - status.Length, status, 0, status.Length);
            return(new ApduReply(status, result));
        }
示例#8
0
 private static extern int SCardTransmit(IntPtr hCard,
                                         ref SCARD_IO_REQUEST pioSendPci,
                                         byte[] pbSendBuffer,
                                         int cbSendLength,
                                         IntPtr pioRecvPci,
                                         byte[] pbRecvBuffer,
                                         out IntPtr pcbRecvLength);
 static internal extern int SCardTransmit(
     IntPtr hCard,
     ref SCARD_IO_REQUEST pioSendRequest,
     ref byte SendBuff,
     uint SendBuffLen,
     ref SCARD_IO_REQUEST pioRecvRequest,
     byte[] RecvBuff,
     ref uint RecvBuffLen);
示例#10
0
 internal static extern uint SCardTransmit(
     IntPtr hCard,
     SCARD_IO_REQUEST pioSendPci,
     [In] byte[] pbSendBuffer,
     uint cbSendLength,
     SCARD_IO_REQUEST pioRecvPci,
     [In, Out] byte[] pbRecvBuffer,
     ref uint pcbRecvLength);
        public static void Main(string[] args)
        {
            IntPtr hContext;
            uint res = 0;

            res = SCardEstablishContext(SCARD_SCOPE_USER, IntPtr.Zero, IntPtr.Zero, out hContext);

            //Detect readers connected to the system
            byte[] bufReaderName = new byte[1024];
            int lenReaderName = bufReaderName.Length;
            res = SCardListReaders(hContext, SCARD_ALL_READERS, bufReaderName, ref lenReaderName);

            //Parse reader names
            List<string> readers = new List<string>();
            while (bufReaderName.Length > 0) {
                string s = System.Text.Encoding.ASCII.GetString (bufReaderName);
                if (s.Length == 0) { break; }
                readers.Add (s);
                bufReaderName = bufReaderName.Skip (s.Length + 1).ToArray();
            }
            Console.WriteLine ( readers.Count.ToString() + " reader(s) detected");
            foreach (var s in readers) { Console.WriteLine (" - "+s); }
            Console.WriteLine ("");

            //Connect to the card
            IntPtr hCard;
            uint activeProtocol;
            res = SCardConnect (hContext, readers [0], SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
                out hCard, out activeProtocol);

            //Command for selecting(activating) VISA card application
            byte[] sendBuffer = new byte[]{ 0x00, 0xa4, 0x04, 0x00, 0x05, 0xa0, 0x00,0x00,0x00,0x03,0x00 };

            //Command for selecting(activating) MasterCard card application
            //byte[] sendBuffer = new byte[]{ 0x00, 0xa4, 0x04, 0x00, 0x05, 0xa0, 0x00,0x00,0x00,0x04,0x00 };

            Console.Write("Card command:");
            dump (sendBuffer, sendBuffer.Length);
            Console.WriteLine ("");

            byte[] recvBuffer = new byte[1024];
            int lenRecv = recvBuffer.Length;

            SCARD_IO_REQUEST pci = new SCARD_IO_REQUEST (activeProtocol);
            res = SCardTransmit (hCard, pci, sendBuffer, sendBuffer.Length, pci, recvBuffer, ref lenRecv);

            Console.Write("Card response:");
            dump (recvBuffer, lenRecv);

            res = SCardDisconnect (hCard, SCARD_UNPOWER_CARD);

            res = SCardReleaseContext (hContext);
        }
示例#12
0
        /// <summary>
        /// Exchange data with smartcard
        /// </summary>
        /// <returns>
        /// Empty or error message
        /// </returns>
        public string SendReceive(string command, ref string response)
        {
            // check for selected reader
            if (selectedReader == "")
            {
                // no reader selected
                return(GlobalObj.LMan.GetString("noselreader"));
            }


            IntPtr retCommandLen = new IntPtr(261);

            // remove unused digits
            command = command.Trim().Replace("0x", "").Replace(" ", "");

            // Set input command byte array
            byte[] inCommandByte  = utilityObj.GetBytesFromHex(command);
            byte[] outCommandByte = new byte[261];

            // Prepare structures
            SCARD_IO_REQUEST pioSend = new SCARD_IO_REQUEST();
            SCARD_IO_REQUEST pioRecv = new SCARD_IO_REQUEST();

            pioSend.dwProtocol  = (uint)cardProtocol;
            pioSend.cbPciLength = (uint)8;
            pioRecv.dwProtocol  = (uint)cardProtocol;
            pioRecv.cbPciLength = 0;

            // exchange data with smartcard
            int ret = SCardTransmit(nCard,
                                    ref pioSend,
                                    inCommandByte,
                                    inCommandByte.Length,
                                    IntPtr.Zero,
                                    outCommandByte,
                                    out retCommandLen);

            if (ret != 0)
            {
                // Error detected
                log.Error("PcScReader.IReader::SendReceive: SCardTransmit " + parseError(ret));
                return("PcScReader.IReader::SendReceive: SCardTransmit " + parseError(ret));
            }

            // Extract response
            response = utilityObj.GetHexFromBytes(outCommandByte, 0, retCommandLen.ToInt32()).Trim();

            return("");
        }
示例#13
0
        int transmit(IntPtr hCard, byte[] sendBuffer, byte[] recvBuffer)
        {
            SCARD_IO_REQUEST ioRecv = new SCARD_IO_REQUEST();

            ioRecv.cbPciLength = 255;

            int    pcbRecvLength = recvBuffer.Length;
            int    cbSendLength  = sendBuffer.Length;
            IntPtr SCARD_PCI_T1  = getPciT1();
            uint   ret           = SCardTransmit(hCard, SCARD_PCI_T1, sendBuffer, cbSendLength, ioRecv, recvBuffer, ref pcbRecvLength);

            if (ret != SCARD_S_SUCCESS)
            {
                throw new ApplicationException("カードへの送信に失敗しました。code = " + ret);
            }
            return(pcbRecvLength); // 受信したバイト数(recvBufferに受け取ったバイト数)
        }
示例#14
0
        public static byte[] Transmit(int hCard, byte[] Command)
        {
            SCARD_IO_REQUEST ioRecvPci = new SCARD_IO_REQUEST();

            byte[] bTemp          = new byte[2048];
            uint   LenReturnBytes = 2048;

            ioRecvPci.cbPciLength = 2048;
            IntPtr SCARD_PCI_T1 = pcscWrapper.GetPciT1();

            if (SCardTransmit(hCard, SCARD_PCI_T1, Command, Command.Length, IntPtr.Zero, bTemp, ref LenReturnBytes) == SCARD_S_SUCCESS)
            {
                byte[] ReturnBytes = new byte[LenReturnBytes];
                for (int i = 0; i < LenReturnBytes; i++)
                {
                    ReturnBytes[i] = bTemp[i];
                }
                return(ReturnBytes);
            }
            else
            {
                return(null);
            }
        }
示例#15
0
        public bool readCardUID()
        {
            var receivedUID = new byte[256];
            var request     = new SCARD_IO_REQUEST();

            request.dwProtocol  = SCARD_PROTOCOL_T1;
            request.cbPciLength = Marshal.SizeOf(typeof(SCARD_IO_REQUEST));
            var sendBytes = new byte[] { 0xFF, 0xCA, 0x0, 0x0, 0x0 };
            int outBytes  = receivedUID.Length;
            int status    = SCardTransmit(hCard, ref request, ref sendBytes[0], sendBytes.Length, ref request, ref receivedUID[0], ref outBytes);

            if (status != SCARD_S_SUCCESS)
            {
                cardUID = "Error";
                return(false);
            }
            else
            {
                receivedUID = RemoveEmptyBytes16DigitsDecimal(receivedUID);
                cardUID     = BitConverter.ToString(receivedUID.ToArray()).Replace("-", string.Empty).ToLower();
            }

            return(true);
        }
示例#16
0
 static extern uint SCardTransmit(IntPtr hCard, IntPtr pioSendRequest, byte[] SendBuff, int SendBuffLen, SCARD_IO_REQUEST pioRecvRequest,
                                  byte[] RecvBuff, ref int RecvBuffLen);
示例#17
0
 public static extern int SCardTransmit(IntPtr hCard, ref SCARD_IO_REQUEST pioSendPci, ref byte pbSendBuffer, int cbSendLength, ref SCARD_IO_REQUEST pioRecvPci, ref byte pbRecvBuffer, ref int pcbRecvLength);
示例#18
0
        private bool SendCommand(IntPtr hContext, string readerName)
        {
            int  dwBufferSize;
            int  dwResponseSize;
            long lResult;

            byte[] response        = new byte[2048];
            byte[] commnadMF01     = { 0x00, 0xa4, 0x00, 0x00 };
            byte[] commnadVREF1    = { 0x00, 0x20, 0x00, 0x81 };
            byte[] commnadVREF2    = { 0x00, 0x20, 0x00, 0x82 };
            byte[] commnadVRPIN1   = { 0x00, 0x20, 0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] commnadVRPIN2   = { 0x00, 0x20, 0x00, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] commnadDF01     = { 0x00, 0xA4, 0x04, 0x0C, 0x10, 0xA0, 0x00, 0x00, 0x02, 0x31, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] commnadDF02     = { 0x00, 0xA4, 0x04, 0x0C, 0x10, 0xA0, 0x00, 0x00, 0x02, 0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] commnadEF01     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x01 };
            byte[] commnadEF02     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x02 };
            byte[] commnadEF03     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x03 };
            byte[] commnadEF04     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x04 };
            byte[] commnadEF05     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x05 };
            byte[] commnadEF06     = { 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x06 };
            byte[] commnadREAD01   = { 0x00, 0xB0, 0x00, 0x00, 0x00, 0x03, 0x70 };
            byte[] commnadREAD02   = { 0x00, 0xB0, 0x00, 0x00, 0x52 };
            byte[] commnadREADPICT = { 0x00, 0xB0, 0x00, 0x00, 0x00, 0x07, 0xD0 };


            IntPtr           SCARD_PCI_T1 = getPciT1();
            SCARD_IO_REQUEST ioRecv       = new SCARD_IO_REQUEST();

            ioRecv.cbPciLength = 2048;
            IntPtr hCard = connect(hContext, readerName);

            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadMF01, commnadMF01.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }

            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadVREF1, commnadVREF1.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }

            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadVREF2, commnadVREF2.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }

            commnadVRPIN1[4] = 4;
            commnadVRPIN1[5] = pass1byte[0];
            commnadVRPIN1[6] = pass1byte[1];
            commnadVRPIN1[7] = pass1byte[2];
            commnadVRPIN1[8] = pass1byte[3];
            dwResponseSize   = response.Length;
            lResult          = SCardTransmit(hCard, SCARD_PCI_T1, commnadVRPIN1, commnadVRPIN1.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            if (response[0] == (byte)0x63)
            {
                errormsg = "暗所番号1が違います";
                return(false);
            }
            commnadVRPIN2[4] = 4;
            commnadVRPIN2[5] = pass2byte[0];
            commnadVRPIN2[6] = pass2byte[1];
            commnadVRPIN2[7] = pass2byte[2];
            commnadVRPIN2[8] = pass2byte[3];
            dwResponseSize   = response.Length;
            lResult          = SCardTransmit(hCard, SCARD_PCI_T1, commnadVRPIN2, commnadVRPIN2.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            if (response[0] == (byte)0x63)
            {
                errormsg = "暗所番号2が違います";
                return(false);
            }


            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadDF01, commnadDF01.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadEF01, commnadEF01.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadREAD01, commnadREAD01.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            parse_tag(response);



            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadEF02, commnadEF02.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadREAD02, commnadREAD02.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            parse_tag(response);



            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadDF02, commnadDF02.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadEF01, commnadEF01.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            dwResponseSize = response.Length;
            lResult        = SCardTransmit(hCard, SCARD_PCI_T1, commnadREADPICT, commnadREADPICT.Length, ioRecv, response, ref dwResponseSize);
            if (lResult != SCARD_S_SUCCESS)
            {
                return(false);
            }
            parse_tag_picture(response);

            quit = true;
            return(response[dwResponseSize - 2] == 0x90 && response[dwResponseSize - 1] == 0x00);
        }
 public static extern int SCardTransmit(IntPtr hCard, ref SCARD_IO_REQUEST ioSendRequest, byte[] InBuff, int InBuffSize, ref SCARD_IO_REQUEST ioRecvRequest, byte[] OutBuff, out int OutBuffSize);
示例#20
0
        private static extern int SCardTransmit(IntPtr hCard, 
		                                    ref SCARD_IO_REQUEST pioSendPci,
		                                        byte[] pbSendBuffer, 
		                                        int cbSendLength, 
		                                        IntPtr pioRecvPci,
	                                            byte[] pbRecvBuffer, 
	                                        out IntPtr pcbRecvLength);
        public static void Main(string[] args)
        {
            IntPtr hContext;
            uint   res = 0;


            res = SCardEstablishContext(SCARD_SCOPE_USER, IntPtr.Zero, IntPtr.Zero, out hContext);

            //Detect readers connected to the system
            byte[] bufReaderName = new byte[1024];
            int    lenReaderName = bufReaderName.Length;

            res = SCardListReaders(hContext, SCARD_ALL_READERS, bufReaderName, ref lenReaderName);

            //Parse reader names
            List <string> readers = new List <string>();

            while (bufReaderName.Length > 0)
            {
                string s = System.Text.Encoding.ASCII.GetString(bufReaderName);
                if (s.Length == 0)
                {
                    break;
                }
                readers.Add(s);
                bufReaderName = bufReaderName.Skip(s.Length + 1).ToArray();
            }
            Console.WriteLine(readers.Count.ToString() + " reader(s) detected");
            foreach (var s in readers)
            {
                Console.WriteLine(" - " + s);
            }
            Console.WriteLine("");

            //Connect to the card
            IntPtr hCard;
            uint   activeProtocol;

            res = SCardConnect(hContext, readers [0], SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
                               out hCard, out activeProtocol);

            //Command for selecting(activating) VISA card application
            byte[] sendBuffer = new byte[] { 0x00, 0xa4, 0x04, 0x00, 0x05, 0xa0, 0x00, 0x00, 0x00, 0x03, 0x00 };

            //Command for selecting(activating) MasterCard card application
            //byte[] sendBuffer = new byte[]{ 0x00, 0xa4, 0x04, 0x00, 0x05, 0xa0, 0x00,0x00,0x00,0x04,0x00 };


            Console.Write("Card command:");
            dump(sendBuffer, sendBuffer.Length);
            Console.WriteLine("");

            byte[] recvBuffer = new byte[1024];
            int    lenRecv    = recvBuffer.Length;

            SCARD_IO_REQUEST pci = new SCARD_IO_REQUEST(activeProtocol);

            res = SCardTransmit(hCard, pci, sendBuffer, sendBuffer.Length, pci, recvBuffer, ref lenRecv);

            Console.Write("Card response:");
            dump(recvBuffer, lenRecv);

            res = SCardDisconnect(hCard, SCARD_UNPOWER_CARD);

            res = SCardReleaseContext(hContext);
        }
示例#22
0
        private void btn_ReadCard_Click(object sender, EventArgs e)
        {
            int    phContext      = 0;
            int    phCard         = 0;
            int    ActiveProtocol = 0;
            string empty          = string.Empty;

            byte[] array = new byte[21]
            {
                0,
                164,
                4,
                0,
                16,
                209,
                88,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                17,
                0
            };
            byte[] array2 = new byte[7]
            {
                0,
                202,
                17,
                0,
                2,
                0,
                0
            };
            byte[] array3        = new byte[2];
            int    pcbRecvLength = 2;

            byte[] array4         = new byte[59];
            int    pcbRecvLength2 = 59;
            uint   num            = 0u;

            num = SCardEstablishContext(0u, 0, 0, ref phContext);
            if (num != 0)
            {
                MessageBox.Show(ErrCode.errMsg(num), "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            int num2 = 0;

            byte[]        array5      = new byte[num2];
            List <string> list        = new List <string>();
            int           pcchReaders = 0;

            num = SCardListReaders(phContext, null, null, ref pcchReaders);
            if (num == 0)
            {
                byte[] array6 = new byte[pcchReaders];
                num = SCardListReaders(phContext, null, array6, ref pcchReaders);
                if (num == 0)
                {
                    ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
                    string        text          = aSCIIEncoding.GetString(array6);
                    int           num3          = 0;
                    char          c             = '\0';
                    int           num4          = pcchReaders;
                    while (text[0] != c)
                    {
                        num3 = text.IndexOf(c);
                        string text2 = text.Substring(0, num3);
                        list.Add(text2);
                        num4 -= text2.Length + 1;
                        text  = text.Substring(num3 + 1, num4);
                    }
                }
            }
            if (num != 0)
            {
                MessageBox.Show("請確認卡片類別,並重新插卡", "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else if (list.Count == 0)
            {
                MessageBox.Show("請接上讀卡機裝置", "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                uint num5 = 0u;
                foreach (string item in list)
                {
                    num = SCardConnect(phContext, item, 1u, 2u, ref phCard, ref ActiveProtocol);
                    if (num != 0)
                    {
                        num5 = num;
                    }
                    else
                    {
                        SCARD_IO_REQUEST pioSendPci = default(SCARD_IO_REQUEST);
                        SCARD_IO_REQUEST pioRecvPci = default(SCARD_IO_REQUEST);
                        pioSendPci.dwProtocol  = (pioRecvPci.dwProtocol = ActiveProtocol);
                        pioSendPci.cbPciLength = (pioRecvPci.cbPciLength = 8);
                        num = SCardTransmit(phCard, ref pioSendPci, array, array.Length, ref pioRecvPci, ref array3[0], ref pcbRecvLength);
                        if (num == 0)
                        {
                            num = SCardTransmit(phCard, ref pioSendPci, array2, array2.Length, ref pioRecvPci, ref array4[0], ref pcbRecvLength2);
                            if (num != 0)
                            {
                                MessageBox.Show(ErrCode.errMsg(num), "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            }
                            else
                            {
                                try
                                {
                                    if (dt.Select("Modified = 1").Length != 0)
                                    {
                                        if (MessageBox.Show("本個案接種資料未完成儲存,是否放棄儲存繼續讀取下一位個案?", "紀錄尚未儲存", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No)
                                        {
                                            return;
                                        }
                                        InitDataTable();
                                    }
                                    string text3  = Encoding.Default.GetString(array4, 0, 12).Replace("\0", "");
                                    double result = 0.0;
                                    double.TryParse(text3, out result);
                                    if (text3.Length != 12 || result == 0.0)
                                    {
                                        throw new Exception();
                                    }
                                    tb_CaseName.Text     = Encoding.Default.GetString(array4, 12, 20).Replace("\0", "");
                                    tb_RocID.Text        = Encoding.Default.GetString(array4, 32, 10);
                                    tb_Birthday.Text     = Convert.ToInt32(Encoding.Default.GetString(array4, 42, 3)) + 1911 + "/" + Encoding.Default.GetString(array4, 45, 2) + "/" + Encoding.Default.GetString(array4, 47, 2);
                                    tb_Birthday2.Text    = tb_Birthday.Text;
                                    cb_Sex.SelectedIndex = ((!tb_RocID.Text.Substring(1, 1).Equals("1")) ? 1 : 0);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("請確認卡片類別,並重新插卡", "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                    string str = "C:\\NIISOL\\";
                                    Utility.WriteToFile(str + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "_log.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\t請確認卡片類別,並重新插卡,讀卡失敗" + ex.Message, 'A', "");
                                }
                            }
                            SCardDisconnect(phCard, 0);
                            break;
                        }
                        MessageBox.Show(ErrCode.errMsg(num), "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
                if (num5 != 0)
                {
                    MessageBox.Show(ErrCode.errMsg(num), "讀卡失敗", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            SCardReleaseContext(phContext);
        }
示例#23
0
        /// <summary>
        /// Exchange data with smartcard
        /// </summary>
        /// <returns>
        /// Empty or error message
        /// </returns>
        public string SendReceive(string command, ref string response)
        {
            // check for selected reader
            if (selectedReader == "")
            {
                // no reader selected
                return GlobalObj.LMan.GetString("noselreader");
            }

            IntPtr retCommandLen = new IntPtr(261);

            // remove unused digits
            command = command.Trim().Replace("0x", "").Replace(" ", "");

            // Set input command byte array
            byte[] inCommandByte = utilityObj.GetBytesFromHex(command);
            byte[] outCommandByte = new byte[261];

            // Prepare structures
            SCARD_IO_REQUEST pioSend = new SCARD_IO_REQUEST();
            SCARD_IO_REQUEST pioRecv = new SCARD_IO_REQUEST();
            pioSend.dwProtocol = (uint)cardProtocol;
            pioSend.cbPciLength = (uint)8;
            pioRecv.dwProtocol = (uint)cardProtocol;
            pioRecv.cbPciLength = 0;

            // exchange data with smartcard
            int ret = SCardTransmit(nCard,
                                ref pioSend,
                                    inCommandByte,
                                    inCommandByte.Length,
                                    IntPtr.Zero,
                                    outCommandByte,
                                out retCommandLen);

            if (ret != 0)
            {
                // Error detected
                log.Error("PcScReader.IReader::SendReceive: SCardTransmit " + parseError(ret));
                return "PcScReader.IReader::SendReceive: SCardTransmit " + parseError(ret);
            }

            // Extract response
            response = utilityObj.GetHexFromBytes(outCommandByte, 0, retCommandLen.ToInt32()).Trim();

            return "";
        }
        static extern uint SCardTransmit(IntPtr hCard, SCARD_IO_REQUEST pioSendPci, byte[] pbSendBuffer, int cbSendLength, SCARD_IO_REQUEST pioRecvPci,
			byte[] pbRecvBuffer, ref int pcbRecvLength);
示例#25
0
 private static extern uint SCardTransmit(int hCard, ref SCARD_IO_REQUEST pioSendPci, byte[] pbSendBuffer, int cbSendLength, ref SCARD_IO_REQUEST pioRecvPci, ref byte pbRecvBuffer, ref int pcbRecvLength);
示例#26
0
    public ResultObj Execute(Dictionary <string, string> args)
    {
        ResultObj resobj = new ResultObj();

        resobj.IsSuccess  = false;
        resobj.CertStatus = CertStatus.未驗證;
        Dictionary <string, string> dictionary = new Dictionary <string, string>();
        int    phContext      = 0;
        int    phCard         = 0;
        int    ActiveProtocol = 0;
        string empty          = string.Empty;

        byte[] array = new byte[21]
        {
            0,
            164,
            4,
            0,
            16,
            209,
            88,
            0,
            0,
            1,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            17,
            0
        };
        byte[] array2 = new byte[7]
        {
            0,
            202,
            17,
            0,
            2,
            0,
            0
        };
        byte[] array3        = new byte[2];
        int    pcbRecvLength = 2;

        byte[] array4         = new byte[59];
        int    pcbRecvLength2 = 59;
        uint   num            = 0u;

        num = SCardEstablishContext(0u, 0, 0, ref phContext);
        if (num != 0)
        {
            resobj.ErrorMsg = ErrCode.errMsg(num);
        }
        else
        {
            int           num2        = 0;
            byte[]        array5      = new byte[num2];
            List <string> list        = new List <string>();
            int           pcchReaders = 0;
            num = SCardListReaders(phContext, null, null, ref pcchReaders);
            if (num == 0)
            {
                byte[] array6 = new byte[pcchReaders];
                num = SCardListReaders(phContext, null, array6, ref pcchReaders);
                if (num == 0)
                {
                    ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
                    string        text          = aSCIIEncoding.GetString(array6);
                    int           num3          = 0;
                    char          c             = '\0';
                    int           num4          = pcchReaders;
                    while (text[0] != c)
                    {
                        num3 = text.IndexOf(c);
                        string text2 = text.Substring(0, num3);
                        list.Add(text2);
                        num4 -= text2.Length + 1;
                        text  = text.Substring(num3 + 1, num4);
                    }
                }
            }
            if (num != 0)
            {
                SetErrorMsg(ref resobj, num);
            }
            else if (list.Count == 0)
            {
                SetErrorMsg(ref resobj, 2148532270u);
            }
            else
            {
                uint num5 = 0u;
                foreach (string item in list)
                {
                    num = SCardConnect(phContext, item, 1u, 2u, ref phCard, ref ActiveProtocol);
                    if (num != 0)
                    {
                        num5 = num;
                    }
                    else
                    {
                        SCARD_IO_REQUEST pioSendPci = default(SCARD_IO_REQUEST);
                        SCARD_IO_REQUEST pioRecvPci = default(SCARD_IO_REQUEST);
                        pioSendPci.dwProtocol  = (pioRecvPci.dwProtocol = ActiveProtocol);
                        pioSendPci.cbPciLength = (pioRecvPci.cbPciLength = 8);
                        num = SCardTransmit(phCard, ref pioSendPci, array, array.Length, ref pioRecvPci, ref array3[0], ref pcbRecvLength);
                        if (num == 0)
                        {
                            num = SCardTransmit(phCard, ref pioSendPci, array2, array2.Length, ref pioRecvPci, ref array4[0], ref pcbRecvLength2);
                            if (num != 0)
                            {
                                SetErrorMsg(ref resobj, num);
                            }
                            else
                            {
                                try
                                {
                                    string text3  = Encoding.Default.GetString(array4, 0, 12).Replace("\0", "");
                                    double result = 0.0;
                                    double.TryParse(text3, out result);
                                    if (text3.Length != 12 || result == 0.0)
                                    {
                                        throw new Exception();
                                    }
                                    dictionary.Add("健保卡ID", text3);
                                    dictionary.Add("姓名", Encoding.Default.GetString(array4, 12, 20).Replace("\0", ""));
                                    dictionary.Add("身分證字號", Encoding.Default.GetString(array4, 32, 10));
                                    dictionary.Add("生日", Encoding.Default.GetString(array4, 43, 2) + "/" + Encoding.Default.GetString(array4, 45, 2) + "/" + Encoding.Default.GetString(array4, 47, 2));
                                    dictionary.Add("姓別", Encoding.Default.GetString(array4, 49, 1));
                                    dictionary.Add("發卡日期", Encoding.Default.GetString(array4, 51, 2) + "/" + Encoding.Default.GetString(array4, 53, 2) + "/" + Encoding.Default.GetString(array4, 55, 2));
                                    resobj.IsSuccess = true;
                                    resobj.CardInfo  = dictionary;
                                }
                                catch
                                {
                                    resobj.IsSuccess = false;
                                    SetErrorMsg(ref resobj, 2148532326u);
                                }
                            }
                            SCardDisconnect(phCard, 0);
                            break;
                        }
                        SetErrorMsg(ref resobj, num);
                    }
                }
                if (!resobj.IsSuccess && num5 != 0)
                {
                    SetErrorMsg(ref resobj, num5);
                }
            }
            SCardReleaseContext(phContext);
        }
        if (!resobj.IsSuccess && resobj.ErrorMsg.Equals(""))
        {
            resobj.ErrorType = ErrorType.非預期錯誤;
            resobj.ErrorMsg  = "非預期錯誤,無法讀取健保卡";
        }
        return(resobj);
    }
示例#27
0
 public static extern int SCardTransmit(int hCard, ref SCARD_IO_REQUEST pioSendRequest, ref byte SendBuff, int SendBuffLen, ref SCARD_IO_REQUEST pioRecvRequest, ref byte RecvBuff, ref int RecvBuffLen);
示例#28
0
 public static extern int SCardTransmit(int hCard, ref SCARD_IO_REQUEST pioSendRequest, ref byte SendBuff, int SendBuffLen, ref SCARD_IO_REQUEST pioRecvRequest, ref byte RecvBuff, ref int RecvBuffLen);
示例#29
0
        public long GetUID(ref byte[] UID)
        {
            long _result      = 0;
            bool cardInserted = false;


            IntPtr _CardContext   = IntPtr.Zero;
            IntPtr ActiveProtocol = IntPtr.Zero;

            // Establish Reader context:
            if (this._ReaderContext == IntPtr.Zero)
            {
                _result = SCardEstablishContext(2, IntPtr.Zero, IntPtr.Zero, out this._ReaderContext);

                #region Get List of Available Readers

                uint pcchReaders = 0;
                int  nullindex   = -1;
                char nullchar    = (char)0;

                // First call with 3rd parameter set to null gets readers buffer length.
                _result = SCardListReaders(this._ReaderContext, null, null, ref pcchReaders);

                byte[] mszReaders = new byte[pcchReaders];

                // Fill readers buffer with second call.
                _result = SCardListReaders(this._ReaderContext, null, mszReaders, ref pcchReaders);

                // Populate List with readers.
                string currbuff = new ASCIIEncoding().GetString(mszReaders);
                int    len      = (int)pcchReaders;

                if (len > 0)
                {
                    while (currbuff[0] != nullchar)
                    {
                        nullindex = currbuff.IndexOf(nullchar);                           // Get null end character.
                        string reader = currbuff.Substring(0, nullindex);
                        this._AvailableReaders.Add(reader);
                        len      = len - (reader.Length + 1);
                        currbuff = currbuff.Substring(nullindex + 1, len);
                    }
                }

                #endregion

                // Select the first reader:
                this._ReaderName = this._AvailableReaders[0];
            }

            try
            {
                //Check if there is a Card in the reader:

                //dwShareMode: SCARD_SHARE_SHARED = 0x00000002 - This application will allow others to share the reader
                //dwPreferredProtocols: SCARD_PROTOCOL_T0 - Use the T=0 protocol (value = 0x00000001)

                if (this._ReaderContext != IntPtr.Zero)
                {
                    _result = SCardConnect(this._ReaderContext, this._ReaderName, 0x00000002, 0x00000001, ref _CardContext, ref ActiveProtocol);
                    if (_result == 0)
                    {
                        cardInserted = true;

                        SCARD_IO_REQUEST request = new SCARD_IO_REQUEST()
                        {
                            dwProtocol  = (uint)ActiveProtocol,
                            cbPciLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(SCARD_IO_REQUEST))
                        };

                        byte[] sendBytes = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 };                         //<- get UID command for iClass cards
                        byte[] ret_Bytes = new byte[33];
                        uint   sendLen   = (uint)sendBytes.Length;
                        uint   ret_Len   = (uint)ret_Bytes.Length;

                        _result = SCardTransmit(_CardContext, ref request, ref sendBytes[0], sendLen, ref request, ret_Bytes, ref ret_Len);
                        if (_result == 0)
                        {
                            UID = ret_Bytes.Take(4).ToArray();                             //only take the first 8, the last 2 bytes are not part of the UID of the card
                            string dataOut = byteToHexa(UID, UID.Length, true).Trim();     //Devolver la respuesta en Hexadecimal
                        }
                    }
                }
            }
            finally
            {
                SCardDisconnect(_CardContext, 0);
                SCardReleaseContext(this._ReaderContext);
            }
            return(_result);
        }