Content upgraded and moved to my own website. Access here:
https://www.iranthajayasekara.com/blog/read-and-write-to-nfc-card-with-acr122u-reader.html
https://www.iranthajayasekara.com/blog/read-and-write-to-nfc-card-with-acr122u-reader.html
A BLOG FOR MY FINDINGS ON C# PROGRAMMING
Sir, when i try to read the UID from card using your code, it gives me error
ReplyDeleteWhat is the error? and what is your card type? Can you give me more details?
DeleteError is : 6
DeleteI changed the settings in configuration manager to x86 also
M using
ACR 122U nfc reader
Win 8 64 bit
VS 2010 (i also have VS 2012)
I dont know about the card
may b its Mifare 4K
Error 6 refer to "the card has been reset and specific communication protocols have been established". can you try with different card?
DeleteI tried with Mifare 1K cards but APDU command should works with 4K also.
Yes
DeleteI have tried with 5 different cards
It gives me the same result
Hi Malvinder,
DeleteI tried just now with 4K cards and its works fine. please make sure your card type is Mifare 1K, 4K or Ultralight.
I had the same error but got fixed changing "Compile>Target CPU = x86"...the problem was smart card driver version and OS 64bit version
DeleteYes, sir
ReplyDeleteI am sure its Mifare 4k
Apart from the Cars.cs file
here's the code for winform
public List ListReaders()
{
int ReaderCount = 0;
List AvailableReaderList = new List();
//Make sure a context has been established before
//retrieving the list of smartcard readers.
retCode = Card.SCardListReaders(hContext, null, null, ref ReaderCount);
if (retCode != Card.SCARD_S_SUCCESS)
{
MessageBox.Show(Card.GetScardErrMsg(retCode));
//connActive = false;
}
byte[] ReadersList = new byte[ReaderCount];
//Get the list of reader present again but this time add sReaderGroup, retData as 2rd & 3rd parameter respectively.
retCode = Card.SCardListReaders(hContext, null, ReadersList, ref ReaderCount);
if (retCode != Card.SCARD_S_SUCCESS)
{
MessageBox.Show(Card.GetScardErrMsg(retCode));
}
string rName = "";
int indx = 0;
if (ReaderCount > 0)
{
// Convert reader buffer to string
while (ReadersList[indx] != 0)
{
while (ReadersList[indx] != 0)
{
rName = rName + (char)ReadersList[indx];
indx = indx + 1;
}
//Add reader name to list
AvailableReaderList.Add(rName);
rName = "";
indx = indx + 1;
}
}
return AvailableReaderList;
}
private string getcardUID()//only for mifare 1k cards
{
string cardUID = "";
byte[] receivedUID = new byte[256];
Card.SCARD_IO_REQUEST request = new Card.SCARD_IO_REQUEST();
request.dwProtocol = Card.SCARD_PROTOCOL_RAW;
request.cbPciLength = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Card.SCARD_IO_REQUEST));
byte[] sendBytes = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; //get UID command for Mifare cards
int outBytes = receivedUID.Length;
int status = Card.SCardTransmit(hCard, ref request, ref sendBytes[0], sendBytes.Length, ref request, ref receivedUID[0], ref outBytes);
if (status != Card.SCARD_S_SUCCESS)
{
MessageBox.Show(status.ToString());
}
else
{
cardUID = BitConverter.ToString(receivedUID.Take(4).ToArray()).Replace("-", string.Empty).ToLower();
}
return cardUID;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
/*for (int i = 0; i <= 10; i++)
{*/
string cardUId = getcardUID();
listBox2.Items.Add(cardUId);
/* Thread.Sleep(2000);
}*/
}
catch (Exception ex)
{
}
}
Looks like you didn't establish the context before you connect the reader.
Deletecheck your code again. check whether you call establishContext() method.
Hello, Thanks for your nice article, I did everything you said but i have some problem with your codes:
ReplyDeletewhen I try to get UID of Mifare 1k it textbox show me "17900000" for all of mifare 1k cards.
and when I try to read or write block textbox show me "FailAuthentication"
can you help me??? thanks a lot
Hi Morid,
DeleteYou are welcome!
Can you check your cards information with any other way like Android application?
Did you try with block number 5 ? Can you try with brand new card?
hi i am getting different uid number in nfc mobile and through this code.both are different and when i read or write its gives a msg that failed authentication
ReplyDeleteHi Nikitha,
DeleteSorry for the delay.
What is your card type? Mifare 1K ?
The reason why you can't read or write is you have encrypted the card before. You will need that encrypted code to write and read data.
Hai jeyasekar i using Ask smart card reader i am getting UID but i am trying to read data from card i return -2146434967 this number how to i fix it
ReplyDeleteError code means that the smart card has been removed on the reader,
DeleteCheck this link:
http://stackoverflow.com/a/19110907/1134291
thanks for your reply, Now I am getting error code 69 84 on read or write data in smart card how to solve this issue
DeleteHi IJ,
ReplyDeleteI hope you always in the great life...
I want to ask something. How to detect card continuously then the read card data executed without clicking a login button?
Thank you..
Hi Duni,
Deleteyes you can, its quite a handy work.
will give u a hint, you have to write a event catcher for catch the change of the reader status.
SCardGetStatusChange() method and SCARD_READERSTATE struct
Good luck!
Hi Duni,
Deletethis works for me enjoy
internal enum SmartcardState
{
None = 0,
Inserted = 1,
Ejected = 2
}
private BackgroundWorker _worker;
private Card.SCARD_READERSTATE[] states;
public void SelectDevice()
{
List availableReaders = this.ListReaders();
if (availableReaders.Count == 0) { return; }
this.RdrState = new Card.SCARD_READERSTATE();
readername = availableReaders[0].ToString();//selecting first device
this.RdrState.RdrName = readername;
///
states = new Card.SCARD_READERSTATE[1];
states[0] = new Card.SCARD_READERSTATE();
states[0].RdrName = readername;
states[0].UserData = IntPtr.Zero;
states[0].RdrCurrState = Card.SCARD_STATE_EMPTY;
states[0].RdrEventState = 0;
states[0].ATRLength = 0;
states[0].ATRValue = null;
if (availableReaders.Count > 0)
{
this._worker = new BackgroundWorker();
this._worker.WorkerSupportsCancellation = true;
this._worker.DoWork += WaitChangeStatus;
this._worker.RunWorkerAsync();
}
}
private void WaitChangeStatus(object sender, DoWorkEventArgs e)
{
while (!e.Cancel)
{
int nErrCode = Card.SCardGetStatusChange(hContext, 1000, ref states[0], 1);
//Check if the state changed from the last time.
if ((this.states[0].RdrEventState & 2) == 2)
{
//Check what changed.
SmartcardState state = SmartcardState.None;
if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
{
//The card was inserted.
state = SmartcardState.Inserted;
}
else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
{
//The card was ejected.
state = SmartcardState.Ejected;
}
if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
{
switch (state)
{
case SmartcardState.Inserted:
{
MessageBox.Show("Card inserted");
break;
}
case SmartcardState.Ejected:
{
MessageBox.Show("Card ejected");
break;
}
default:
{
MessageBox.Show("Some other state...");
break;
}
}
}
//Update the current state for the next time they are checked.
this.states[0].RdrCurrState = this.states[0].RdrEventState;
}
}
}
Awesome!
DeleteIll try this.
Thank you Petr
You are welcome let me know if any issue
DeletePetr Toth, thank you, I will try it...
DeleteGreat code. Thanks for sharing.
DeleteDear sir,
Delete64 bit system background worker is not working properly sir ...any idea ?
SendAPDUandDisplay, ClearBuffers, and AuthenticateBlock is not in current context...How should I fix that? Thank you!
ReplyDeleteHello Maron,
DeleteDid you copy all the codes displayed here? I have coded SendAPDUandDisplay(), ClearBuffers() and authenticateBlock(String block) methods. Please come through the previous post and try again.
Thanks
Hi, this article is what I'm looking for. Thanks a lot :) Btw, I'd like to automatically connect the reader and display the card UID to the textbox without pressing a button. The card UID is displayed automatically every time a new card is tapped... How can I do this?
ReplyDeleteHi, your question same as mine and Petr Toth already answer in this page (you can check above noted)...
DeleteI am still trying and get error for this "The calling thread cannot access this object because a different thread owns it."...
case SmartcardState.Inserted:
{
string text = verifyCard("5"); // 5 - is the block we are reading
textBlock1.Text = text.ToString(); // error on this line
MessageBox.Show("Card inserted");
break;
}
I am still working on this and if I have the answer I let you know...
Hi all you have to create new thread
Deleteusing System.Threading;
then
case SmartcardState.Inserted:
{
//MessageBox.Show("Card inserted");
Dispatcher.BeginInvoke(new ThreadStart(() =>
{
your text field or label or.Text = "Card inserted";
}));
break;
}
Also i did read/write for mifare ultralight cards if this interest you let me know in this blog
DeleteHi Petr,
DeleteThank you for your help... Is every card have different code (problems) to display data and read them, like mifare (I though all mifare has same code)...
This comment has been removed by the author.
DeleteRead is same for mifare standard and ultralight, only write is little bit different for ultralight.
DeleteI see... You help a lot Petr...
DeleteIt's maybe sound a silly questions for the expert, but I want to know...
How to determine which one mifare classic with other card when the card tapped in to the reader?
Card type is include ATR string so for example:
Deletecase SmartcardState.Inserted:
{
string CardType = BitConverter.ToString(states[0].ATRValue.Take(15).ToArray()).Replace("-", string.Empty);
CardType = CardType.Substring(26, 4);
}
give you :
0001 = standard
0003 = ultralight
For another card brands you have to find out this number.
DeleteThanks, I'll try with the Ultralight asap...
DeleteHi, I have a solution to this one....
ReplyDeleteYou have to create a function that will set the textbox text property to show the card's UID every time a card is tapped/changed state...
private void showTheFuckingUID()
{
//This function is necessary to avoid the stated error when setting the text in the TextBox property.
//ERROR: Cross-thread operation not valid: Control 'textBlock1' accessed from a thread other than the thread it was created on.
if (this.txtstud_No.InvokeRequired == true)
{
txtstud_No.Invoke(new MethodInvoker(delegate
{
txtstud_No.Text = getUID();
performOperation();
}));
}// if (this.textBlock1.InvokeRequired == true)
}//private void showTheFuckingUID()
You just have to call your function in the WaitChangeStatus(.......) in the SmartcardState.Inserted case :) I hope that helps.....
ReplyDeleteprivate void WaitChangeStatus(object sender, DoWorkEventArgs e)
{
while (!e.Cancel)
{
int nErrCode = Card.SCardGetStatusChange(hContext, 1000, ref states[0], 1);
//Check if the state changed from the last time.
if ((this.states[0].RdrEventState & 2) == 2)
{
//Check what changed.
SmartcardState state = SmartcardState.None;
if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
{
//The card was inserted.
state = SmartcardState.Inserted;
}// if ((this.states[0].RdrEventState & 32) == 32 && (this.states[0].RdrCurrState & 32) != 32)
else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
{
//The card was ejected.
state = SmartcardState.Ejected;
}// else if ((this.states[0].RdrEventState & 16) == 16 && (this.states[0].RdrCurrState & 16) != 16)
string stats = "";
if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
{
switch (state)
{
case SmartcardState.Inserted:
{
stats = "Card State: Card INSERTED";
showTheFuckingCardStatus(stats);//Displays the card's changed state
showTheFuckingUID();//Displays the Card UID/Serial & the Student Details
timeInOut();//Card Read&Write Functions
break;
}//case SmartcardState.Inserted:
case SmartcardState.Ejected:
{
stats = "Card State: Card EJECTED";
showTheFuckingCardStatus(stats);
break;
}//case SmartcardState.Ejected:
default:
{
stats = "Card State: UNKNOWN STATE";
showTheFuckingCardStatus(stats);
break;
}// default:
}//switch (state)
}//if (state != SmartcardState.None && this.states[0].RdrCurrState != 0)
//Update the current state for the next time they are checked.
this.states[0].RdrCurrState = this.states[0].RdrEventState;
}// if ((this.states[0].RdrEventState & 2) == 2)
}//while (!e.Cancel)
}//private void WaitChangeStatus(object sender, DoWorkEventArgs e)
private string getUID()
{
if (connectCard())
{
string cardUID = getcardUID();
return cardUID;
}//if (connectCard())
else
{
return null;
}//else
}//private void getUID
hi thank you for the code! can i have your project please. the whole vb solution. please
Deleteref states[0] not changing the RdrEventState
Deletein c# asp.net
hi Irantha Jayasekara
ReplyDeletethanks for his article, it is useful for me
i try it i am getting card uid using this code
but when I try to read or write block textbox show me "FailAuthentication"
i am using "acr122u" reader and card type is "Mifare Classic 1k" card
and what is block
submitText(TextBox1.Text, "5");
thanks in advance.
Hi Ketan,
DeleteThank you for compliment.
Block is the where you write data in to the card. you have plenty of location in a card that you can write data. Also there are some restricted blocks you should not write in to.
check this link for more information;
https://learn.adafruit.com/adafruit-pn532-rfid-nfc/mifare
Fail authentication mean you have set up key to that block earlier. Try to write in to the block 9.
thanks irantha
Deletei solved my problem for Mifare Classic card using mifare classic tool android app factory format.
but now i have one another card, type is "Mifare ultralight" and i am getting same error and this android app is only for mifare classic card.
so i can't format
and i am use block 9 but not solve.
max block is?
and any idea for Mifare ultralight card?
Im sorry I didn't check with another card types.
Deletethanks i got it my card problem if any one getting this problem than using
ReplyDeletemifare classic tool android app and card factory formate than you can read write your card.
Dear Irantha Jayasekara,
ReplyDeleteFirst of all, Thanks for the nice article. I tried your source on another NFC reader but when I read the NFC card (MiFare 1K) it keeps display ? What should I do ?
Im sorry, I'm not sure whether it works with another type of readers. What do you mean by it keeps display?
DeleteCan I read data via P2P insted of card blocks. I need to transfer data from a Cordova mobile application to a ACR122U and cannot use host-based card emulation. Thanks
ReplyDeleteHi Sir,
ReplyDeleteI can not find "winscard.dll". Please help me!
What is your windows operating system? can you manually register winscard.dll ?
DeleteRead more from here;
http://www.solvusoft.com/en/files/missing-not-found-error/dll/windows/microsoft/msdn-windows-codename-whistler-personal-beta-1/winscard-dll/
Irantha, you have not been coming online like before. Pls we still need your assistant on the mifare Ultralight coding I keep getting FailAuthentiation when i try to read or write to the card.
DeleteWhen you have to read/write to ultralight cards you don't need to do any authentication, you can find this info here":https://learn.adafruit.com/adafruit-pn532-rfid-nfc/mifare
DeleteHi sir,
ReplyDeleteim getting this error code, 69 88 which is SM_INCORRECT or secure messaging data objects are incorrect can you help me solve this? thanks
Hi Irantha Jayasekara,
ReplyDeleteI'm using ACS122u-A9. It's quite similar, reading uid works perfectly.
Unfortunately i can't either read or write data on card, it gives me an error, it returns 0 on SCardTransmit all the time so SendAPDUandDisplay method returns -202 what is "Return bytes are not acceptable."
error is the same if i m sending the data from textbox or no data is sent from textbox.
Please suggest needful.
I have the same problem. I can read the uid however whenever I try to read/write gives failauthentication error
DeleteACS 122u-A9 authenticateBloc works fine by changing the sendbuff values as below now i am searching for read and write ...
Deleteprivate bool authenticateBlock(IntPtr handle, int proto, string Block)
{
ClearBuffers();
SendBuff[0] = 0xFF;
SendBuff[1] = 0x82;
SendBuff[2] = 0x00;
SendBuff[3] = 0x00;
SendBuff[4] = 0x06;
SendBuff[5] = 0xFF;
SendBuff[6] = 0xFF;
SendBuff[7] = (byte)int.Parse(Block); //0xFF;
SendBuff[8] = 0xFF;
SendBuff[9] = (byte)int.Parse("1"); //0xFF;
SendBuff[10] = 0xFF;
SendLen = 0x0B;
RecvLen = 0x02;
Hi Irantha Jayasekara,
ReplyDeleteNow i am able to READ/WRITE on the particular block of card .But the still problem is that i have to WRITE DATA on all the blocks at once and same for READ DATA at once as well.
So if i m doing it by looping method then "FailAuthentication" error is occurring in both the cases.
Please suggest needful in order to WRITE AND READ DATA in all blocks at once.
Tell me how did you manage to read/write data from/on a certain block. Because I can see you had problem with authentication few days ago.
Deletei had used above code for read and write into NFC card.
Deletethanks for reply,
DeleteBut how did you manage to fix authentication after having the same error?
Hi, I used this code to write to blocks 1-15 and after some reading and writing the blocks fail authentication, what could have happened and how do I fix this card?
ReplyDeleteFull code and project files https://app.box.com/s/g8jwjuiicxu8vvtyhnb7drbqh4b7jrnv
DeleteI think I know what I did. I have acidentally overwritten the keys for each block. FYI anyone else do not use blocks 0,3,7,11,15
DeleteHi Matthew Wood,
DeleteYou mean to say we can't write data in blocks 0,3,7,11,15 because after writing data on these blocks "FailAuthentiation" error is occurring. right...?
And if you have resolved(reset cards as default) the problem in overwritten cards then please suggest me also how to reset those as default !
did you found how to reset the card ?
DeleteThanks very much for this post. Please i have followed your code but get FailAuthentiation each time i try to read or write to my Mifare Ultralight card. What is the problem pls. Also you can contact me for paid support on this project. Thanks
ReplyDeleteRead Function:
ReplyDeletewhat can i do read NDEF code? Thanks
thank you for your useful post. It's very helpful.
ReplyDeleteI would like to something to ask you that How can i recover the sector after I write data into block 3 in this sector.
You should not write data in to these blocks 0,3,7,11,15.
DeleteI am not sure how to recover them.
How to prevent rewrite on same block that previously written data
ReplyDeleteU can handle it by ur code, check if the block is empty, if not, write to it
Deletesir I need Write Protected ...
DeleteSir, I am able to write and read data in mifare 1kb card but i am unable make the card data secure.
ReplyDeleteHi Sir,
ReplyDeleteHow to do read/write ndef block?
thanks for you help
Great article,, Sir, i want ask, when leng character i change to be more than 16, it's can't write,,,
ReplyDeletehow if i want to write more than 16 character??
If you want to write more than 16 characters, you need to write to to blocks, so you have to make and custom mechanism that will divide your string into 16characters strings and write them on different blocks....
Deletesolved!!
Deletethank you sir :D
Hi guys, how do I write to an ultrahigh card?
ReplyDeleteAny help greatly appreciated.
Thanks
Great post, and great code. Thank you very much.
ReplyDeleteHello how to automatically read data when i tap the card? I create a function that will send the data to textbox. My problem is where i will put the function
ReplyDeleteThank you very much it helps me a lot
ReplyDeleteNow i am able to READ/WRITE on the particular block of card .
Hello Sir
ReplyDeletewhen leng of character i change to be more than 16, it's can't write,,,
how if i want to write more than 16 character??
please ans me i a waiting for answer.....
If you want to write more than 16 characters, you need to write to two blocks, so you have to make and custom mechanism that will divide your string into 16 characters strings and write them on different blocks. but make sure you do not write data in to these blocks 0,3,7,11,15.
DeleteThis comment has been removed by the author.
ReplyDeleteSir I am unable to Build the project. 1 Failed
ReplyDeleteHey, I still get the FailAuthentication problem. Could somebody tell how to fix it?
ReplyDeleteHi sir @Irantha Jayasekara. Good day, can i have your project uploaded here please. Im a first timer in this technology. Please and thank you in advance :)
ReplyDeleteHello, Whenever I attempt to read more than two blocks in a row I get the error "The thread 0x84 has exited with code 0 (0x0)." Does anyone know how to fix this and what will allow me to read multiple blocks at what time?
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHi,
ReplyDeleteThank you for this awesome code.How can I change the default Authentication Key?
Thank you
How I can get the CardUID without click button 1 ?
ReplyDeletehi, i tried this code and got output successful... but i have one major problem... u gave this code..
ReplyDeletesubmitText(textBox1.Text, "5"); // 5 - is the block we are writing data on the card
here it save and also read from the block"5"...
so i tried the same method with different block's... to save multiple textbox datas...like this ..
write operation..
submitText(regnumber, "5");
submitText(firstname, "6");
submitText(lastname, "7");
submitText(finnumber, "8");
submitText(dt, "9");
read operation...
string a = verifyCard("5");
txtShow4.Text = a.ToString();
string b = verifyCard("6");
txtShow3.Text = b.ToString();
string c = verifyCard("7");
txtShow2.Text = c.ToString();
string d = verifyCard("8");
txtShow1.Text = d.ToString();
at first time it execute without any error...
but when i tried to rewrite the datas...i mean update the data on that block's again and again..it returns "fail authentication" error.. so i tried with some other blocks...like 20,21,22,23,24,,,etc.. in all i got same error..
pls help to overcome that problem...
You should not write data in to these blocks 0,3,7,11,15.
DeleteI am not sure how to recover them now.
Hi,
ReplyDeleteThanks for the code above . Its very helpfull to me for creating an windows form application, But now iam facing a problem.
The code is working fine in windows form, but i used this in web application iam facing retcode=Card.SCardTransmit() getting a value of "6". why iam getting this error in web application, friends please help me to solve this issue, i already wasted a lot of time for this, now its very urgent, please help me frinds,
Thanks
Hi Irantha Jayasekara,
ReplyDeleteThanks for this article. I tried and successfully read and write data to the card. But I want to trigger the data reading method at the time of tap the card on NFC reader. Now i need to click the read button for getting the data stored in the card. Please help me.
Thanks
Hi Sir,
ReplyDeleteThank you for this helpful article. I already successfully display card UID without clicking a button. Right now, i'm working on multiple forms and i want to reset the device everytime i open another form. Please help me.
Thanks
It is really grateful if you could tell me,that how can I detect the UID of the card without clicking the button...
DeleteHello Sir
ReplyDeleteWIll this code work with ACS ACR1251U?
Yes its work fine. :-)
Deletehow to read and write on each and every block of nfc card in c#
ReplyDeleteWhat a great write up, and I can read the UID from a NTAG213 with a ACR122 Reader on Windows 10. But I can't read or write custom data to the tag all I get is "Fail Authentication" any ideas as this is so close.
ReplyDeleteHey where can I get the full source code?
ReplyDeletehow to read and write card mifare 1K with acr 122u with php? please
ReplyDeleteHow to resolve Fail Authentication response?
ReplyDeleteI think the mifare card or rfid wristband should be never used to make it write success . means if u already tapped it to perform write and read card using commercial software like gototags. there will be Fail Authentication
DeleteIn connectCard() function i received retCode as -2146434967 and function return false. Any idea regarding this issue.?
ReplyDeleteThank you for such great article. May I ask is there anyway to make the application to run with x64? I have tried renaming [DllImport("C:\\Windows\\System32\\WinSCard.dll")]
ReplyDeleteto
[DllImport("C:\\Windows\\System34\\WinSCard.dll")]
However, the program will not compile, it says System.BadImageFormatException: 'An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)'
same error. Fail Authentication
ReplyDeleteGreat guidance.. make me success to explore PC/SC. Many thanks
ReplyDeleteHi,
ReplyDeletei got this code from petr Toth and it was very helpful.
///
states = new Card.SCARD_READERSTATE[1];
states[0] = new Card.SCARD_READERSTATE();
states[0].RdrName = readername;
states[0].UserData = IntPtr.Zero;
states[0].RdrCurrState = Card.SCARD_STATE_EMPTY;
states[0].RdrEventState = 0;
states[0].ATRLength = 0;
states[0].ATRValue = null;
may i ask how to fix this error, something about cannot be converted.
Error:
Cannot implicitly convert type 'System.IntPtr' to 'Int'. An explicit
conversion exists(are you missing a cast?)
For a very long time I was trying to find a solution. Thanks to you, it was found. Many thanks!
ReplyDeletedid you try two NFC card reader at the same time?, is it possible to work with that code above. because based on what i have read, the reader can be listed
ReplyDeleteHaven't tried but am sure its possible, you may select availabledevice[1] in case for second nfc device, make a background worker and access it.
DeleteHi Irantha Jayasekara, hoping you'll be fine. I've been using your code since a year now and its really helpful and working perfectly well until now.
ReplyDeleteI recently ordered a new NFC 122 Device from china, initially it was not connected after debugging a bit of code I got to know on my computer it was showing as RFCARD RF1258V603 so i changed type from 122 to RFCARD RF1258V603 and found the list number and so made it working.
BUT for some reason i'm only able to read the card uid but I am NOT able to read/write anything and i get the error of FailAuthentication, on further debugging i did get to know that the failed authentication is occurring because its returning the code -202 that means the byes being received are not 90 00.
Its urgent any help in this regard would be really helpful.
Please note the same code is working perfectly fine with the previously order NFC devices, these new ones are failing.
Please note the previous device had a properly printed model acr122u-a9 where as the new device has a Chinese label acr122-a9u.
Looking towards a solution.
Just for the sake of information, Problem Resolved:
ReplyDeleteThese readers required loading authentication key first before authentication and read/write.
To load the authentication key you need to perform the below before authenticationblock function:
ClearBuffer()
SendBuff(0) = &HFF
SendBuff(1) = &H82
SendBuff(2) = &H0
SendBuff(3) = &H0
SendBuff(4) = &H6
SendBuff(5) = &HFF
SendBuff(6) = &HFF
SendBuff(7) = &HFF
SendBuff(8) = &HFF
SendBuff(9) = &HFF
SendBuff(10) = &HFF
' Byte 5 : Session key for non-volatile memory
SendLen = &HB
RecvLen = &H2
retCode = SendAPDUandDisplay(0)
yeps its working but read and right still returning 63 00
Deletecan you guide me about SendBuff for read and write
WOW everything working fantastic ... but the dirty blocks 0,3,7,11,15, 19, 27, 35, 39 really disturbing don't write anything on these blocks
DeleteBro , how you fix the issue? now card is successfully authenticate but still i can't read or write? when reading it returns 63 00
DeleteThis comment has been removed by the author.
ReplyDeleteSir this article helped me a lot God bless you... i am facing a problem at the moment is private bool authenticateBlock(String block) reaches to the below line...
ReplyDeleteif ((tmpStr).Trim() != "90 00")
{
//MessageBox.Show("Return bytes are not acceptable.");
return -202;
}
but once i read card block from NFCTEST.exe the above code starts working... i think after using NFCTEST.exe device ACR122U become enabled or what ever plz guide me if you know why this is happening.
its working by changing this
Deleteprivate bool authenticateBlock(IntPtr handle, int proto, string Block)
{
ClearBuffers();
SendBuff[0] = 0xFF;
SendBuff[1] = 0x82;
SendBuff[2] = 0x00;
SendBuff[3] = 0x00;
SendBuff[4] = 0x06;
SendBuff[5] = 0xFF;
SendBuff[6] = 0xFF;
SendBuff[7] = (byte)int.Parse(Block); //0xFF;
SendBuff[8] = 0xFF;
SendBuff[9] = (byte)int.Parse("1"); //0xFF;
SendBuff[10] = 0xFF;
SendLen = 0x0B;
RecvLen = 0x02;
but read and write still not working
Hello bro, how i configure TypeATR in ur code? My Card is of Identification of URuguay i have a HExadecimal Code string of ATR TypeCard. I always get an error when SCardConnect() is executed
ReplyDeleteSome can help me i get retCode = -2146434967 in Card.SCardConnect()...
ReplyDeleteI need really help
Great Contribution.
ReplyDeleteThanks a lot
First thing first I want to thank you to Irantha for providing the code. it's really helpful for me!
ReplyDeleteAfter struggling "Fail Authentication" for 2 days, I found my solution.
I tried many ways (which mentioned above by some people) but it still appeared. My solution is to update the source code, which adding an additional authentication between the Reader and the card (because I used Mifare Classic 1K which is need 3 PASS AUTHENTICATIONS).
I use ACR123U anyway.
After adding an additional authentication, I can do both read & write (rewrite), no problem occurred so far.
DeleteHOW AND WHERE DID U ADD additional authentication CAN U SHARE CODE?
ReplyDeletehi sir.. i need some help.. can someone help me? i want to create an attendance system using nfc (acr122u).. Can somesone help me.. please sir give me some source code for this..
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThose facing problem with X64 please change all Integer/Int32 to IntPtr. Here's the reference: https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/3efbabeb-ccc7-44c1-b7ed-f4c8e56844ec/help-with-scardconnect-for-vista-64-bit?forum=windowssecurity
ReplyDeletehttps://social.msdn.microsoft.com/Forums/getfile/1037537
I can share the complete code of converted reader.
Have tested with X86 and X64 both
Shall be mailing the code to the author as well.
Please, send me the code x64
Delete