使用WinSCard库获取mifare卡序列号

时间:2013-05-31 11:50:01

标签: c# .net rfid mifare winscard

我正在开发一个需要读取mifare卡序列号的应用程序,我正在使用的语言是C#。

我是mifare读者编程的新手,所以我很抱歉提出愚蠢的问题。 首先,我想知道Mifare UID和Mifare序列号之间是否存在差异。

我已经设法在WinSCard库的帮助下获得了UID,但是我无法弄清楚如何获得应该是10位数的卡序列号。

如果你能指出我正确的方向,我很感激。

提前感谢您的帮助。 此致

2 个答案:

答案 0 :(得分:10)

SCardTransmit方法的C#签名

[StructLayout(LayoutKind.Sequential)]
public struct SCARD_IO_REQUEST
{
   public int dwProtocol;
   public int cbPciLength;
}

[DllImport("winscard.dll")]
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);

读取mifare卡的UID的代码示例

private SmartcardErrorCode GetUID(ref byte[] UID)
    {
        byte[] receivedUID = new byte[10];
        UnsafeNativeMethods.SCARD_IO_REQUEST request = new UnsafeNativeMethods.SCARD_IO_REQUEST();
        request.dwProtocol = 1; //SCARD_PROTOCOL_T1);
        request.cbPciLength =    System.Runtime.InteropServices.Marshal.SizeOf(typeof(UnsafeNativeMethods.SCARD_IO_REQUEST));
        byte[] sendBytes = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x04 }; //get UID command      for Mifare cards

        int outBytes = receivedUID.Length;
        int status = SCardTransmit(_hCard, ref request, ref sendBytes[0], sendBytes.Length,  ref request, ref receivedUID[0], ref outBytes);

        UID = receivedUID.Take(8).ToArray(); 
        return status;
    }

答案 1 :(得分:0)

“选择的答案”不适用于x64环境。

这里是完整的示例代码,已在Windows 10 x64上测试并运行。 这是做什么的:

  • 获取可用读者列表
  • 选择使用第一个可用的阅读器
  • 检查读卡器中是否有卡并已连接。
  • 将命令传输到卡以检索其UID
  • 将UID转换为十六进制字符串。

       a  b  f  d  e  c
    0  1  0  0  0  0  0
    1  1  1  0  0  0  0
    2  0  0  2  1  1  0
    3  0  0  1  1  1  0
    4  1  1  0  0  0  1
    

PInvoke文档提供了很多帮助:https://www.pinvoke.net/default.aspx/winscard.scardtransmit