/// <inheritdoc />
        public SCardError Status(out string[] readerName, out SCardState state, out SCardProtocol protocol,
                                 out byte[] atr)
        {
            var rc = Platform.Lib.Status(
                _cardHandle,
                out readerName,
                out var dwState,
                out var dwProtocol,
                out atr);

            if (rc == SCardError.Success)
            {
                protocol = SCardHelper.ToProto(dwProtocol);
                state    = SCardHelper.ToState(dwState);

                // update local copies
                ActiveProtocol = protocol;
                if (readerName.Length >= 1)
                {
                    ReaderName = readerName[0];
                }
            }
            else
            {
                protocol = SCardProtocol.Unset;
                state    = SCardState.Unknown;
            }

            return(rc);
        }
Example #2
0
        public SCardError Reconnect(SCardShareMode mode,
                                    SCardProtocol prefProto,
                                    SCardReaderDisposition initExec)
        {
            if (cardHandle.Equals(IntPtr.Zero))
            {
                throw new InvalidOperationException(
                          "Reader is currently not connected or no card handle has been returned.");
            }

            SCardProtocol dwActiveProtocol = activeprot;

            SCardError rc = SCardAPI.Lib.Reconnect(cardHandle,
                                                   mode,
                                                   prefProto,
                                                   initExec,
                                                   out dwActiveProtocol);


            if (rc == SCardError.Success)
            {
                activeprot = dwActiveProtocol;
                sharemode  = mode;
            }

            return(rc);
        }
Example #3
0
        /// <inheritdoc />
        public void Connect(string readerName, SCardShareMode mode, SCardProtocol preferredProtocol)
        {
            ThrowIfDisposed();
            ThrowIfAlreadyConnected();

            if (readerName == null)
            {
                throw new ArgumentNullException(nameof(readerName));
            }

            if (string.IsNullOrWhiteSpace(readerName))
            {
                throw new UnknownReaderException(SCardError.InvalidValue, "Invalid card reader name.");
            }

            if (_context.Handle.Equals(IntPtr.Zero))
            {
                throw new InvalidContextException(SCardError.InvalidHandle, "Invalid connection context.");
            }

            _api.Connect(
                hContext: _context.Handle,
                szReader: readerName,
                dwShareMode: mode,
                dwPreferredProtocols: preferredProtocol,
                phCard: out var cardHandle,
                pdwActiveProtocol: out var activeProtocol)
            .ThrowIfNotSuccess();

            Handle     = cardHandle;
            Protocol   = activeProtocol;
            Mode       = mode;
            ReaderName = readerName;
        }
Example #4
0
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol proto, bool copy)
        {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response.Length < length))
            {
                throw new ArgumentOutOfRangeException("length");
            }

            if (copy)
            {
                if (response != null)
                {
                    this.response = new byte[length];
                    Array.Copy(response, this.response, length);
                }
            }
            else
            {
                this.response = response;
            }
            this.length  = length;
            this.isocase = isoCase;
            this.proto   = proto;
        }
Example #5
0
        public SCardError Connect(
            IntPtr hContext,
            string szReader,
            SCardShareMode dwShareMode,
            SCardProtocol dwPreferredProtocols,
            out IntPtr phCard,
            out SCardProtocol pdwActiveProtocol)
        {
            byte[] readername = SCardHelper._ConvertToByteArray(szReader, textEncoding, SCardAPI.Lib.CharSize);
            Int32  sharemode  = (Int32)dwShareMode;
            Int32  prefproto  = (Int32)dwPreferredProtocols;
            IntPtr ctx        = (IntPtr)hContext;
            IntPtr card;
            Int32  activeproto;

            Int32 result = SCardConnect(ctx,
                                        readername,
                                        sharemode,
                                        prefproto,
                                        out card,
                                        out activeproto);

            phCard            = card;
            pdwActiveProtocol = (SCardProtocol)activeproto;

            return(SCardHelper.ToSCardError(result));
        }
Example #6
0
        public byte[] GetAtr() => _atr?.ToArray(); // return copy or NULL

        /// <summary>
        /// Creates a new instance
        /// </summary>
        /// <param name="readerNames">The reader's friendly names</param>
        /// <param name="state">A bit mask that represents the reader status</param>
        /// <param name="protocol">The reader's currently used protocol.</param>
        /// <param name="atr">The card's ATR if available</param>
        public ReaderStatus(string[] readerNames, SCardState state, SCardProtocol protocol, byte[] atr = null)
        {
            State        = state;
            Protocol     = protocol;
            _readerNames = readerNames;
            _atr         = atr;
        }
Example #7
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="length">The size of the response.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <param name="copy">If <see langword="true" /> the bytes of the supplied response will be copied.</param>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="length" /> is greater than the <paramref name="response" /> size.</exception>
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol protocol, bool copy)
        {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response != null && response.Length < length))
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            if (copy)
            {
                if (response != null)
                {
                    FullApdu = new byte[length];
                    Array.Copy(response, FullApdu, length);
                }
            }
            else
            {
                FullApdu = response;
            }

            Length   = length;
            Case     = isoCase;
            Protocol = protocol;
        }
Example #8
0
        /// <summary>
        /// Transmits the specified data to the card using the specified protocol.
        /// </summary>
        /// <param name="cardHandle">An IntPtr that is the card handle to use.</param>
        /// <param name="data">An array of byte containing the data to send.</param>
        /// <param name="protocol">A SCardProtocol that indicates the protocol to use.</param>
        /// <returns>An array of byte containing the response data.</returns>
        public static byte[] TransmitDataToCard(IntPtr cardHandle, byte[] data, SCardProtocol protocol = SCardProtocol.T0)
        {
            byte[] returnValue;

            if (cardHandle != null && cardHandle != IntPtr.Zero)
            {
                SCardResponse result;
                bool          wasSuccessful;

                try
                {
                    wasSuccessful = NativeMethods.TransmitToCard(cardHandle, protocol, data, out returnValue, out result);
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to disconnect from the card due to an exception", ex);
                }

                if (!wasSuccessful)
                {
                    throw new InvalidOperationException($"Unable to disconnect from the card. Error code {result}");
                }
            }
            else
            {
                throw new ArgumentException("The specified card handle is invalid", nameof(cardHandle));
            }

            return(returnValue);
        }
Example #9
0
        public static IntPtr GetGlobalPci(SCardProtocol protocol)
        {
            string globalPath = @"";

            switch (protocol)
            {
            case SCardProtocol.T0:
                globalPath = "g_rgSCardT0Pci";
                break;

            case SCardProtocol.T1:
                globalPath = "g_rgSCardT1Pci";
                break;

            case SCardProtocol.Raw:
                globalPath = "g_rgSCardRawPci";
                break;

            default:
                throw PCSCException.ThrowByResult(PCSCResult.ProtocolMismatch);
            }

            IntPtr handle = NativeMethods.LoadLibrary("Winscard.dll");
            IntPtr pci    = NativeMethods.GetProcAddress(handle, globalPath);

            NativeMethods.FreeLibrary(handle);
            return(pci);
        }
Example #10
0
        internal static bool TransmitToCard(IntPtr cardHandle, SCardProtocol protocol, byte[] data, out byte[] response, out SCardResponse result)
        {
            bool returnValue = false;

            // Defaults
            response = null;
            result   = SCardResponse.SCARD_E_INVALID_HANDLE;

            if (cardHandle != IntPtr.Zero)
            {
                SCARD_IO_REQUEST receiveProtocol;
                uint             resultCode;
                SCARD_IO_REQUEST sendProtocol;

                // Setup
                sendProtocol    = GetNewIoRequest(protocol);
                receiveProtocol = GetNewIoRequest(protocol);

                resultCode = SCardTransmit(cardHandle, ref sendProtocol, data, (uint)data.Length, ref receiveProtocol, null, out uint receivedSize);
                result     = (SCardResponse)resultCode;
                if (result == SCardResponse.SCARD_S_SUCCESS)
                {
                    response   = new byte[receivedSize];
                    resultCode = SCardTransmit(cardHandle, ref sendProtocol, data, (uint)data.Length, ref receiveProtocol, response, out receivedSize);
                    result     = (SCardResponse)resultCode;
                    if (result == SCardResponse.SCARD_S_SUCCESS)
                    {
                        returnValue = true;
                    }
                }
            }

            return(returnValue);
        }
Example #11
0
        /// <summary>Creates a new SCardPCI object.</summary>
        /// <param name="protocol">
        ///     <list type="table">
        ///         <listheader><term>Protocol Control Information</term><description>Description</description></listheader>
        ///         <item><term><see cref="P:PCSC.SCardPCI.T0" /></term><description>Pre-defined T=0 PCI structure. (SCARD_PCI_T0)</description></item>
        ///         <item><term><see cref="P:PCSC.SCardPCI.T1" /></term><description>Pre-defined T=1 PCI structure. (SCARD_PCI_T1)</description></item>
        ///         <item><term><see cref="P:PCSC.SCardPCI.Raw" /></term><description>Pre-defined RAW PCI structure. (SCARD_PCI_RAW)</description></item>
        ///     </list>
        /// </param>
        /// <param name="pciData">User data.</param>
        public SCardPCI(SCardProtocol protocol, byte[] pciData)
            : this(protocol, pciData.Length)
        {
            if (pciData == null)
            {
                throw new ArgumentNullException(nameof(pciData));
            }

            if (pciData.Length <= 0 || MemoryPtr == IntPtr.Zero)
            {
                return;
            }

            if (Platform.IsWindows)
            {
                // Windows
                Marshal.Copy(pciData, 0,
                             BufferStartAddr,
                             pciData.Length);

                return;
            }

            // Unix
            Marshal.Copy(pciData, 0,
                         BufferStartAddr,
                         pciData.Length);
        }
Example #12
0
        /// <summary>Creates a new SCardPCI object.</summary>
        /// <param name="protocol">
        ///     <list type="table"><listheader><term>Protocol Control Information</term><description>Description</description></listheader>
        ///         <item><term><see cref="P:PCSC.SCardPCI.T0" /></term><description>Pre-defined T=0 PCI structure. (SCARD_PCI_T0)</description></item>
        ///         <item><term><see cref="P:PCSC.SCardPCI.T1" /></term><description>Pre-defined T=1 PCI structure. (SCARD_PCI_T1)</description></item>
        ///         <item><term><see cref="P:PCSC.SCardPCI.Raw" /></term><description>Pre-defined RAW PCI structure. (SCARD_PCI_RAW)</description></item>
        ///     </list>
        /// </param>
        /// <param name="bufLength">Size of this structure in bytes.</param>
        public SCardPCI(SCardProtocol protocol, int bufLength)
            : this() {
            if (bufLength < 0) {
                throw new ArgumentOutOfRangeException(
                    "bufLength");
            }

            if (Platform.IsWindows) {
                // Windows
                _iomem = unchecked((IntPtr) ((long) Marshal.AllocCoTaskMem(bufLength
                    + Marshal.SizeOf(typeof(SCARD_IO_REQUEST_WINDOWS)))));

                _winscardIoRequest.dwProtocol = (Int32) protocol;
                _winscardIoRequest.cbPciLength = bufLength;
                if (_iomem != IntPtr.Zero) {
                    Marshal.StructureToPtr(_winscardIoRequest, _iomem, false);
                }
                return;
            }

            // Unix
            _iomem = unchecked((IntPtr) ((long) Marshal.AllocCoTaskMem(bufLength
                + Marshal.SizeOf(typeof(Interop.Unix.SCARD_IO_REQUEST)))));

            _pcscliteIoRequest.dwProtocol = (IntPtr) protocol;
            _pcscliteIoRequest.cbPciLength = (IntPtr) bufLength;
            if (_iomem != IntPtr.Zero) {
                Marshal.StructureToPtr(
                    _pcscliteIoRequest,
                    _iomem,
                    false);
            }
        }
Example #13
0
        public SCardError Status(out string[] ReaderName,
                                 out SCardState State,
                                 out SCardProtocol Protocol,
                                 out byte[] Atr)
        {
            SCardError rc;
            IntPtr     dwState    = IntPtr.Zero;
            IntPtr     dwProtocol = IntPtr.Zero;

            rc = SCardAPI.Lib.Status(cardHandle,
                                     out ReaderName,
                                     out dwState,
                                     out dwProtocol,
                                     out Atr);

            if (rc == SCardError.Success)
            {
                Protocol = SCardHelper.ToProto(dwProtocol);
                State    = SCardHelper.ToState(dwState);

                // update local copies
                activeprot = Protocol;
                if (ReaderName.Length >= 1)
                {
                    readername = ReaderName[0];
                }
            }
            else
            {
                Protocol = SCardProtocol.Unset;
                State    = SCardState.Unknown;
            }

            return(rc);
        }
Example #14
0
        /// <summary>Creates a new SCardPCI object.</summary>
        /// <param name="protocol">
        ///     <list type="table"><listheader><term>Protocol Control Information</term><description>Description</description></listheader>
        ///         <item><term><see cref="SCardPCI.T0" /></term><description>Pre-defined T=0 PCI structure. (SCARD_PCI_T0)</description></item>
        ///         <item><term><see cref="SCardPCI.T1" /></term><description>Pre-defined T=1 PCI structure. (SCARD_PCI_T1)</description></item>
        ///         <item><term><see cref="SCardPCI.Raw" /></term><description>Pre-defined RAW PCI structure. (SCARD_PCI_RAW)</description></item>
        ///     </list>
        /// </param>
        /// <param name="bufLength">Size of this structure in bytes.</param>
        public SCardPCI(SCardProtocol protocol, int bufLength)
            : this()
        {
            if (bufLength < 0)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(bufLength));
            }

            switch (Platform.Type)
            {
            case PlatformType.Windows:
                MemoryPtr = unchecked ((IntPtr)((long)Marshal
                                                .AllocCoTaskMem(bufLength + Marshal.SizeOf(typeof(SCARD_IO_REQUEST_WINDOWS)))
                                                ));
                _winscardIoRequest.dwProtocol  = (int)protocol;
                _winscardIoRequest.cbPciLength = bufLength;
                if (MemoryPtr != IntPtr.Zero)
                {
                    Marshal.StructureToPtr(_winscardIoRequest, MemoryPtr, false);
                }

                break;

            case PlatformType.Linux:
                MemoryPtr = unchecked ((IntPtr)((long)Marshal
                                                .AllocCoTaskMem(bufLength + Marshal.SizeOf(typeof(SCARD_IO_REQUEST_UNIX)))));
                _linuxIoRequest.dwProtocol  = (IntPtr)protocol;
                _linuxIoRequest.cbPciLength = (IntPtr)bufLength;
                if (MemoryPtr != IntPtr.Zero)
                {
                    Marshal.StructureToPtr(
                        _linuxIoRequest,
                        MemoryPtr,
                        false);
                }

                break;

            case PlatformType.MacOSX:
                MemoryPtr = unchecked ((IntPtr)((long)Marshal
                                                .AllocCoTaskMem(bufLength + Marshal.SizeOf(typeof(SCARD_IO_REQUEST_MACOSX))))
                                       );
                _macosIoRequest.dwProtocol  = (int)protocol;
                _macosIoRequest.cbPciLength = bufLength;
                if (MemoryPtr != IntPtr.Zero)
                {
                    Marshal.StructureToPtr(
                        _macosIoRequest,
                        MemoryPtr,
                        false);
                }

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #15
0
        public IsoCard(ISCardReader reader, string readerName, SCardShareMode mode, SCardProtocol proto)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            this.reader = reader;
            Connect(readerName, mode, proto);
        }
Example #16
0
 private static SCARD_IO_REQUEST GetNewIoRequest(SCardProtocol protocol)
 {
     return(new SCARD_IO_REQUEST
     {
         dwProtocol = protocol,
         cbPciLength = (uint)Marshal.SizeOf(typeof(SCARD_IO_REQUEST))
     });
 }
Example #17
0
        /// <inheritdoc />
        public ICardHandle Connect(string readerName, SCardShareMode mode, SCardProtocol preferredProtocol)
        {
            ThrowOnInvalidContext();

            var handle = new CardHandle(_api, this);

            handle.Connect(readerName, mode, preferredProtocol);
            return(handle);
        }
Example #18
0
 public SCardWrapper(
     SCardScopes scope,
     SCardShareModes shareMode,
     SCardProtocol protocol)
 {
     _scope     = (uint)scope;
     _shareMode = (uint)shareMode;
     _protocol  = (uint)protocol;
 }
Example #19
0
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol proto)
        {
            this.response = response;
            if (response != null)
                length = response.Length;

            this.isocase = isoCase;
            this.proto = proto;
        }
Example #20
0
        public IsoCard(ISCardReader reader, string readerName, SCardShareMode mode, SCardProtocol proto)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.reader = reader;
            Connect(readerName, mode, proto);
        }
Example #21
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol protocol) {
            _response = response;

            if (response != null) {
                _length = response.Length;
            }

            Case = isoCase;
            Protocol = protocol;
        }
Example #22
0
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol proto)
        {
            this.response = response;
            if (response != null)
            {
                length = response.Length;
            }

            this.isocase = isoCase;
            this.proto   = proto;
        }
Example #23
0
        public SCardError Reconnect(IntPtr hCard, SCardShareMode dwShareMode, SCardProtocol dwPreferredProtocols, SCardReaderDisposition dwInitialization, out SCardProtocol pdwActiveProtocol)
        {
            var result = SCardReconnect(
                hCard,
                (int)dwShareMode,
                (int)dwPreferredProtocols,
                (int)dwInitialization,
                out var activeproto);

            pdwActiveProtocol = (SCardProtocol)activeproto;
            return(SCardHelper.ToSCardError(result));
        }
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol proto)
        {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response.Length < length))
                throw new ArgumentOutOfRangeException("length");

            this.response = response;
            this.length = length;
            this.isocase = isoCase;
            this.proto = proto;
        }
Example #25
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="length">The size of the response.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="length" /> is greater than the <paramref name="response" /> size.</exception>
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol protocol) {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response != null && response.Length < length)) {
                throw new ArgumentOutOfRangeException("length");
            }

            _response = response;
            _length = length;
            Case = isoCase;
            Protocol = protocol;
        }
Example #26
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol protocol)
        {
            FullApdu = response;

            if (response != null)
            {
                Length = response.Length;
            }

            Case     = isoCase;
            Protocol = protocol;
        }
Example #27
0
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol proto)
        {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response.Length < length))
            {
                throw new ArgumentOutOfRangeException("length");
            }

            this.response = response;
            this.length   = length;
            this.isocase  = isoCase;
            this.proto    = proto;
        }
Example #28
0
        public IntPtr Connect(string readerName, SCardShareMode shareMode, SCardProtocol protocol)
        {
            IntPtr        CardHandle;
            SCardProtocol ActiveProtocol;
            SCardError    Error = SCardApi.SCardConnect(this.Context, readerName, shareMode, protocol, out CardHandle, out ActiveProtocol);

            if (SCardApi.IsError(Error))
            {
                throw new SCardException(Error);
            }

            SCardApi.sessionProtocols.Add(CardHandle, protocol);
            return(CardHandle);
        }
Example #29
0
        public virtual void Connect(string readerName, SCardShareMode mode, SCardProtocol proto)
        {
            if (readerName == null)             // Invalid reader name?
                throw new ArgumentNullException("readerName");  
            if (proto == SCardProtocol.Unset)   // Invalid protocol?
                throw new InvalidProtocolException(SCardError.InvalidValue);
            if (((long)mode) == 0)              // Invalid sharing mode?
                throw new InvalidShareModeException(SCardError.InvalidValue);
            
            SCardError sc = reader.Connect(readerName, mode, proto);

            // Throws an exception if sc != SCardError.Success
            ThrowExceptionOnSCardError(sc);
        }
Example #30
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="length">The size of the response.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="length" /> is greater than the <paramref name="response" /> size.</exception>
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol protocol)
        {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response != null && response.Length < length))
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            FullApdu = response;
            Length   = length;
            Case     = isoCase;
            Protocol = protocol;
        }
Example #31
0
        /// <inheritdoc />
        public void Disconnect(SCardReaderDisposition disconnectExecution)
        {
            ThrowIfDisposed();
            ThrowOnInvalidCardHandle();

            _api.Disconnect(
                hCard: Handle,
                dwDisposition: disconnectExecution)
            .ThrowIfNotSuccess();

            Handle     = IntPtr.Zero;
            ReaderName = null;
            Protocol   = SCardProtocol.Unset;
            Mode       = SCardShareMode.Shared;
        }
Example #32
0
        public SCardError Connect(IntPtr hContext, string szReader, SCardShareMode dwShareMode,
                                  SCardProtocol dwPreferredProtocols, out IntPtr phCard, out SCardProtocol pdwActiveProtocol)
        {
            var readername = SCardHelper.ConvertToByteArray(szReader, TextEncoding, Platform.Lib.CharSize);

            var result = UnixNativeMethods.SCardConnect(hContext,
                                                        readername,
                                                        (IntPtr)dwShareMode,
                                                        (IntPtr)dwPreferredProtocols,
                                                        out phCard,
                                                        out var activeproto);

            pdwActiveProtocol = (SCardProtocol)activeproto;

            return(SCardHelper.ToSCardError(result));
        }
Example #33
0
        /// <summary>Receives a PCI pointer to a given protocol.</summary>
        /// <param name="protocol">The desired protocol.</param>
        /// <returns>A pointer to the PCI structure in the native system library.</returns>
        public static IntPtr GetPci(SCardProtocol protocol)
        {
            switch (protocol)
            {
            case SCardProtocol.T0:
                return(T0);

            case SCardProtocol.T1:
                return(T1);

            case SCardProtocol.Raw:
                return(Raw);

            default:
                throw new InvalidProtocolException(SCardError.InvalidValue, "Protocol not supported.");
            }
        }
Example #34
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <param name="copy">If <see langword="true" /> the bytes of the supplied response will be copied.</param>
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol protocol, bool copy) {
            Case = isoCase;
            Protocol = protocol;

            if (response == null) {
                return;
            }

            if (copy) {
                _length = response.Length;
                _response = new byte[_length];
                Array.Copy(response, _response, _length);
            } else {
                _response = response;
                _length = response.Length;
            }
        }
Example #35
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <param name="copy">If <see langword="true" /> the bytes of the supplied response will be copied.</param>
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol protocol, bool copy) {
            Case = isoCase;
            Protocol = protocol;

            if (response == null) {
                return;
            }

            if (copy) {
                Length = response.Length;
                FullApdu = new byte[Length];
                Array.Copy(response, FullApdu, Length);
            } else {
                FullApdu = response;
                Length = response.Length;
            }
        }
Example #36
0
 public ReadRecordAPDU(byte recordNumber, SCardProtocol protocol) : base(IsoCase.Case4Short, protocol)
 {
     CLA  = 0xC8;
     INS  = 0x00;
     P1   = 0x00;
     P2   = 0x00;
     Data = new byte[] {
         recordNumber,
         31,                          // DataFormat
         10,                          // DigitCount
         0,                           // Reserved
         1,                           // DeviceId
         0,                           // DeviceVersion
         C, C, C, C, h, h, h, h, h, h // FormatString
     };
     Le = 0x00;
 }
Example #37
0
        /// <inheritdoc />
        public void Reconnect(SCardShareMode mode, SCardProtocol preferredProtocol,
                              SCardReaderDisposition initialExecution)
        {
            ThrowIfDisposed();
            ThrowOnInvalidCardHandle();

            _api.Reconnect(
                hCard: Handle,
                dwShareMode: mode,
                dwPreferredProtocols: preferredProtocol,
                dwInitialization: initialExecution,
                pdwActiveProtocol: out var dwActiveProtocol)
            .ThrowIfNotSuccess();

            Protocol = dwActiveProtocol;
            Mode     = mode;
        }
        private void SetIntPtr(SCardProtocol protocol)
        {
            switch (protocol)
            {
            case SCardProtocol.T0:
                _pioSendPci = SCardPCI.T0;
                break;

            case SCardProtocol.T1:
                _pioSendPci = SCardPCI.T1;
                break;

            default:
                _pioSendPci = new IntPtr();
                break;
            }
        }
Example #39
0
        private ResponseApdu SimpleTransmit(byte[] commandApdu, int commandApduLength, IsoCase isoCase,
                                            SCardProtocol protocol, SCardPCI receivePci, ref byte[] receiveBuffer, ref int receiveBufferLength)
        {
            SCardError sc;
            var        cmdSent = false;

            do
            {
                // send Command APDU to the card
                sc = _reader.Transmit(
                    SCardPCI.GetPci(_reader.ActiveProtocol),
                    commandApdu,
                    commandApduLength,
                    receivePci,
                    receiveBuffer,
                    ref receiveBufferLength);

                // Do we need to resend the command APDU?
                if (sc == SCardError.InsufficientBuffer &&
                    receiveBuffer.Length < receiveBufferLength)
                {
                    // The response buffer was too small.
                    receiveBuffer = new byte[receiveBufferLength];

                    // Shall we wait until we re-send we APDU?
                    if (RetransmitWaitTime > 0)
                    {
                        Thread.Sleep(RetransmitWaitTime);
                    }
                }
                else
                {
                    cmdSent = true;
                }
            } while (cmdSent == false);

            if (sc == SCardError.Success)
            {
                return(new ResponseApdu(receiveBuffer, receiveBufferLength, isoCase, protocol));
            }

            // An error occurred, throw exception..
            ThrowExceptionOnSCardError(sc);
            return(null);
        }
Example #40
0
        /// <summary>Initializes a new instance of the <see cref="ResponseApdu" /> class.</summary>
        /// <param name="response">The response as byte array that shall be parsed.</param>
        /// <param name="length">The size of the response.</param>
        /// <param name="isoCase">The ISO case that was used when sending the <see cref="CommandApdu" />.</param>
        /// <param name="protocol">The communication protocol.</param>
        /// <param name="copy">If <see langword="true" /> the bytes of the supplied response will be copied.</param>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="length" /> is greater than the <paramref name="response" /> size.</exception>
        public ResponseApdu(byte[] response, int length, IsoCase isoCase, SCardProtocol protocol, bool copy) {
            if (length < 0 ||
                (response == null && length > 0) ||
                (response != null && response.Length < length)) {
                throw new ArgumentOutOfRangeException("length");
            }

            if (copy) {
                if (response != null) {
                    _response = new byte[length];
                    Array.Copy(response, _response, length);
                }
            } else {
                _response = response;
            }
            _length = length;
            Case = isoCase;
            Protocol = protocol;
        }
Example #41
0
        public ResponseApdu(byte[] response, IsoCase isoCase, SCardProtocol proto, bool copy)
        {
            this.isocase = isoCase;
            this.proto = proto;

            if (response == null)
                return;
            if (copy)
            {
                length = response.Length;
                this.response = new byte[length];
                Array.Copy(response, this.response, length);
            }
            else
            {
                this.response = response;
                length = response.Length;
            }
        }
Example #42
0
        public SCardPCI(SCardProtocol protocol, int buflength)
            : this()
        {
            if (buflength < 0)
                throw new System.ArgumentOutOfRangeException(
                    "buflength");

            if (SCardAPI.IsWindows)
            {
                iomem = unchecked((IntPtr)((long)Marshal.AllocCoTaskMem(buflength
                    + Marshal.SizeOf(typeof(WinSCardAPI.SCARD_IO_REQUEST)))));

                winscard_iorequest.dwProtocol = (Int32)protocol;
                winscard_iorequest.cbPciLength = (Int32)buflength;
                if (iomem != IntPtr.Zero)
                {
                    Marshal.StructureToPtr(
                        winscard_iorequest,
                        iomem,
                        false);
                }
            }
            else
            {
                iomem = unchecked((IntPtr)((long)Marshal.AllocCoTaskMem(buflength
                    + Marshal.SizeOf(typeof(PCSCliteAPI.SCARD_IO_REQUEST)))));

                pcsclite_iorequest.dwProtocol = (IntPtr)protocol;
                pcsclite_iorequest.cbPciLength = (IntPtr)buflength;
                if (iomem != IntPtr.Zero)
                {
                    Marshal.StructureToPtr(
                        pcsclite_iorequest,
                        iomem, 
                        false);
                }
            }
        }
Example #43
0
 public static IntPtr GetPci(SCardProtocol proto)
 {
     switch (proto) {
         case SCardProtocol.T0:
             return T0;
         case SCardProtocol.T1:
             return T1;
         case SCardProtocol.Raw:
             return Raw;
         default:
             throw new InvalidProtocolException(SCardError.InvalidValue, "Protocol not supported.");
     }
 }
Example #44
0
        public SCardPCI(SCardProtocol protocol, byte[] pcidata)
            : this(protocol, pcidata.Length)
        {
            if (pcidata == null)
                throw new ArgumentNullException("pcidata");

            if (pcidata.Length > 0 && iomem != IntPtr.Zero)
            {
                if (SCardAPI.IsWindows)
                {
                    Marshal.Copy(pcidata, 0,
                        BufferStartAddr, 
                        pcidata.Length);
                }
                else
                {
                    Marshal.Copy(pcidata, 0,
                        BufferStartAddr, 
                        pcidata.Length);
                }
            }
        }
Example #45
0
        /// <summary>Terminates a connection made through <see cref="M:PCSC.ISCardReader.Connect(System.String,PCSC.SCardShareMode,PCSC.SCardProtocol)" />.</summary>
        /// <param name="disconnectExecution">Reader function to execute.</param>
        /// <returns>
        ///     <list type="table">
        ///         <listheader>
        ///             <term>Return value</term>
        ///             <description>Description</description>
        ///         </listheader>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.Success" />
        ///             </term>
        ///             <description>Successful (SCARD_S_SUCCESS)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidHandle" />
        ///             </term>
        ///             <description>Invalid card handle (SCARD_E_INVALID_HANDLE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidValue" />
        ///             </term>
        ///             <description>Invalid <paramref name="disconnectExecution" /> (SCARD_E_INVALID_VALUE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoService" />
        ///             </term>
        ///             <description>The server is not runing (SCARD_E_NO_SERVICE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoSmartcard" />
        ///             </term>
        ///             <description>No smart card present (SCARD_E_NO_SMARTCARD)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.CommunicationError" />
        ///             </term>
        ///             <description>An internal communications error has been detected (SCARD_F_COMM_ERROR)</description>
        ///         </item>
        ///     </list>
        /// </returns>
        /// <remarks>
        ///     <para>This method calls the API function SCardDisconnect().</para>
        ///     <example>
        ///         <code lang="C#">
        /// // Establish PC/SC context.
        /// SCardContext ctx = new SCardContext();
        /// ctx.Establish(SCardScope.System);
        /// 
        /// // Create a Smart Card reader object and connect to it.
        /// ISCardReader reader = new SCardReader(ctx);
        /// SCardError serr = reader.Connect("OMNIKEY", SCardShareMode.Shared, SCardProtocol.Any);
        /// 
        /// // Disconnect the reader and reset the SmartCard.
        /// reader.Disconnect(SCardReaderDisposition.Reset);
        ///   </code>
        ///     </example>
        /// </remarks>
        public SCardError Disconnect(SCardReaderDisposition disconnectExecution)
        {
            ThrowOnInvalidCardHandle();

            var rc = Platform.Lib.Disconnect(_cardHandle, disconnectExecution);

            if (rc != SCardError.Success) {
                return rc;
            }

            // reset local variables
            _readername = null;
            _cardHandle = IntPtr.Zero;
            _activeprot = SCardProtocol.Unset;
            _sharemode = SCardShareMode.Shared;

            return rc;
        }
Example #46
0
        public SCardError Connect(IntPtr hContext, string szReader, SCardShareMode dwShareMode, SCardProtocol dwPreferredProtocols, out IntPtr phCard, out SCardProtocol pdwActiveProtocol) {
            var readername = SCardHelper.ConvertToByteArray(szReader, _textEncoding, Platform.Lib.CharSize);
            IntPtr activeproto;

            var result = SCardConnect(hContext,
                readername,
                (IntPtr) dwShareMode,
                (IntPtr) dwPreferredProtocols,
                out phCard,
                out activeproto);

            pdwActiveProtocol = (SCardProtocol) activeproto;

            return SCardHelper.ToSCardError(result);
        }
Example #47
0
        public SCardError Reconnect(SCardShareMode mode,
                                   SCardProtocol prefProto,
                                   SCardReaderDisposition initExec)
        {
            if (cardHandle.Equals(IntPtr.Zero))
                throw new InvalidOperationException(
                    "Reader is currently not connected or no card handle has been returned.");

            SCardProtocol dwActiveProtocol = activeprot;

            SCardError rc = SCardAPI.Lib.Reconnect(cardHandle,
                                         mode,
                                         prefProto,
                                         initExec,
                                         out dwActiveProtocol);

            if (rc == SCardError.Success)
            {
                activeprot = dwActiveProtocol;
                sharemode = mode;
            }

            return rc;
        }
Example #48
0
        /// <summary>Connects the specified reader.</summary>
        /// <param name="readerName">Name of the reader.</param>
        /// <param name="mode">The share mode.</param>
        /// <param name="protocol">The communication protocol. <seealso cref="ISCardReader.Connect(string,SCardShareMode,SCardProtocol)" /></param>
        public virtual void Connect(string readerName, SCardShareMode mode, SCardProtocol protocol) {
            if (readerName == null) {
                throw new ArgumentNullException("readerName");
            }

            if (protocol == SCardProtocol.Unset) {
                throw new InvalidProtocolException(SCardError.InvalidValue);
            }

            if (((long) mode) == 0) {
                throw new InvalidShareModeException(SCardError.InvalidValue);
            }

            var sc = _reader.Connect(readerName, mode, protocol);

            // Throws an exception if sc != SCardError.Success
	        sc.ThrowIfNotSuccess();
        }
Example #49
0
	    private ResponseApdu SimpleTransmit(byte[] commandApdu, int commandApduLength, IsoCase isoCase,
            SCardProtocol protocol, SCardPCI receivePci, ref byte[] receiveBuffer, ref int receiveBufferLength) {
            SCardError sc;
            var cmdSent = false;

            do {
                // send Command APDU to the card
                sc = _reader.Transmit(
                    SCardPCI.GetPci(_reader.ActiveProtocol),
                    commandApdu,
                    commandApduLength,
                    receivePci,
                    receiveBuffer,
                    ref receiveBufferLength);

                // Do we need to resend the command APDU?
                if (sc == SCardError.InsufficientBuffer &&
                    receiveBuffer.Length < receiveBufferLength) {
                    // The response buffer was too small. 
                    receiveBuffer = new byte[receiveBufferLength];

                    // Shall we wait until we re-send we APDU?
                    if (RetransmitWaitTime > 0) {
                        Thread.Sleep(RetransmitWaitTime);
                    }
                } else {
                    cmdSent = true;
                }
            } while (cmdSent == false);

            if (sc == SCardError.Success) {
                return new ResponseApdu(receiveBuffer, receiveBufferLength, isoCase, protocol);
            }

            // An error occurred, throw exception..
		    sc.Throw();
		    return null;
        }
Example #50
0
 /// <summary>Initializes a new instance of the <see cref="IsoReader" /> class and immediately connects to the reader.</summary>
 /// <param name="reader">The supplied reader will be used for communication with the smart card.</param>
 /// <param name="readerName">Name of the reader to connect with.</param>
 /// <param name="mode">The share mode.</param>
 /// <param name="protocol">The communication protocol. <seealso cref="ISCardReader.Connect(string,SCardShareMode,SCardProtocol)" /></param>
 /// <param name="disconnectReaderOnDispose">if set to <c>true</c> the supplied <paramref name="reader" /> will be disconnected on <see cref="Dispose()" />.</param>
 public IsoReader(ISCardReader reader, string readerName, SCardShareMode mode, SCardProtocol protocol,
     bool disconnectReaderOnDispose = true)
     : this(reader, disconnectReaderOnDispose) {
     Connect(readerName, mode, protocol);
 }
Example #51
0
 /// <summary>Initializes a new instance of the <see cref="CommandApdu" /> class.</summary>
 /// <param name="isoCase">The ISO case to use.</param>
 /// <param name="protocol">The protocol.</param>
 public CommandApdu(IsoCase isoCase, SCardProtocol protocol) {
     Case = isoCase;
     Protocol = protocol;
 }
Example #52
0
        public SCardError Reconnect(
            IntPtr hCard,
            SCardShareMode dwShareMode,
            SCardProtocol dwPreferredProtocols,
            SCardReaderDisposition dwInitialization,
            out SCardProtocol pdwActiveProtocol)
        {
            IntPtr activeproto;
            IntPtr result = SCardReconnect(
                (IntPtr)hCard,
                (IntPtr)dwShareMode,
                (IntPtr)dwPreferredProtocols,
                (IntPtr)dwInitialization,
                out activeproto);

            pdwActiveProtocol = (SCardProtocol)activeproto;
            return SCardHelper.ToSCardError(result);
        }
Example #53
0
        public SCardError Connect(
            IntPtr hContext,
            string szReader,
            SCardShareMode dwShareMode,
            SCardProtocol dwPreferredProtocols,
            out IntPtr phCard,
            out SCardProtocol pdwActiveProtocol)
        {
            byte[] readername = SCardHelper._ConvertToByteArray(szReader, textEncoding, SCardAPI.Lib.CharSize);
            IntPtr ctx = (IntPtr)hContext;
            IntPtr sharemode = (IntPtr)dwShareMode;
            IntPtr prefproto = (IntPtr)dwPreferredProtocols;
            IntPtr card;
            IntPtr activeproto;

            IntPtr result = SCardConnect(ctx,
                readername,
                sharemode,
                prefproto,
                out card,
                out activeproto);

            phCard = card;
            pdwActiveProtocol = (SCardProtocol)activeproto;

            return SCardHelper.ToSCardError(result);
        }
Example #54
0
        public SCardError Connect(string name,
                                  SCardShareMode mode,
                                  SCardProtocol prefProto)
        {
            if (name == null ||
                name.Equals(""))
                throw new UnknownReaderException(SCardError.InvalidValue, "Invalid card reader name.");

            if (context == null || context.contextPtr.Equals(IntPtr.Zero))
                throw new InvalidContextException(SCardError.InvalidHandle, "Invalid connection context.");

            SCardError rc;
            IntPtr hCard = IntPtr.Zero;
            SCardProtocol dwActiveProtocol;

            rc = SCardAPI.Lib.Connect(context.contextPtr,
                              name,
                              mode,
                              prefProto,
                              out hCard,
                              out dwActiveProtocol);

            if (rc == SCardError.Success)
            {
                cardHandle = hCard;
                activeprot = dwActiveProtocol;
                readername = name;
                sharemode = mode;
            }

            return rc;
        }
Example #55
0
        public SCardError Disconnect(SCardReaderDisposition discntExec)
        {
            if (cardHandle.Equals(IntPtr.Zero))
                throw new InvalidOperationException(
                    "Reader is currently not connected or no card handle has been returned.");

            SCardError rc = SCardAPI.Lib.Disconnect(cardHandle,
                discntExec);

            if (rc == SCardError.Success)
            {
                // reset local variables
                readername = null;
                cardHandle = IntPtr.Zero;
                activeprot = SCardProtocol.Unset;
                sharemode = SCardShareMode.Shared;
            }

            return rc;
        }
Example #56
0
        /// <summary>Reestablishes a connection to a reader that was previously connected to using
        ///     <see
        ///         cref="M:PCSC.ISCardReader.Connect(System.String,PCSC.SCardShareMode,PCSC.SCardProtocol)" />
        ///     .</summary>
        /// <param name="mode">Mode of connection type: exclusive/shared.
        ///     <list type="table">
        ///         <listheader>
        ///             <term>Value</term><description>Description</description>
        ///         </listheader>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardShareMode.Shared" />
        ///             </term>
        ///             <description>This application will allow others to share the reader. (SCARD_SHARE_SHARED)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardShareMode.Exclusive" />
        ///             </term>
        ///             <description>This application will NOT allow others to share the reader. (SCARD_SHARE_EXCLUSIVE)</description>
        ///         </item>
        ///     </list>
        /// </param>
        /// <param name="preferredProtocol">Desired protocol use.</param>
        /// <param name="initialExecution">Desired action taken on the card/reader before reconnect.</param>
        /// <returns>An error code / return value:
        ///     <list type="table">
        ///         <listheader>
        ///             <term>Error code</term><description>Description</description>
        ///         </listheader>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.Success" />
        ///             </term>
        ///             <description>Successful (SCARD_S_SUCCESS)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidHandle" />
        ///             </term>
        ///             <description>Invalid context handle (SCARD_E_INVALID_HANDLE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidParameter" />
        ///             </term>
        ///             <description>
        ///                 <paramref name="preferredProtocol" /> is invalid or <see langword="null" />  (SCARD_E_INVALID_PARAMETER)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidValue" />
        ///             </term>
        ///             <description>Invalid sharing mode, requested protocol, or reader name (SCARD_E_INVALID_VALUE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoService" />
        ///             </term>
        ///             <description>The server is not runing (SCARD_E_NO_SERVICE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoSmartcard" />
        ///             </term>
        ///             <description>No smart card present (SCARD_E_NO_SMARTCARD)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NotReady" />
        ///             </term>
        ///             <description>Could not allocate the desired port (SCARD_E_NOT_READY)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.ProtocolMismatch" />
        ///             </term>
        ///             <description>Requested protocol is unknown (SCARD_E_PROTO_MISMATCH)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.ReaderUnavailable" />
        ///             </term>
        ///             <description>Could not power up the reader or card (SCARD_E_READER_UNAVAILABLE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.SharingViolation" />
        ///             </term>
        ///             <description>Someone else has exclusive rights (SCARD_E_SHARING_VIOLATION)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.UnsupportedFeature" />
        ///             </term>
        ///             <description>Protocol not supported (SCARD_E_UNSUPPORTED_FEATURE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.CommunicationError" />
        ///             </term>
        ///             <description>An internal communications error has been detected (SCARD_F_COMM_ERROR)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InternalError" />
        ///             </term>
        ///             <description>An internal consistency check failed (SCARD_F_INTERNAL_ERROR)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.RemovedCard" />
        ///             </term>
        ///             <description>The smart card has been removed (SCARD_W_REMOVED_CARD)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.UnresponsiveCard" />
        ///             </term>
        ///             <description>Card is mute (SCARD_W_UNRESPONSIVE_CARD)</description>
        ///         </item>
        ///     </list>
        /// </returns>
        /// <remarks>
        ///     <para>
        ///         <paramref name="preferredProtocol" />  is a bit mask of acceptable protocols for the connection. You can use (<see cref="F:PCSC.SCardProtocol.T0" /> | <see cref="F:PCSC.SCardProtocol.T1" />) if you do not have a preferred protocol. The protocol used with this connection will be stored in <see cref="P:PCSC.ISCardReader.ActiveProtocol" />.</para>
        ///     <para>This method calls the API function SCardReconnect().</para>
        /// </remarks>
        public SCardError Reconnect(SCardShareMode mode, SCardProtocol preferredProtocol,
            SCardReaderDisposition initialExecution)
        {
            ThrowOnInvalidCardHandle();

            SCardProtocol dwActiveProtocol;
            var rc = Platform.Lib.Reconnect(_cardHandle,
                mode,
                preferredProtocol,
                initialExecution,
                out dwActiveProtocol);

            if (rc != SCardError.Success) {
                return rc;
            }

            _activeprot = dwActiveProtocol;
            _sharemode = mode;

            return rc;
        }
Example #57
0
        public SCardError Status(out string[] ReaderName,
                                 out SCardState State,
                                 out SCardProtocol Protocol,
                                 out byte[] Atr)
        {
            SCardError rc;
            IntPtr dwState = IntPtr.Zero;
            IntPtr dwProtocol = IntPtr.Zero;

            rc = SCardAPI.Lib.Status(cardHandle,
                out ReaderName,
                out dwState,
                out dwProtocol,
                out Atr);

            if (rc == SCardError.Success)
            {
                Protocol = SCardHelper.ToProto(dwProtocol);
                State = SCardHelper.ToState(dwState);

                // update local copies
                activeprot = Protocol;
                if (ReaderName.Length >= 1)
                    readername = ReaderName[0];
            }
            else
            {
                Protocol = SCardProtocol.Unset;
                State = SCardState.Unknown;
            }

            return rc;
        }
Example #58
0
        /// <summary>Returns the current status of the reader and the connected card.</summary>
        /// <param name="readerName">The connected readers's friendly name.</param>
        /// <param name="state">The current state.</param>
        /// <param name="protocol">The card's currently used protocol.</param>
        /// <param name="atr">The card's ATR.</param>
        /// <returns><list type="table">
        ///         <listheader>
        ///             <term>Return value</term>
        ///             <description>Description</description>
        ///         </listheader>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.Success" />
        ///             </term>
        ///             <description>Successful (SCARD_S_SUCCESS)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InsufficientBuffer" />
        ///             </term>
        ///             <description>The reader object did not allocate enough memory for <paramref name="readerName" /> or for <paramref name="atr" /> (SCARD_E_INSUFFICIENT_BUFFER)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidHandle" />
        ///             </term>
        ///             <description>The reader object got invalid. Invalid card handle (SCARD_E_INVALID_HANDLE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InvalidParameter" />
        ///             </term>
        ///             <description>The reader object passed a size of null for <paramref name="readerName" /> or <paramref name="atr" />  (SCARD_E_INVALID_PARAMETER)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoMemory" />
        ///             </term>
        ///             <description>Memory allocation failed (SCARD_E_NO_MEMORY)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.NoService" />
        ///             </term>
        ///             <description> The server is not runing (SCARD_E_NO_SERVICE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.ReaderUnavailable" />
        ///             </term>
        ///             <description>The reader has been removed (SCARD_E_READER_UNAVAILABLE)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.CommunicationError" />
        ///             </term>
        ///             <description>An internal communications error has been detected (SCARD_F_COMM_ERROR)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.InternalError" />
        ///             </term>
        ///             <description>An internal consistency check failed (SCARD_F_INTERNAL_ERROR)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.RemovedCard" />
        ///             </term>
        ///             <description>The smart card has been removed (SCARD_W_REMOVED_CARD)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardError.ResetCard" />
        ///             </term>
        ///             <description>The smart card has been reset (SCARD_W_RESET_CARD)</description>
        ///         </item>
        ///     </list>
        /// </returns>
        /// <remarks>
        ///     <para>The connected readers's friendly name will be stored in <paramref name="readerName" />. The card's ATR will be stored in <paramref name="atr" />. The current state, and protocol will be stored in <paramref name="state" /> and <paramref name="protocol" /> respectively.</para>
        ///     <para>This method calls the API function SCardStatus().</para>
        /// </remarks>
        public SCardError Status(out string[] readerName, out SCardState state, out SCardProtocol protocol,
            out byte[] atr)
        {
            IntPtr dwState;
            IntPtr dwProtocol;

            var rc = Platform.Lib.Status(
                _cardHandle,
                out readerName,
                out dwState,
                out dwProtocol,
                out atr);

            if (rc == SCardError.Success) {
                protocol = SCardHelper.ToProto(dwProtocol);
                state = SCardHelper.ToState(dwState);

                // update local copies
                _activeprot = protocol;
                if (readerName.Length >= 1) {
                    _readername = readerName[0];
                }
            } else {
                protocol = SCardProtocol.Unset;
                state = SCardState.Unknown;
            }

            return rc;
        }
Example #59
0
        private ResponseApdu _SimpleTransmit(byte[] cmdApdu, int cmdApduLength, IsoCase isoCase, SCardProtocol proto, SCardPCI recvPci, ref byte[] recvBuf, ref int recvBufLength)
        {
            SCardError sc = SCardError.UnknownError;
            bool cmdSent = false;

            do
            {
                // send Command APDU to the card
                sc = reader.Transmit(
                    SCardPCI.GetPci(reader.ActiveProtocol),
                    cmdApdu,
                    cmdApduLength,
                    recvPci,
                    recvBuf,
                    ref recvBufLength);

                // Do we need to resend the command APDU?
                if (sc == SCardError.InsufficientBuffer &&
                    recvBuf.Length < recvBufLength)
                {
                    // The response buffer was too small.
                    recvBuf = new byte[recvBufLength];

                    // Shall we wait until we re-send we APDU?
                    if (_retransmitWaitTime > 0)
                        Thread.Sleep(_retransmitWaitTime);
                }
                else
                    cmdSent = true;
            } while (cmdSent == false);

            if (sc == SCardError.Success)
            {
                ResponseApdu respApdu = new ResponseApdu(recvBuf, recvBufLength, isoCase, proto);
                return respApdu;
            }

            // An error occurred, throw exception..
            ThrowExceptionOnSCardError(sc);
            return null;
        }
Example #60
0
        /// <summary>Establishes a connection to the Smart Card reader.</summary>
        /// <param name="readerName">Reader name to connect to.</param>
        /// <param name="mode">Mode of connection type: exclusive or shared.
        ///     <list type="table">
        ///         <listheader>
        ///             <term>Value</term><description>Description</description>
        ///         </listheader>
        ///         <item>
        ///             <term><see cref="F:PCSC.SCardShareMode.Shared" /></term>
        ///             <description>This application will allow others to share the reader. (SCARD_SHARE_SHARED)</description>
        ///         </item>
        ///         <item>
        ///             <term>
        ///                 <see cref="F:PCSC.SCardShareMode.Exclusive" />
        ///             </term>
        ///             <description>This application will NOT allow others to share the reader. (SCARD_SHARE_EXCLUSIVE)</description>
        ///         </item>
        ///     </list>
        /// </param>
        /// <param name="preferredProtocol">Desired protocol use.</param>
        /// <returns>An error code / return value:
        ///     <para>
        ///         <list type="table">
        ///             <listheader>
        ///                 <term>Error code</term><description>Description</description>
        ///             </listheader>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.Success" />
        ///                 </term>
        ///                 <description>Successful (SCARD_S_SUCCESS)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.InvalidHandle" />
        ///                 </term>
        ///                 <description>Invalid context handle (SCARD_E_INVALID_HANDLE)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.InvalidParameter" />
        ///                 </term>
        ///                 <description>
        ///                     <paramref name="preferredProtocol" /> is invalid or <see langword="null" />  (SCARD_E_INVALID_PARAMETER)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.InvalidValue" />
        ///                 </term>
        ///                 <description>Invalid sharing mode, requested protocol, or reader name (SCARD_E_INVALID_VALUE)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.NoService" />
        ///                 </term>
        ///                 <description>The server is not runing (SCARD_E_NO_SERVICE)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.NoSmartcard" />
        ///                 </term>
        ///                 <description>No smart card present (SCARD_E_NO_SMARTCARD)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.NotReady" />
        ///                 </term>
        ///                 <description>Could not allocate the desired port (SCARD_E_NOT_READY)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.ProtocolMismatch" />
        ///                 </term>
        ///                 <description>Requested protocol is unknown (SCARD_E_PROTO_MISMATCH)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.ReaderUnavailable" />
        ///                 </term>
        ///                 <description>Could not power up the reader or card (SCARD_E_READER_UNAVAILABLE)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.SharingViolation" />
        ///                 </term>
        ///                 <description>Someone else has exclusive rights (SCARD_E_SHARING_VIOLATION)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.UnknownReader" />
        ///                 </term>
        ///                 <description>The reader name is <see langword="null" /> (SCARD_E_UNKNOWN_READER)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.UnsupportedFeature" />
        ///                 </term>
        ///                 <description>Protocol not supported (SCARD_E_UNSUPPORTED_FEATURE)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.CommunicationError" />
        ///                 </term>
        ///                 <description>An internal communications error has been detected (SCARD_F_COMM_ERROR)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.InternalError" />
        ///                 </term>
        ///                 <description>An internal consistency check failed (SCARD_F_INTERNAL_ERROR)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.UnpoweredCard" />
        ///                 </term>
        ///                 <description>Card is not powered (SCARD_W_UNPOWERED_CARD)</description>
        ///             </item>
        ///             <item>
        ///                 <term>
        ///                     <see cref="F:PCSC.SCardError.UnresponsiveCard" />
        ///                 </term>
        ///                 <description>Card is mute (SCARD_W_UNRESPONSIVE_CARD)</description>
        ///             </item>
        ///         </list>
        ///     </para>
        /// </returns>
        /// <remarks>
        ///     <para>
        ///         <paramref name="preferredProtocol" />  is a bit mask of acceptable protocols for the connection. You can use (<see cref="F:PCSC.SCardProtocol.T0" /> | <see cref="F:PCSC.SCardProtocol.T1" />) if you do not have a preferred protocol. The protocol used with this connection will be stored in <see cref="P:PCSC.ISCardReader.ActiveProtocol" />.</para>
        ///     <para>This method calls the API function SCardConnect().</para>
        ///     <example>
        ///         <code lang="C#">
        /// // Establish PC/SC context.
        /// SCardContext ctx = new SCardContext();
        /// ctx.Establish(SCardScope.System);
        /// 
        /// // Create a Smart Card reader object and connect to it.
        /// ISCardReader reader = new SCardReader(ctx);
        /// SCardError serr = reader.Connect("OMNIKEY CardMan 5x21 00 00",
        /// 	SCardShareMode.Shared,
        /// 	SCardProtocol.Any);
        ///   </code>
        ///     </example>
        /// </remarks>
        public SCardError Connect(string readerName, SCardShareMode mode, SCardProtocol preferredProtocol)
        {
            if (readerName == null) {
                throw new ArgumentNullException("readerName");
            }

            if (readerName.IsNullOrWhiteSpace()) {
                throw new UnknownReaderException(SCardError.InvalidValue, "Invalid card reader name.");
            }

            if (_context == null || _context.Handle.Equals(IntPtr.Zero)) {
                throw new InvalidContextException(SCardError.InvalidHandle, "Invalid connection context.");
            }

            IntPtr hCard;
            SCardProtocol dwActiveProtocol;

            var rc = Platform.Lib.Connect(_context.Handle,
                readerName,
                mode,
                preferredProtocol,
                out hCard,
                out dwActiveProtocol);

            if (rc != SCardError.Success) {
                return rc;
            }

            _cardHandle = hCard;
            _activeprot = dwActiveProtocol;
            _readername = readerName;
            _sharemode = mode;

            return rc;
        }