Mifare Desfire communication example

MiFare DESFire are iso14443A compliant contactless smartcards, and support all layers including iso14443-4. These cards are so-called “stored value” cards, so you cannot install and execute your own program code on DESFire cards. DESFire is like a memory card with access control.

Typical usage is within public transportation and access control.

DESFire cards are considered secure. Even though there are some theoretical security flaws, no public working hack has been published like there has been for Mifare classic (standard) cards. (The new DESFire EV1 cards are supposed to address the flaws found in v0.6).

Depending on the version of the card, a DESFire card might support commands in native, native-wrapped or iso7816-4 command set styles.

  • Software version v0.4 does not support APDU (only native commands)
  • v0.5 adds support for wrapping native commands inside ISO 7816 style APDUs
  • v0.6 adds ISO/IEC 7816 command set compatibility. 

 New versions of DESFire cards (EV1) (v1.3) support extended APDU commands.

“Application” in DESFire terms is more like a DF (Directory File) in iso7816. DESFire AIDs (Application IDs) are 3 bytes long.

The command style of the first command determines the mode for the rest of the session. You cannot mix different command modes in the same session.

First, lets look at Native command mode.

Native Command mode:

Most of these commands are one byte long, and the card responds with “statusbyte + [optional data]”

Statusbyte examples:
00 : Command successful
af : More data (send command 'af' to fetch remaining data)
9d : Permission Denied
Communication flow:
--> To card
<-- From card

Example using a blank DESFire v0.6 card:

Get Version:
--> 60
<-- af 04 01 01 00 02 18 05
--> af
<-- af 04 01 01 00 06 18 05
--> af
<-- 00 XX XX XX XX XX XX XX ZZ ZZ ZZ ZZ ZZ 05 06

The first response denotes the hardware releated data: version is 0.2 (00 02), and storage size is 18 (4096 bytes)
The second response denotes the software releated data: version is 0.6 (00 06), and storage size is 18 (4096 bytes)
The X’s are the 7-byte UID
The Z’s are the 5-byte batch number
05 = Calendar week of production
06 = Production year

Get Application IDs:
--> 6a
<-- 00

No applications available (blank card)

Select PICC Application:
--> 5a 00 00 00
<-- 00

OK

Get File IDs (for PICC Application):
--> 6f
<-- 9d

Permission denied.

Get Key Settings (for PICC Application):
--> 45
<-- 00 0f 01

0f = All bits in the lower nibble are set, meaning configuration can be changed, CreateApplication/GetApplicationIDs/GetKeySettings can be performed without master key, and master key is changeable
01 = Only 1 key can exist for this application (the PICC application)

Get Key Version for key 00 (for PICC Application):
--> 64 00
<-- 00 00

The PICC master key version is 0x00

Authentication with key 00 (for PICC Application):
--> 0a 00
<-- af a2 be cd 03 d8 46 cb 33
--> af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c
<-- 00 76 73 d9 49 71 3f f2 d1

This example only showed authentication with the PICC application. In a real world transaction, you would typicall select a specific AID (!= 00 00 00), authenticate, and then read/write to files within that application.

After a successful authentication, further communication with the card is done in plain/plain+MAC/encrypted+MAC, depending on the access bits for the particular file.
Authentication is done using DES or Triple-DES, depending on keysize. If key is 8 bytes: Single DES. If key is 16 bytes, and the first 8 bytes of the key are different from the last 8 bytes: Triple-DES. The card terminal (PCD) always use DECRYPT_MODE (both when recieving and sending encrypted data), and the card always uses ENCRYPT_MODE. However, the DESFire crypto is a bit different from the normal DES/CBC scheme: The PCD uses DES “send mode” when sending data (xor before DES), and the card uses DES “recieve mode” when recieving data (xor after DES). But when the PCD recieves data, it uses normal DES/CBC mode (xor after DES), and the card uses normal DES send mode when sending data (xor before DES).

DESFire encryption:
Send encrypted data Recieve encrypted data
PCD (DECRYPT) DES/CBC “send mode” Normal DES/CBC “recieve mode”
Card (ENCRYPT) Normal DES/CBC “send mode” DES/CBC “recieve mode”

The last 2 modes are useful if you need to communicate with a DESFire card through PC/SC, or you need to emulate DESFire on Java Cards.

Native Wrapped command style:

In this mode, native commands are wrapped inside iso7816 style APDUs.

The mapping is done as follows:
cls ins          p1 p2 lc [data] le
90  [native ins] 00 00 lc [data] 00

SW1 SW2
91  [native status code]
Wrapped version of the commands shown above:
--> 90 60 00 00 00 00
<-- 04 01 01 00 02 18 05 91 af
--> 90 af 00 00 00 00
<-- 04 01 01 00 06 18 05 91 af
--> 90 af 00 00 00 00
<-- 04 28 3b 61 5b 1b 80 8e 64 55 61 10 05 06 91 00
--> 90 6a 00 00 00 00
<-- 91 00
--> 90 5a 00 00 03 00 00 00 00
<-- 91 00
--> 90 6f 00 00 00 00
<-- 91 9d
--> 90 45 00 00 00 00
<-- 0f 01 91 00
--> 90 64 00 00 01 00 00
<-- 00 91 00
--> 90 0a 00 00 01 00 00
<-- a2 be cd 03 d8 46 cb 33 91 af
--> 90 af 00 00 10 b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c 00
<-- 76 73 d9 49 71 3f f2 d1 91 00

The last mode is the iso7816 command set mode:

Full support for these commands require DESFire v1.3 (EV1)
ISO SELECT (A4)
ISO GET CHALLENGE (84)
ISO EXTERNAL AUTHENTICATE (82)
ISO INTERNAL AUTHENTICATE (88)
ISO READ BINARY (B0)
ISO UPDATE BINARY (D6)
INS READ RECORDS (B2)
ISO APPEND RECORD (E2)

As you can see, not all functions are available using the iso7816 command set. If you need more functions, you must use native or native-wrapped mode.


949 responses to “Mifare Desfire communication example

  • Jacek

    Hello.
    Nice example but I’m not able to do any autentication with Desfire card.
    I was trying to authenticate accordingly to nxp documentation but still get 0xAE error ( authentication failed ).
    Looking at Your example above ( I guesss You utilized master PICC transport key which value as I know is equal 0 or better all bytes are 0’es )
    I was trying to forget about the card 🙂 and I assumed card responded on command “authenticate” ( 0x0A ) like in Your example “af a2 be cd 03 d8 46 cb 33”. So utilizing only autentication procedure and mentioned key value I should get APDU frame to card like in Your example again:

    af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c

    Unfortunately , I’m not able to achieve the same result. Could You describe me step by step operations that led You to above APDU frame ?

    Regards
    Jacek

    • ridrix

      Hi,

      Yes I used default DESFire key with all ‘0’s.

      The auth starts with host sending 0x0A + keyNumber to card.

      Card responds with 0xAF + encrypted RANDOM_B (8 bytes)

      Host DECRYPTS RANDOM_B using normal DES CBC recieve mode.

      Host then creates new array ARRAY2 (length 16), and copies its own random data (RANDOM_A) to bytes 0-7.

      Bytes 8-15 are the decrypted RANDOM_B, but with a 1 byte left shift. So ARRAY2[15] = RANDOM_B[0]

      ARRAY2 is then DECRYPTED using CBC SEND mode (not a normal CBC mode, and you will probably not find a standard library that does this for you. You may have to implement this CBC mode yourself using Single DES + xor).

      Host then sends the decypted ARRAY2 to card: 0xAF + decrypted ARRAY2.

      Card ENCRYPTS ARRAY2, and if RANDOM_B is correct (after a 1 byte right shift), it then does a 1 byte left shift of RANDOM_A, and ENCRYPTS the result using normal CBC Send mode.

      Card then responds with 0x00 (auth ok) + encrypted RANDOM_A (after 1 byte left shift).

      Host then DECRYPTS the response using normal CBC recieve mode, and checks RANDOM_A (remember 1 byte right shift).

      Auth finished.

      Let me know if it works 🙂

      Ridrix

      • Jacek

        Thanks for fast response.
        What exactly means xor operation here ? Xor given buffer with what ?
        1) Itself – byte after byte ( ARRAY2[0] = ARRAY2[0]^ARRAY2[0], ARRAY2[1] = ARRAY2[1] ^ ARRAY2[1] and so on) .
        2) With given number ? – All bytes xor’ed with 0xFF for example , so ARRAY2[0] = ARRAY2[0] ^ 0xFF, ARRAY2[1] = ARRAY2[1]^0xFF and so on.

        Regards
        Jacek

      • ridrix

        Sorry, a little typo there, I meant you have to implement CBC mode yourself using _Triple_DES + xor.

        XOR is a part of the CBC mode. See here how CBC works:

        (The XOR operation is of course the circle with the cross inside.)

        The CBC mode in this picture is the normal CBC send mode (as done by the card when sending data to host).
        When receiving data, the card does the xor operation AFTER the “Block Cipher Encryption” step (but still using DES ENCRYPT).
        Note that the card ALWAYS uses DES ENCRYPT mode (both when recieving and sending data). And the host ALWAYS uses DECRYPT mode.

      • Jacek

        So , as I understood this modified 3DES CBC decryption it is 3DES CBC decryption but with schema as for encryption. In other words, in first step
        I xor iv with first 8 bytes of cryptogram ( for encryption schema it is first 8 bytes of text ) and do 3DES decryption. In next step, previously 8 decrypted bytes I xor ( it is new iv ) with next 8 bytes of cryptogram and do next 3DES decryption.

      • Jacek

        Uffff… Now it works for 0x0A for Your sample above. Now real card….

      • Alexey

        Still fighting with CBC mode using _Triple_DES + xor.


        RNDA and RNDB is combined. -> 16 bytes

        What should be XOR and with what?

        In java

        byte keyBits[] = new byte[]{ (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00 };

        Cipher c = null;

        IvParameterSpec iv= new IvParameterSpec( new byte[]{ (byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00,(byte)0×00, (byte)0×00, (byte)0×00, (byte)0×00 }, 0, 8 );

        SecretKeySpec sks = new SecretKeySpec( keyBits, 0, keyBits.length, “DES” );

        c.init( Cipher.DECRYPT_MODE, sks, iv);
        c.doFinal(combinedArray, 0, tempSource.length, result, 0 );

      • Alexey

        Also cipher algorithm is

        c = Cipher.getInstance( “DES/CBC/NoPadding” );

      • bala

        Hi Ridix,

        Could you please send me the “3des source code in C” if possible.
        I have an algo. which gives decrypted output {0x39,0x34,0x51,0x2a,0xb2,0x3d,0x55,0x05}for input{0xa2,0xbe,0xcd,0x03,0xd8,0x46,0xcb,0x33}.

        Please check.

        Thanks,
        Bala.

      • akdrmrk

        Hi ;
        I created an application with ‘CA3333330F0A’ …Then I sent 90-0A-00-01-00-00 (begin authentication procedure)…
        it responsed me 1D-A4-56-2E-78-43-F6-CB (encrypted rndB)
        Now I should Decrypt and build Rondom B..
        I am sending to picc 1D-A4-56-2E-78-43-F6-CB (encrypted rndB), it returned 67 00..it is wrong way.
        How can I decrypt rndB?

    • ridrix

      Oh, and I forgot, the Initialization Vector to the CBC is all ‘0’s. (Which, by the way, is a possible security flaw).

  • Baron

    Hi can you please help me on How can I communicate with DESFire using the other type of commands. I have successfully done it using this type of commands. But I am having a hard time using the commands with the

    cls ins p1 p2 lc [data] le
    90 [native ins] 00 00 lc [data] 00

    SW1 SW2
    91 [native status code]

    I dont know what to put in the instruction code and the p1 p2 area.

    I have two different readers Omnikey 5121 and Omnikey 5321. The 5121 doesn’t accept Native commands.

    Help will be appreciated.

    Thanks

    • Jacek

      Hello Baron.
      I utilize Omnikey CardMan 5121.
      It works without problems in ISO7816-4 mode. What problems You have with it ? As mentioned in documentation P1 and P2 are always 0.
      LE = 0 must be at the end of APDU frame.

      Jacek

  • Jacek

    To avoid further misunderstandings, all DES oparations in 0x0A autentications are 3DES operations ?

    • ridrix

      Weither the operation is 3DES or singleDES depends on the size and format of the key. But it’s better to always use the 3DES algorithm, because that will work both as 3DES and SingleDES, and a 3DES operation is usually pretty fast anyway. For example: If your key is 16 bytes, and the first 8 bytes are equal to the last 8 bytes, then the effecive encryption will be single DES, even if you are using 3DES. 3DES is Single DES done 3 times: ENCRYPTION (using key bytes 1-8), DECRYPTION (using key bytes 9-16), and ENCRYPTION (using key bytes 17-24). So use 3DES and create code to “expand” the key. Let’s say your 3DES algorithm wants 24 byte keys: if the key is 8 bytes, then repeat these 8 bytes 2 times (SingleDES). If the keys is 16 bytes, then copy the first 8 bytes into bytes 17-24.

  • yasar

    Hello,

    I’m working on a project and i have to use mifare desfire but i don’t know anything and i couldn’t find any information about communication.

    Can you give me document about how can i communication it.

    thanks

    • ridrix

      Hi,
      To obtain the desfire documentation you will have to contact NXP. You will most likely have to sign NDAs (None Disclosure Agreements). I don’t have any documentation I can give away unfortunately. I haven’t signed any NDAs with NXP. All the information you can find in this blog is collected from other blogs and forums on the internet. What do you mean by “how can i communicate with it”? Do you have a card reader and know how to program against PC/SC? Make sure you have a contactless smartcard reader, like the Omnikey Cardman 5321 or similar which supports the PC/SC standard. Then write an application in C/Java (or other preferred language that has PC/SC bindings), and use the “native wrapped mode” or “ISO command set mode” to communicate with your Desfire card.

  • Jacek

    Hello again.
    A lot of work I have done with Desfire card so far but now but in front of me many serious problems concerned with secure messaging as always 🙂
    First task – key changing
    I created application with 5 3DES key on “good day”. Accordingly to documentation they should have 0’es values. Chnage mode to the keys I set in that way , key changing is possible if old key with the same number will be authenticated.
    After application selection, I was trying to change key 1. Before operation I authenticated succesfully with old key 1 and in further step I issued “Change key” APDU sequence. Unfortunately , error 0x1E appeared.
    What could went wrong ?
    1) Autentication was succesfull so I assume session 3DES key I calculated ok
    2) Myabe CRC16 ? I found different ways of calculating it even with the same generator. Could anybody confirm that CRC16 for 16 bytes, each of 0 value ( default value of old 3DES key ) , is equal 0xAFA9 ?
    I put it 0xA9 0xAF in APDU buffer LSB MSB. Correct ?
    3) 3DES calculation of data. It is normal 3DES encryption in CBC mode with IV = 0 ? ( data to be encrypted is “new key” || CRC16 || 0’s padding until 24 bytes )

    Any suggestions ?

    Regards
    Jacek

  • Rob

    Hi, This has been a very useful article, thanks for publishing it.

    I am looking at DESFire EV1, but cannot get a list of the command codes to use for the following functions.

    Authenticate
    Change KeySettings
    Set Configuration
    Change Key
    Get KeyVersion
    Create Application
    Delete Application
    Get Applications IDs
    Free Memory
    GetDFNames
    Get KeySettings
    Select Application
    FormatPICC
    Get Version
    GetCardUID
    Get FileIDs
    Get FileSettings
    Change FileSettings
    Create StdDataFile
    Create
    BackupDataFile
    Create ValueFile
    Create
    LinearRecordFile
    Create
    CyclicRecordFile
    DeleteFile
    Read Data
    Write Data
    Get Value
    Credit
    Debit
    Limited Credit
    Write Record
    Read Records
    Clear RecordFile
    Commit Transaction
    Abort Transaction

    Do you have any links or other documentation I can read to help with this. I have tried NXP several times but they don’t respond!

    Many thanks in anticipation 😉

    • ridrix

      I don’t have any document that describes all the commands unfortunately. I think such documents are only available under NDA’s. However, you can find many of the DESFire commands in the Nokia proprietary extension classes in the 6212 Java SDK. This SDK is free, but you need to register to download. Registration is of course also free.

      http://www.forum.nokia.com/info/sw.nokia.com/id/5bcaee40-d2b2-4595-b5b5-4833d6a4cda1/S40_Nokia_6212_NFC_SDK.html

      Install SDK and add to for example Netbeans.

      Look in the package “com.nokia.nfc.nxp.desfire”.

      These classes contain utility methods that help you construct native DESFire commands. I think most of the commands are described there.

      • srinath2

        Hi Ridrix,

        I tried accessing the SDK but was not able to ,
        I am trying to Develop an Desktop application which requires Reading of an Desfire Card. is there any other SDK Kindly Let me Know

  • Héctor Nebot

    Hello,

    I’m developing an application for a mifare DESFIRE card and a portable terminal from Ingenico (EFT930G Contactless).

    I have done tests with SAM communications without problems (activating, selecting app, presenting the PIN…), I have also sent different commands to the card with good results: GetVersion (in order to get the card UID), GetApplicationIDs, SelectApplication…

    My problem has appear when I’m trying to carry out the authentication process in order to get the session key.

    I follow the first steps, but when I send the Authenticate Command to the card (with KeyID 0x01): 0x90, 0x0A, 0x00, 0x00, 0x01, 0x11, 0x00 the cards returns only 3 bytes, instead of 8.

    I have tried many different things, as sending Additional Frame command (0x90, 0xAF, 0x00, 0x00, 0x00) in order to get the rest of the of the bytes, but the card always returns me the Command Aborted message: 91 CA

    Please, can you help me with this issue?

    Thank you very much in advance.

    • freeds

      This is beacause the length of card response is set to 3 bytes instead of 8. check this parameter.

      • Héctor Nebot

        Thank you freeds,

        It was exactly this issue…it wasn’t set to 3 bytes (null value) but it must be 8 😀

  • Jafer

    hi ridrix
    i develope an application for Desfire card. the authentication with card is successfull and I can generate the session key.
    bt I have a problem. How we can specify a key (rather than application master key) in the selected AID. osuppose that I want to set the value of key 1 to 0x00 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x00 0x11 0x22 0x33 0x44 0x55 0x66 0x77. and then set the access right of a data file to authenticated with this key. my question is general . how and when we can specify the application user file?
    thanks in advance
    Jafer

    • Praveen TV

      hi ridix,
      I have created a application with 2 keys. with crypto mode Desfire Native. I need to change key for key entry 1 in the application. Since I have created application with change key access rights with 0x0E I need to authenticate with same key. The authentication is success and session key is generated, but later change key gives me an error 0x1E. I have calculated a CRC16 and appended to data frame and appended 00’s to make it multiple of 8. can anyone help me on this?

  • Newbie

    Hi, I am a newbie and I am trying to communicate with a DESFire card using an OMNIKey 5321 reader on VB6. I am able to follow all the communication samples and I am also able to do authentication. I request assistance on how to create an application on a new card and subsequently write and read standard files into the application created. Any assistance will be greatly appreciated. Thanks.

  • Lara

    Hi guys.
    I’ve a problem with desfire EV1 cards. I can send basic commands in ISO7816 wrapping mode such as GetVersion, Select Card Level and Authenticate by default TDES card level key (all ‘0’). After that I’ve correctly generated the session key, I would to set an UID random by the setConfiguration command. Now, I don’t know on which data the CRC32 is evalued. In fac, following commands give me 811E error:
    90 5c 00 00 09 00 Ek(02 CRC32(90 5c 00 00 02) 00 00 00) 00.
    The result doesn’t change if I use CRC32(5c 00 02) or CRC32(all command). Help me, please!!

  • bluecard

    Hi Ridrix,
    Excellent examples 🙂

    I am new one in the card development. and start working on desfire native mode using omnikey reader. Need some guides in change key command.

    Here is my log
    ->CA 20 20 20 0F 0E( CREATE APPLICATION HAVING ID=202020 )
    5A 20 20 20
    0A 02
    AF F8 07 5D C3 EA F3 CD 7C 68 2D F6 46 44 FF 34 6D
    >0101020203030404
    RANDOM B>>6B4B5908F93AA1E4
    SESSION KEY>>010102026B4B590803030404F93AA1E4

    String oldKey = “00000000000000000000000000000000”;
    String newKey = “00112233445566778899aabbccddeeff”;

    -> C4 02 DF 90 2F 3D 84 89 2D B9 13 20 EC 9D 98 F3 A6 47 B2 0E 71 B9 09 F0 29 69
    <- AE

    Need your guides in change key command

    Hope this finds you all in the best of Good days and good luck.

    Thank you
    cheers

  • Rob

    Hi,
    Looks like the CRC calculation is a problem. I have tried several versions with no success. I am fairly confident that the rest of the ChangeKey code is correct.

    Can anyone with a known to be working CRC16 routine for DESFire supply a CRC16 value for the following example: AABBCCDDEE001122

    Many thanks.

    • Adam Laurie

      desfire uses iso14443a crc16 – here’s the python implementation i use:

      
      def crc16_iso14443a(data):
              crc= 0x6363
              return crc16_iso14443ab(data, crc, 0x8408, False)
      
      def crc16_iso14443b(data):
              crc= 0xffff
              return crc16_iso14443ab(data, crc, 0x8408, True)
      
      def crc16_iso14443ab(data, crc, polynomial, invert):
              for byte in data:
                      crc= crc ^ byte
                      for bit in range(8):
                              if crc & 0x0001:
                                      crc= (crc >> 1) ^ polynomial
                              else:
                                      crc= crc >> 1
              crclow= crc & 0xff
              crchigh= (crc >> 8) & 0xff
              if invert:
                      crclow= 256 + ~crclow
                      crchigh= 256 + ~crchigh
              return [crclow, crchigh]
      
      • PeaceMaker

        Hi Adam Laurie?

        Do you have the CRC16 implementation in Java and C++? 🙂
        I have already tested the implementation in Java, but why the result is different?..
        Could you help me regarding this?

        Thx

      • Adam Laurie

        I don’t have a Java implementation, but here’s one in C:

        
        
        unsigned short crc_16(unsigned char *data, unsigned int len)
        {
                unsigned int i;
                unsigned short crc= 0x6363;
        
                for(i= 0; i < len ; ++i)
                        crc=  update_crc16(crc, data[i]);
                return crc;
        }
        
        unsigned short update_crc16(unsigned short crc, unsigned char c)   
        {
                unsigned short i, v, tcrc = 0;
        
                v = (crc ^ c) & 0xff;
                for (i = 0; i > 1 ) ^ 0x8408 : tcrc >> 1;
                        v >>= 1;
                        }
                return ((crc >> 8) ^ tcrc) & 0xffff;
        }
        
        

        and BTW, the correct answer for the original example (AABBCCDDEE001122) is 7B09, so you need to be careful to use the correct byte order when passing on the short returned by this version.

      • Adam Laurie

        Hmmm… Something went horribly wring with cut & paste there!

        
        unsigned short crc_16(unsigned char *data, unsigned int len)
        {
                unsigned int i;
                unsigned short crc= 0x6363;
        
                for(i= 0; i < len ; ++i)
                        crc=  update_crc16(crc, data[i]);
                return crc;
        }
        
        unsigned short update_crc16(unsigned short crc, unsigned char c)
        {
                unsigned short i, v, tcrc = 0;
        
                v = (crc ^ c) & 0xff;
                for (i = 0; i > 1 ) ^ 0x8408 : tcrc >> 1;
                        v >>= 1;
                        }
                return ((crc >> 8) ^ tcrc) & 0xffff;
        }
        
      • Adam Laurie

        OK, so it;s not cut & paste but something in wordpress that’s screwing it up…

        Function is here:

        http://www.rfidiot.org/crc16.c

      • PeaceMaker

        Hi Adam Laurie

        Thanks for the CRC16 in C implementation..
        It works great!!.. 🙂
        But unfortunately, i’m still looking for CRC16 in Java implementation, and i’m still facing problem when convert it to Java.. 😦

        Anyway, thanks for the example..

  • Mansour

    hi Ridrix,
    i have a Desfire MF3ICD41 card and wrote a C# program for authenticate with it; the default key is 0000000000000000
    but i can’t authenticate with this card
    may you give some test vector for my authenticate module (i sure that’s work correctly but i can’t authenticate yet)
    please help me
    regards

  • Elfina

    Hi Ridrix
    I am trying to create files and read and write those files.
    I succeed with the Data files, but with the record file I am receiving error “0xBE”.
    I’m creating record file and can write the record file. On the Read Record command I’m receiving this error.
    Command I send:”bb 07 01 00 00 03 00 00″ – as I understand it’s file 7 from read 3 ercords starting from record 1. This file have 3 records.
    What is wrong here?
    regards

  • Elfina

    I have one more question.
    I can’t create value file. I receive error code 9E (parameter error).
    command that I send:cc 01 00 42 f0 00 00 00 00 99 99 99 99 00 00 00 01 01

    Thanks you

  • Ande

    Has anyone read and decrypted a key from ANY Mifare DESFire cards?
    Specifically public transit systems?

  • Lara

    Hi, guys.
    I’ve a question for you. I’m using nokia 6212 in order to read a DESFire EV1 card personalized in ISO7816 wrapping mode; but I’ve some problem because the phone doesn’t detect the card. I use this code in targetDetected method:

    if (classes[i].equals(Class.forName(“com.nokia.nfc.nxp.desfire.DESFireConnection”))) {
    String url = target.getUrl(classes[i]);
    conn = (ISO14443Connection)Connector.open(url);
    The method Connector.open(url) is not capable to establish a connection. In case of APDU commands native, I thing the connection work. In other words, I think that is not possible to use the specific features of Ev1 chip, that is AES authentication, UID random and ATS configurable. Is it so? If not, how can I connect my 6212 phone to the chip Ev1 card in order to use the EV1 features?
    Thank you in advance.

  • Lara

    Hi!
    I’ve found that the nokia 6212 cannot open connection only if the uid of desfire ev1 card is set to “uid random”; when I use a desfire ev1 card with uid in plain, the connection is ok. Now, I think the problem is of phone because the uid random not change after the RF-reset but then I don’t know why connection fails. Have you some idea?

  • Vaishali

    Hi all
    Iam new into card development.
    I have dis Mifare 1K card.
    iam able to get the UID but cannot get the authentication done.
    I am trying read and write from the sectors but without authentication
    it gives me 69 82 as response.
    please help me
    regards

    • Elfina

      Hi Vaishali, This error means security status not satisfied.
      You should first select application on the SAM and on the PICC, then authenticate this application, and only when applications will be authenticated you will be able to read and write records.
      Try to authenticate with master key 0.

  • Slalen

    Hi Ridix and another one!!

    Thanks for your web!!

    I have a question about the authentication. In the cbc encryption the Plaintext is the random numbers, the key is the codification key (0s in your example), but what is the initialization vector??

    Thanks!

  • Gorka

    Hi,

    I am trying to change the keyno 1 of my application but I get a 911E error, what means that CRC or padding must be wrong. I can authenticate to the master key and get the session key. Here I post the output of my program.

    Session Key: D8 15 60 CE 33 55 7D BC 3E F4 34 EA 1D FF F9 28
    Old Key: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    New Key: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF

    Key Data: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 69 CC 69 CC 00 00 00 00
    Transmitted data: 71 66 0B 4C C6 EB A6 F9 D6 36 86 2F 6A ED 33 E5 D9 84 50 B0 04 6B A9 85

    I Hope someone can help me.

    • Mustafa Moripek

      The session key is wrong.You have to authenticate with the old key.The first eight bytes are equal to the second half , therefore you have to build
      the session key in the same way.The first half of the session key must be
      equal to the second half.

      • Gorka

        Hi,

        Thanks for your response.
        So, what you mean is that if the random numbers are: D8 15 60 CE 3E F4 34 EA – 33 55 7D BC 1D FF F9 28, the key I have to use is: D8 15 60 CE 33 55 7D BC D8 15 60 CE 33 55 7D BC ???

        Bye.

      • Gorka

        Hi again,

        I have a similar problem trying to send encrypted data, so I think that maybe the problem is not in the key, but in the way I encrypt the data when the data is more than 8 bytes.

        For example if I try to write 00 01 02 03 04 05 I send the next command and everything is fine:
        90 3D 0000 0F 06 000000 060000 + Encrypt(00 01 02 03 04 05 28 da) + 00 –> OK
        But if I try to write more bytes it doesn´t work.
        90 3D 0000 17 06 000000 0c0000 + Encrypt(00 01 02 03 00 01 02 03 00 01 02 03 62 20 00 00) + 00 –> FAIL

        Here is a log:
        Data: 00 01 02 03 00 01 02 03 00 01 02 03 62 20 00 00
        Session Key: 43 D8 9D 37 3F 0F E1 BC
        APDU: 90 3D 00 00 17 06 00 00 00 0C 00 00 3F 40 08 FC 1D 60 5D C8 B4 30 71 1D 03 E1 57 11 00

        Does anyone know why fails when I try to write more than 8 bytes??

        Thanks again.

    • Ali

      Hi Gorka,
      Would you mind tell me how attain CC 69 for your data please?
      it is so imprtant for me too find how crc 00 11 22 33 44 55 66 77 88 99 AA bb cc dd ee ff == cc 69

  • bluecard

    Hi,
    Can any one have the CRC32 implementation in Java or C++?

    Thank you,

  • DESFire

    Hello:
    How to know the version of a DESFire card? (any Command?)

    Thanks~

  • selzeda

    Hey,

    I implemented almost the whole DESFire-spec in java and everything works fine (i.e. authentication with aes/des, create/delete aid, create/delete fids, write standard files) but I’m not able to change a key on application level. I’m creating an aid, a fid, standard file and write some bytes into it. Everything with standard key (i.e. 0x00…). Reading out the file does work also.

    Now I implemented a changeKey-method which should work but always gives me 0x1E, i.e. “INTEGRITY_ERROR”. I’m using the standard java crc32 implementation. Authentication ist 0xAA, i.e. aes. But I also get 0x1E if I “corrupt” bytes of the ciphered key data block, so I’m not sure if my crc32 is not correct or the parameters are in the wrong order. According to the spec, its encrypt(aesKey(16), keyVersion(1), CRC32(4), padding(11)), right? Does java.util.zip.crc32 produce the correct crc? The exponents etc. should be correct, I even tried to XOR the bytes with 0xFF…

    Any hints on this one? Thanks a lot!

    • Meph

      Hello,

      i’m developing a java application and i want to read files from a desfire ev1 card with AES protection. I began to reconstruct the way of authetification from the nxp application notes. i succesfuly can generate the reply from pcd (to picc’s) to the command 0x90 0xAA. Only problem is after i send (0x90 0xAF 0x00 0x00 0x32….) i get a IllegalArgumentException with “invalid apdu: length=38, b1=50”. In NXP documentation i read that length of command could be up to 64byte, so i think thats enough.
      Thanks a lot for any help. And sorry for my english. If someone prefers german answer on my question thats no problem;)

      • Meph

        OK, i think i need a brake. only problem was 0x32 is not the same as 32 (int).0x20 in stead of 0x32 works perfectly;)

    • George

      Dear selzeda,
      If you would kindly share or send me the desfire library you created in JAVA, that would be a greatly appreciated help. szgeri@gmail.com
      Thank you, George

    • Miha

      Hello,

      I’m also trying to use java to write and read desfire ev1 cards, is it possible for you to share library with me?
      email:insaniae@gmail.com

  • bluecard

    Hi,
    Can any one have the CRC32 implementation in Java according to Mifare Desfire specification

    Thank you,

    • Gorka

      Hi,

      You just have to copy the crc32_table and then create a new method where the crc is calculated:

      public byte[] crc32(byte[] d) {
      long temp;
      long oldcrc=0xffffffff;

      for(int i = 0; i > 8) & 0x00FFFFFF) ^ crc32_table[(int) temp];
      }

      byte [] b = new byte[4];
      for(int i= 0; i >> (i * 8));

      return b;
      }

      • Gorka

        Arggg,

        It seems there is a problem when trying to copy the code. Here is the code again. If it does not appear correctly please post your email and I will send you.

        long len = data.length;
        for(int i = 0; i > 8) & 0x00FFFFFF) ^ crc32_table[(int) temp];

        }

        byte [] b = new byte[4];
        for(int i= 0; i >> (i * 8));
        }

  • Gorka

    Hi,

    I have been reading the Ev1 specification but I cannot undestand how the IV management works.

    In the beginning we have Iv=0x00 … 0x00. Then we send something and the CMAC value gets a value, for example IV=0011223344556677. So how can I get the second part of the IV and get the new value IV=11223344556677XXXXXXXXXXXXXX ??????????

    Thanks

    • Keeper

      Hi Gorka,

      having the same issue… Did you find a solution of how to calculate the second part of the IV?
      I’m also having trouble calculation the AES CMAC, but that’s a different story…

      Thanks!

  • bluecard

    Hi,
    i am facing problem in changing card master key to AES.
    Raw Text >>
    000000000000000000000000000000000075450000000000
    after native enciphering>>
    91EC5552B50A73630000000000000000E97E894656A9F0F4(incorrect)

    Can any explain desfire native TDES MODE enciphering for change master key case2?

    My session key =b954afcbcf8c4e95b954afcbcf8c4e95b954afcbcf8c4e95

    Thanks.

  • c t skinner

    with an omnikey 5321 I get
    DESFire ATR 3B8180018080
    UID 04 52 2E AA 47 23 80 90 00 [from apdu FFCA000000]
    All other apdu give 917E unknown error

    • Gorka

      Hi,

      I don´t know what you are sending to your DESFire card, but the 917E means that:

      0x7E LENGTH_ERROR Length of command string invalid

      So, take a look at the length you are indicating in your commands because it mus be wrong.

      Hope this helps.

      Bye.

    • c t skinner

      most apdu now working
      but NOT ChangeKey <<<<<<<<<<<<<
      which differs according to Native|Standard
      may have iv pre-decrypt?
      may require version ?
      for key0 all zeros Session key 1sthalf=2ndhalf?
      Standard uses crc32?
      tried all, no changekey
      working: MakeAID, read,write, even format works!
      (I have a lot of test cards to play with!)

  • Anum

    Hi to all,
    I’m new to the smartcard Desfire programming.
    Following the samples in the forum I was able to get the UID of the desfire card, but no success in the nex steps. Basically I wanna do:
    1) Create application (other than 000000)
    2) Set a new Key to the application( use application level keys, not the master PICC)
    3) Create a new file within the application
    4) Being able to read the app/file created in the 1~3.
    Can some body provide a source code in c/c++, so I can see how it is done?
    Thank you in advance and any help is very welcome.

  • Bruno Bertechini

    Gorka

    I am facing exactly same error mentioned in one of yours previous message (msg at the end).

    I can successfully authenticate and create the session key. But I am not able to change PICC MASTER KEY.

    Already tried Mustafa suggestion to use sessionkey with first 8 bytes equals to last 8 bytes. Same result (91 1E).

    No idea what is the correct process to be able to debug/resolve this issue.

    Have you been able to figure this out? If so, what was the problem?

    Thank you ver very much!

    I will post a new msg with the complete APDU log for my communication.

    Thanks

    Bruno

    Slightly difference from your code is regarding the CRC16. I am appending only 2 bytes after the new key. And you are appending twice. Any problem with this? What is the correct way?

    “##BEGIN##”

    Gorka Says:
    December 15, 2010 at 17:24

    Hi,

    I am trying to change the keyno 1 of my application but I get a 911E error, what means that CRC or padding must be wrong. I can authenticate to the master key and get the session key. Here I post the output of my program.

    Session Key: D8 15 60 CE 33 55 7D BC 3E F4 34 EA 1D FF F9 28
    Old Key: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    New Key: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF

    Key Data: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 69 CC 69 CC 00 00 00 00
    Transmitted data: 71 66 0B 4C C6 EB A6 F9 D6 36 86 2F 6A ED 33 E5 D9 84 50 B0 04 6B A9 85

    I Hope someone can help me.

    “” END “”

    • Bruno Bertechini

      Following my previous post, here is the complete communication with desfire ev1 8k card:

      1. Select PICC App

      APDUCommmand: [9 bytes, LC=3, LE=256]
      –> 90 5A 00 00 03 00 00 00 00
      90 0A 00 00 01 00 00 (Authentication with Key 00 – Request Random Number)
      90 AF 00 00 10 22 95 75 18 68 13 46 31 44 8A 64 35 3F 15 06 BC 00
      90 C4 00 00 19 00 AA 6D E2 CF 80 01 63 53 C0 94 8B 88 8C A7 44 51 51 93 04 1A F5 21 C1 9E 00
      <– 91 1E [ERROR]

      INTEGRITY_ERROR – CRC or MAC does not match data – Padding bytes not valid

      The Error is the same as Gorka. No idea what to do to fix it. Can anybody help me with that?

      Thanks

      Bruno Bertechini

      • Bruno Bertechini

        Sorry , it seems like wordpress does not like copy & paste for big texts…

        Will split in few posts.

      • Bruno Bertechini

        ### POST 1 ###

        1. Select PICC App

        APDUCommmand: [9 bytes, LC=3, LE=256]
        –> 90 5A 00 00 03 00 00 00 00
        90 0A 00 00 01 00 00
        90 AF 00 00 10 22 95 75 18 68 13 46 31 44 8A 64 35 3F 15 06 BC 00
        <– 39 B4 6B 2B 05 45 3B 72 91 00

        At this point, the Card decipher RndB, execute a left shit and compare with its own RndB.
        If its okay, it decipher RndA, execute a left shit and cipher with same key (0x00).
        So, the response is RndA (left-shifted) ciphered by the card:

        RndA (left-shifted and ciphered) = 39 B4 6B 2B 05 45 3B 72

        2.6 The program (my program) decipher RndA using key 0x00 and execute a right shift

        RndA (deciphered) = 7B B7 CB F4 14 9F 01 07
        RndA (deciphered and right-shifted) = B7 CB F4 14 9F 01 07 7B

  • Mustafa Moripek

    1.When you build the session key you must take care that the first eight
    bytes are equal to the second byte.The reson is that the default key
    all zeroes also has the first eight bytes equal with the last eight
    bytes.
    2.When you send the new key you have to use CBC with single DES
    decryption.That Means: You have to exor the fisrt eight bytes of the
    new key with IV=00 00 00 00 00 00 00 00,than single DES decrypt the
    result(using the session key built like mentioned under point 1) and
    send it to PICC ,than exor this result with the second eight bytes of
    the new key and single DES decrypt it and send it to PICC, the
    result you have to exor with two bytes CRC with padding zeroes (six
    bytes) and single DES it and send it to the PICC.

    • Bruno Bertechini

      Hi Mustafa, Thanks for your response.

      For Point #1 thats okay. already changed the code to make 16 bytes key with 8 first bytes (RndA 1st half + RndB 2nd half) equals to last 8 bytes.

      For Point #2: What does that mean the exor? I am using a simple DES operation (decryption) on the new key. What do I need to do with the IV ?

      Bruno

      • Mustafa Moripek

        Hi Bruno,
        the reason is that DES decryption you can use on eight byte blocks only.When you change the key it is 16 bytes long plus you have to build CRC16 (two byts long) and you have to pad it to eight bytes with six zeroes.That means you have to send three blocks each eight bytes long to the PICC.To send three blocks you have to chain them (this method is called CBC chaining).
        For this operation you need to logical XOR the result of the
        plain data with the result of the foregoing decryption and then decrypt it (DES or 3 DES according key type).And at the first block you use the initial vector 00 00 00 00 00 00 00 00.

      • Gorka

        Hi Bruno,

        First of all, the key I had to change was the key #1 of my application. I tell you that because the CRC16 depends on the change you want to change. As you can read in the DESFire specification, it is not the same if the key you want to change is the one used in the authentication (that is your case since you are working with the master key) or it is another key from the keyset. In the first key you have to add only two CRC bytes and in the second one 4 bytes (I think it was that way, take a look at this point)

        The problem I used to have was on the encryption. I was not encrypting the data in the correct way (you know, all the xor before DES thing). Once I corrected that, it worked. If you don´t know what I mean try to send more than 8 bytes of data over an encrypted channel. If you can´t do that, you probable are not doing that ok.

        Good luck 🙂

        Gorka.

      • Bruno Bertechini

        Thank you guys.

        So, what exactly do I need to do now in order to change the master key from default (all 0s) to another key with 16bytes length to use 3DES.

        1. Build Session Key using only 8 bytes? or Build session key using 16 bytes with last 8 equals first 8 bytes?

        2. If it is 16 bytes DES key (with 1st half = 2nd half) do I need to do it in 3 steps right?

        Mustafa, sorry for my newbie questions, but can you pls show me in a step-by-step examples with real bytes to help me understand? Im real stucked on this issue.

        Gorka, I got what you said. My 1st goal here is to change the master key (to 3DES and later to AES). I have read on specs taht EV1 1.06 uses CMAC instead of CRC16. Is that correct?

        Also, when you say ” I tell you that because the CRC16 depends on the change you want to change”. What does that mean?

        Thanks for all your help guys!

        Bruno

    • c t skinner

      3 seperate sends of 90C4 with 8 bytes in each?
      I’ve been trying 1 send of 24 bytes…

      • ctskin

        na, the card doesnt like it, it wants 24 bytes of data in 1 go.
        I use key 0, keyvalue 0…0 version 0 so the order
        doesnt matter, tried w * w/out version
        keep getting that 911E

        required:
        [90C4 0000 19 data 00] where data is 24 decrypted bytes
        since the card knows not the new key it MUST be a crc problem ( i dont believe a MAC is required)

  • Mustafa Moripek

    OK Bruno,
    let mexplain more detailed.First of all the main thing is if the first half of the key you use is equal to the second half you use single DES for decryption.If the first half different from the second half you use triple DES for decryption.The first half of the default key all zeroes is practically equal to second half so you use single DES for decryption.Now assume your session key after successfully authentication is A4 24 63 B7 1C EC 85 0F (these are sample data and not real )and the key you want to use is : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F .
    The CRC16 for this key is 77 F5 .Now you have to send following blocks to the PICC :
    1. Block 00 01 02 03 04 05 06 07
    2. Block 08 09 0A 0B 0C 0D 0E 0F
    3. Block 77 F5 00 00 00 00 00 00
    When sending you have to chain them together using CBC rules.You have to build logical XOR byte for byte with 00 00 00 00 00 00 00 00.The
    result is the first block itself.This you have DES decrypt (single DES ,
    decrypt only once).Build the XOR with the result of it and second block
    (08 09 0A 0B 0C 0D 0E 0F).Then DES decrypt it (only once again).Build
    the XOR with the rsult and last block (77 F5 00 00 00 00 00 00) and
    Des decrypt it.Now you have to send thes data in the same sequence you
    build them to the PICC.

    • Bruno Bertechini

      Thanks Mustafa. Just one question. The session key must be single DES right? Should it be 8 bytes long or 16 bytes with first half equals second half?

    • Bruno Bertechini

      Mustafa, I just authenticated to the card to get a “real” session key and provide mor information to validate my code for Decrypt using CBC.

      After Authentication, I have the RandomA and RandomB (already validated with mutual auth).

      Here they are:

      RandomA = 9F CA 40 0F 3F AA 65 AC
      RandomB = 21 82 A9 52 D0 C9 64 02

      In order to change the master key from all 0s. What session key should be generated?

      1. DES Key (RndA 1st half + RndB 1st half)
      9F CA 40 0F D0 C9 64 02

      Is that correct?

      Need to figure this out first before go forward. I am also having problem to achieve the same CRC16 as you for the new key in your example (code is in C#). But I am forcing the CRC16 now and later on I will go through this.

      Can you pls confirm if this is the session key I need to use?

      Thanks!

      Bruno

  • Mustafa Moripek

    Bruno,
    you have written right thing (RndA 1st half + RndB 1st half) but
    you made wrong thing , the session key for single des decryption
    is : 9F CA 40 0F 21 82 A9 52.For building CRC don’t worry.There
    are many codes on internet.

    • Bruno Bertechini

      Thanks Mustafa. Realy typo in there.

      Okay, now I have the correct SessionKey. I will use for now the CRC16 as you mentioned and later on gather something from internet.

      Moving forward:

      Here I will get a new session key from the card and ask if you can help me to validate my single DES operations. I.E. I will send unenvrypted and encrypted data to check if you can get same results (to be able to validate my code).

      1. Session Key = 93 C1 93 5B 60 5A AE E2

      2. New Key Blocks =

      1. Block 00 01 02 03 04 05 06 07
      2. Block 08 09 0A 0B 0C 0D 0E 0F
      3. Block 77 F5 00 00 00 00 00 00

      3. Block1 XOR defaultKey (All 0s)
      xorB1 = 00 01 02 03 04 05 06 07

      4. Single DES Decrypt Operation using previous Session Key and IV = 0x00
      xorB1Decrypted = B1 D0 01 AC 14 A6 BF 0F
      Mustafa: Could you please validate this data? To make sure my “decrypt” process is okay?

      5. Result#4 XOR Block2
      xorB2 = B9 D9 0B A7 18 AB B1 00

      6. Single DES Decrypt Operation using previous Session Key and IV (here is another question — Should I use the IV generated in previous step #4 ? Or should I use the result data (xorB1Decrypted) as IV?)

      Here I am using the xorB1Decrypted as IV =
      xorB2Decrypted = 7D 51 A6 D2 A3 56 40 D7

      Same process for the 3rd block.

      I would like to confirm these steps to make sure I am doing it in the right way…

      Regards

      Bruno

  • Mustafa Moripek

    Sorry Bruno,
    I’am not in my office.Please write down the results of each step.Ican check them tomorrow and tell wether they are correct.

    • Bruno Bertechini

      This is what I have done for the ciphering process for block1 and block2

      Will try to send you a complete process using my own keys…

      Do you have an email/gtalk/msn or anything I cant get you in touch?

      Bruno

      P.S.: Many thanks in advance!

    • Bruno Bertechini

      If you could just validate what i’ve sent in previous post that will be great. There you have my session key and the operations results (which I need to match yours using my session key).

      Thanks a lot!

      Bruno

  • Mustafa Moripek

    Hi Bruno,
    I think there is something wrong with your DES code.Here the results with
    your data:
    Session Key : 93 C1 93 5B 60 5A AE E2
    New Key : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
    1.Block XOR IV : 00 01 02 03 04 05 06 07
    DES decrypted 1. Block : 9C 5F D6 AF 54 5B F3 CF
    Decr.1.Block XOR 2.Block : 94 56 DC A4 58 56 FD C0
    DES decrypted 2.Block : B4 75 3E 05 AA DD BF 14
    Decr.2.Block XOR 3.Block : C3 80 3E 05 AA DD BF 14
    Decr. 3.Block : F4 66 84 8B 21 0F CD C2

    • Bruno Bertechini

      Okay.

      That’s what I was afraid of. I am using C# standard DES Provider using CreateEncryptor to get the result.

      Will need to do some sort of research to achieve same results.

      Mustafa, thanks for your results…

      Regards

      Bruno

      P.S.: You are being able to change PICC master key for some card right?

      Again, This CRC16 code is only for ID 40 (not EV1). I will try to fix the DES part and later move to EV1 ID41 (Desfire EV1 4K) and ID81 (Desfire EV1 8k).

      Thank you very much!

      Bruno

    • Bruno Bertechini

      Mustafa, did you implement the DES code yourself or are you using some library?

      What language are you using?

      Bruno

    • Bruno Bertechini

      Mustafa thanks again.

      Previously you said: “Now you have to send thes data in the same sequence you
      build them to the PICC.”

      Based on the decrypted example (the last one) do I need to send one apdu to the card with 24bytes (the 3 blocks xor/decrypted) together ?

      Thanks

      Bruno

    • Bruno Bertechini

      Got it working and I am being able to achieve same results as yours. little more happy now 🙂

      But, still having problems to change the PICC master Key. Pls have a look:

      SessionKey
      [5E 9D 67 5D E3 9F DA 4D]

      Block1 : 00 01 02 03 04 05 06 07
      Block2 : 08 09 0A 0B 0C 0D 0E 0F
      Block3 : 77 F5 00 00 00 00 00 00

      R1 = Block1 XOR DefaultKey
      R2 = R1 Decrypted
      R3 = R2 XOR Block2
      R4 = R3 Decrypted
      R5 = R4 XOR Block3
      R6 = R5 Decrypted

      R1: 00 01 02 03 04 05 06 07
      R2: EA 69 9B 0F 14 10 F1 1E
      R3: E2 60 91 04 18 1D FF 11
      R4: A1 70 60 B2 D5 69 1A 52
      R5: D6 85 60 B2 D5 69 1A 52
      R6: BD 08 71 4B B4 05 D4 C0

      –> 90 CA 00 00 19 00 EA 69 9B 0F 14 10 F1 1E A1 70 60 B2 D5 69 1A 52 BD 08 71 4B B4 05 D4 C0 00
      <– 91 7E

      With the wrong DES operation I was getting 911E and now i am having 917E (Length Error).

      Do you have any idea on whats going on ?

      Are my DES/XOR operations above correct now?

      Thanks Again!

      Bruno

      • Zack

        Bruno,
        Hi, i am also working on a desfire cards in C# and am stuck on changing the keys, i have got the encryption stuff working so if i plug in this data i get the correct data out, however i still get a data integrity error. I am pretty sure i have generated the session key correctly, i took the first 4 bytes of the RND-A and appended the first 4 bytes of RND-B to them. However when i substitute in the ACTUAL session key i generated from authentication, it doesn’t work. The only difference i can think of is possibly the fact that i authenticated with the application using triple des instead of single des, while still attempting to use single des in the change key command. So i was wondering if when you got this working you authenticated with the application using triple des or single des.
        I tried authenticating using single des to rule out this possibility but i get an authentication failed error.
        Any help would be great, thanks
        Zack

      • Bruno

        Zack, I need to look over my code to get you this answer. Will try to reply that when I get back to the office…

        Regards

        Bruno
        P.S: What do you think about start writing an API in C# to handle DESFire cards?

      • Zack

        I would really like to, but unfortunatly i really don’t have time for any extra projects, and the code i will be merging this into is very “specialized” (read: old and horrible). maybe later on down the line though.

      • Bruno

        Zack, are you using DESFire or DESFire EV1 cards? Are you trying to authenticate or send/write some data to the card?

        I will send you a piece of code (working) from my demo solution.

        Bruno

      • Zack

        Hi, sorry took so long to reply, send the notification to the wrong bloody address. I have got authentication working, and i have been trying to do stuff like change the key settings and changing the actual key. To fit with the comments you were posting previously i am now testing with the changekey function. I have actually got the code to the point where if i plug in the data you were using i get the data you guys were saying was correct, and am still get an integrity error. If you want to send me that code you can send it to spudsmcghee@yahoo.co.uk and also i am using EV1 cards.

        P.S Thanks a lot, really

      • Gabriel

        Hi Bruno,
        Thanks for clear explaination of PICC master key change process. How did you overcome the 1E problem which I am also having when I send the key change command.

        KEY= 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        Random_A = 45 8D F3 A0 0D D3 9F B1
        PCD command = 0A00
        Random_B = 5C 21 59 09 DB AD A7 4B
        PCD command = AF1918A4FCFA6AE74FA0B89D4BDDE0497A
        PICC Reply = 004D85BF875ADDB9BC

        Session key = 458DF3A05C215909

        Block1 = 00 01 02 03 04 05 06 07
        Block2 = 08 09 0A 0B 0C 0D 0E 0F
        Block3 = 77 F5 00 00 00 00 00 00

        R1 0001020304050607
        R2 B774837B32146E1D
        R3 BF7D89703E196012
        R4 7B8662789CEEA0A3
        R5 0C7362789CEEA0A3
        R6 F0425DE79B1E00BB

        PICC command = C400B774837B32146E1D7B8662789CEEA0A3F0425DE79B1E0BB

        Thanks for the attention.
        Gabriel

  • Mustafa Moripek

    Hi Bruno,
    I have written DES for myself and I used standard C and GNU compiler.
    Following link may be useful (http://www.aci.net/kalliste/homepage.html).
    I didn’t used APDU but I have sent native changekey command and the
    three blocks.
    Good luck

  • Mustafa Moripek

    Bruno your command code is wrong.CA is for create application.Change Key
    command code is C4.

    • Bruno Bertechini

      Mustafa, typo and copy paste problem. Problem fixed! Key Changed and Card authenticated. Now I will move on to AES.

      Note: I am using all desfire versions for tests Mifare Desfire 4K (ID40) Desfire EV1 4K (ID41) and Desfire EV1 8K (ID81)…and also (just for tests desfire ev1 2k).

      Thank you very much for your help. Very soon i will post here some info on how I did it in C# to get it working with all credits for DES/CBC going to you 🙂

      Thanks!

      Bruno

  • Felipe Andrade

    Hello,
    I’m having some problems with the use of the session key.
    What I am doing is reading a standard data file that has zeros for data, and trying to reproduce the generated MAC.
    Here is a sample log of the commands I am sending

    >905A00000301000300 //Select Application with AID:010003
    900A0000010000 //Authenticate with key 0
    B = BBBCF23D82B7AA2B
    >90AF00001067CB1064A90A0BC5B705DB03C0EA7A4B00
    //With A = 0011223344556677
    906F000000
    //Get File IDs
    90F50000010200
    //Get FIle Settings for file 02
    90BD0000070200000008000000
    //Read 8 bytes from file 2 starting at index 0
    90BD0000070200000010000000
    //Read 16 bytes from file 2 starting at index 0
    <00000000000000000000000000000000D6ACE0D19100 //data:00000000000000000000000000000000 MAC: D6ACE0D1

    Now, encrypting 0000000000000000 with DES Session Key gives: FA2B513202BD660A
    And with the DES3 key gives: 3FA964A8211CDFA1

    neither of these matches the given MAC 7CEC960D. what key should I use?

    • Felipe Andrade

      The formatting didn’t show up right.
      here is the log again:

      PCD: 905A00000301000300
      //Select Application with AID:010003
      PICC: 9100
      PCD: 900A0000010000
      //Authenticate with key 0
      PICC: 630A702C444BE34A91AF
      //-> B = BBBCF23D82B7AA2B
      PCD: 90AF00001067CB1064A90A0BC5B705DB03C0EA7A4B00
      //With A = 0011223344556677
      PICC: BA6EB2C23193EE8A9100
      //Authentication Successful

      Session key should be
      DES: 00112233BBBCF23D
      DES3: 00112233BBBCF23D4455667782B7AA2B

      PCD: 906F000000
      //Get File IDs
      PICC: 03029100
      //Files 03 and 02 present
      PCD: 90F50000010200
      //Get FIle Settings for file 02
      PICC: 000100002000009100
      //standard data file, MAC, all access only with master key, size 32 bytes
      PCD: 90BD0000070200000008000000
      //Read 8 bytes from file 2 starting at index 0
      PICC: 00000000000000007CEC960D9100
      //data: 0000000000000000 MAC: 7CEC960D
      PCD: 90BD0000070200000010000000
      //Read 16 bytes from file 2 starting at index 0
      PICC: 00000000000000000000000000000000D6ACE0D19100
      //data:00000000000000000000000000000000 MAC: D6ACE0D1

      Now, encrypting 0000000000000000 with DES Session Key gives: FA2B513202BD660A
      And with the DES3 key gives: 3FA964A8211CDFA1

      neither of these matches the given MAC. what key should I use?

  • Mustafa Moripek

    Hi Felippe,
    1.What is your key 0, is it the default key all zeroes.The general rule is
    if the first half of the key is equal to the second half you use single DES.
    If the fist half is different from the second half you have to use 3 DES.
    2.When you send data to PICC you use DES or 3DES decryption because
    PICC always make encryption.When you build MAC you have to use
    DES or 3DES encryption.
    3.When you want to build the MAC you have to chain eight byte long
    blocks of data.You have to build the logical XOR of the first eight byte
    with IV(00 00 00 00 00 00 00 00) then DES or 3DES encrypt it.Then
    you have to build the logical XOR of the result with the the second eight
    byte and DES or 3DES encrypt it.The first four bytes of the result is
    your MAC.

    • Felipe Andrade

      The key 0 is the default all zeroes. Could you look at my example and tell me what the session key is supposed to be?

  • Mustafa Moripek

    According the data you have given the session key should be
    00112233BBBCF23D.To build MAC you should use single DES encrypt not
    decrypt and you should chain the two blocks using CBC as mentioned before.

    • Felipe Andrade

      When I send the PICC the command
      PCD: 90BD0000070200000008000000

      I am asking for 8 bytes, meaning that I should only receive 1 block. The response from the PICC is

      PICC: 00000000000000007CEC960D9100

      This, as I understand it, means that the data is 8 bytes of zeroes (1 block) followed by the 4 byte MAC which would be 7CEC960D.

      This would mean that if I XOR the first and only block of data with the IV I would still get 0000000000000000. If I encrypt that with the session key, I receive 0xFA2B513202BD66A0, which does not match the received MAC. Could you please point to where I am making a mistake?

  • William

    I am new for desfire card.

    Can someone explain how host DECRYPTS RANDOM_B when i first run the authentication. Use which IVector and Key to decrypt.

    If there is a sample code in c#, it will be prefect.

    Thanks a lot.

    • Felipe Andrade

      Unfortunately there are few C# resources when it comes to DESFire.
      Here is a short explanation of the authentication process.

      The PICC will send the application an 8 byte random number encrypted with the master key. The default master key is 0000000000000000 0000000000000000. Because both halves are the same, it is a single DES key and the session key produced will also be a single DES key. The IV is 0000000000000000.

      The tricky part with the authentication is to make sure the application decrpyts when sending the response. And make sure you use CBC-Send mode.

      You will receive e(B). Then you will send a 2 block message containing A followed by B’.
      Decrypted, the first block will be D1 = d(A xor B) followed by D2 = d(D1 xor B’).
      The response from the PICC will be e(A’^B’).

    • Felipe Andrade

      William,
      Apparently I gave you the wrong answer and might have led you down a path of much frustration. So in hopes that you do read this, when you reply to the PICC’s first response to the 0A command, reset the IV to 0000000000000000.

      So your transactions should look like this.

      PCD: 0A00
      PICC: AF e(B)

      PCD: AF (e(A)) (e(e(A) xor B’))
      PICC: 00 e(A’)

      your session key will then be the first 4 bytes of A followed by the first four bytes of B.

      • William

        Dear Felipe,

        Thanks for your reply and following up. Finally, i succeed to authentication step.

        By the way, do you know the cmd/Auth/others difference between the desfire (D40) and desfire ev1 (D41). As i only can find the Specification of D40. Can i develop the program according this specification? Thanks.

      • Felipe Andrade

        I haven’t been able to get the D41 functional spec either. You have to sign a NDA with NXP if you want those documents, and they can at times not be very helpful. However, you can find a lot of the details in the libfreefare source. http://code.google.com/p/nfc-tools/wiki/libfreefare

  • Mustafa Moripek

    Hi Felipe,
    are you sure that the session key and MAC are belonging together.
    Because with your data I’m getting the same result.

    • Felipe Andrade

      Mustafa,
      Have you been able to perform a change of key or any operation that uses the session key?
      Could you please post a log of such a transaction starting with the authorization using master key zeroes?
      Thank you

      • Bruno Bertechini

        Felipe, I am not at the office right now, but I will post something tomorrow regarding desfire/auth/change key etc..

        I had a hard time but with Mustafa’s help now I am being able to change key and authenticate with the new one.

        Will let you know tomorrow ok?

        By the way, I presume you are also from Brazil 🙂

        Bruno

      • Felipe Andrade

        Bruno,

        That would be a great help. Thanks in advance.

  • Adam Laurie

    There is an open source project that includes DESFire authentication and keychange examples written in C:

    http://code.google.com/p/nfc-tools/wiki/libfreefare

  • Felipe Andrade

    Can someone please help me. I have read every comment on this blog and other forums and still can’t seem to get anything that uses the session key working. I even looked through the libfreefare source and I could swear I am doing the exact same thing, but mine just doesn’t work.

    Here is a log of an authentication process?

    out: 5A 00 00 01
    in 00
    out 0A 00
    in AF B2 F1 D2 8A D5 55 3C 35
    out AF 86 71 3A E7 7C B7 C5 51 AF AF 66 4C 59 F4 8E 9A
    in 00 6F A0 F0 1F 9B EB B5 C6

    I think i might be interpreting my values of A and B wrong and therefore generating the wrong session key, so could someone please look over this and tell me what the session key from this authentication would be?

  • Mustafa Moripek

    Hi Felipe,
    what do yo want to do with sessionkey?
    I think your decryption algorithm is O.K.
    Otherwise you wouldn’t be able to authenticate and
    you wouldn’t get the answer: 00 6FA0F01F9BEBB5C6.
    To build the session key you get first 4 bytes of
    random A put first 4 bytes of random B then last 4
    bytes of random A and last 4 bytes of random B.
    If you wish send the complete data,I mean not only
    data coming from the PICC also the single DES
    decrypted data,so I can check them.
    of

    • Felipe Andrade

      Hi Mustafa,
      I am still having the same problems from last week. No operation that uses the session key seems to work correctly. reading/writing encrypted or MACed data, changing keys, etc…
      I am using the session key generated by combining the first halves of randA an randB. Here is another full trace where I create and then read 2 bytes from an encrypted file.

      The card is a brand new Mifare DESFire EV1 with one application FFFFFF, max 5 keys, access rights EF in it.
      The master key of application FF FF FF is the default, all zeroes.

      PCD: 5A FF FF FF
      PICC: 00
      PCD: 0A 00
      PICC: AF EA 18 DE FF 52 0E CD 90 //B = A42F3E842C5A2968 Please verify these numbers are correct
      PCD: AF 04 30 D7 63 E8 0E 43 1A 3D 09 69 AF 44 A2 70 D2 //A = 0123456789ABCDEF Please verify.
      PICC: 00 33 00 70 A7 4A DF 17 00
      PCD: CD 01 03 00 00 20 00 00
      PICC: 00
      PCD: BD 01 00 00 00 02 00 00
      PICC: 00 EC 3B 5D E6 C6 1F 88 21

      As you can see, decrypting EC3B5DE6C61F8821 with key 01234567A42F3E84, gives 41C415038EFE212B. This is clearly wrong since the block should be bytes of data, followed by 2 bytes of CRC and then padded with zeros.

      just in case it might be relevant, here is what I receive when I perform a getVersion command.

      AF 04 01 01 01 00 1A 05
      AF 04 01 01 01 03 1A 05
      00 04 50 3B 81 33 26 80 CF B6 D4 66 90 53 08

  • Mustafa Moripek

    Felipe,
    your B is correct,but there is something wrong with your decryption of A.Are you sure that you get:
    0430D763E80E431A when you decrypt: 0123456789ABCDEF,
    because I’m getting different data.
    Another thing is that you have chain both blocks of
    byte using CBC before sending them to thePICC.But
    first try to fix the problem with decrypting of A.
    For this I’m getting : 3B 73 A1 53 75 7B 1A D8

  • Mustafa Moripek

    Sorry Felipe,the correct data
    I’m getting is : 80 B1 7A B4 00 B2 B9 37

    • Felipe Andrade

      wow,
      thank you so much mustafa.
      Here is what I was doing wrong in case anyone out there is having the same issue.
      The IV never carries over from previous messages sent, it is always reset to 00000000000000.

      So after the first decryption of e(B), what I did was keep B as the IV, then sending D1 = d(A xor B) to the PICC followed by D2 = d(D1 xor B’). What is truly curious is that the PICC’s response, in my line of thinking was valid. What the PICC was actually responding was e(A’), but I thought the PICC was responding A’ ^ B’, since B’ was, i thought, the IV.
      Now, A’ xor B’ = (A xor B)’.

  • c t skinner

    Authenticated “Standard” DESFire OK
    Read & Write Standard & Backup files Plain Mode OK
    So I decide to create a DES encrypted Linear File
    File Created OK
    Write Data NOT OK
    CRC32 must be inverted and bytes reversed from usual OK
    Padding: The Card complained so I tried 28 Bytes (+4 bytes = 32, OK for DES)
    Sent the data, card replied AF (More please)
    Sent the More block, wrapped in iso7816

    Sent: 90AF00002700000000200000491E890DE9ACE9320AA0DF24E9FE9CECF5B9424D66190FFD9C0695F2AB5DD7BC00
    got …917E LENGTH_ERROR Length of command string invalid…
    the apdu is OK what can they mean by “command String”??
    Previous 90AF sends to PLAIN files went OK
    Whatever I put in the data I get 917E, ie its not a decryption problem…

    • Felipe Andrade

      c t skinner,

      The CRC is CRC16, the implementation is a bit odd, you can find it in the ISO 14443-3 specification. That is probably what is giving you the error. Also, try first sending a small message so that you don’t have to send additional frames.

  • Gorka

    Hi,

    After some time I am now back to DESFire and I want to do some tests with SAM modules, where the keys of the reader will be hosted. I already have some SAMv2 modules and readers ready to work with them.

    I have completed many times DESFire authentications, so I know the procedure. I also have read the SAM specification and communicate with it sending for instance the GetVersion command and getting the correct answer. I also know how the DESFire_Authenticate command works.

    So now, my problem is that I don´t know how to make the DESFire tag and the SAM module work together. What I want is that when the reader detects a new tag to try to authenticate it using the keys that are stores in the SAM module.

    Just for you to know, I am using Gemalto´s GemProx PU reader, which has 2 SAM slots

    Thanks,
    Bye

    • Felipe Andrade

      Gorka,

      Unfortunately, I can’t really help you. But I would like to know how you obtained the SAM functional specification. Did you sign an NDA with NXP? If not, could you please tell me where I can find it? I’ve been trying to get a copy of the spec from NXP but they have been less than helpful.

      • Gorka

        Hi Felipe,

        Yes, I obtained the SAM specification from NXP and I had to sign and NDA with them before. So, I cannot send you the spec, sorry.

    • Mustafa Moripek

      Hi Gorka,
      it is similar like communicating with Desfire directly.
      The only difference is that you don’t need to make all
      the decryption work for yourself but let it make the SAM module.You send the authentication command to the Desfire card,the answer which is encrypted RndB you
      forward to the SAM module.From the SAM module you
      will get decrypted RndA+RndB’ which you forward to the
      Desfire card.This goes on until you get from the
      Desfire card that the authentication is complete.Now
      if you want to communicate encrypted with the Desfire
      card you have first to send the plain data to the SAM
      module and get the encrypted data which you forward to
      the Desfire card.And send the encrypted data to the
      SAM module to let it decrypt by the SAM module.

      • Gorka

        Hi Mustafa,

        Thanks for your response. Yes, I supposed it should be that way, the problem I have is that I don´t know how to forward the challenge I get from the tag to the SAM directly without having to type it by myself. I guess somehow I have to install a script or something in the reader.

        Anyway, I guess that what I have to read about is the reader, and not the specs of the DESFire and the SAM, because the problem is not in the commands I have to send to them, but in the way to communicate with both at the same time.

        Thanks again.
        Bye.

      • Gorka

        Hi again,

        I forgot something. I don´t know what reader have you used, but I guess the way to work should be similar. Right now I am using the GUI application they gave me. So what I do is to initialize the 14443-A and the SAM module and complete all the Select procedure. Next I send an authentication request command to the tag, I get the challenge and then I copy it and paste it inside the command I send to the SAM. I get the response, copy it and paste it to the 14443-A management page, etc.

        What I want to do obviously is to make all this procedure automatic, so that I don´t have to copy the responses by myself. How can I do that, with some kind of script, or application in C++ using the API they gave me?? In that case, I guess I should have to connect to the COM port where the reader is and then start sending Request commands until I detect a tag and send all the commands from the tag to the SAM and viceversa. Is that correct?

        Thanks a lot for your time.
        Bye.

  • Mustafa Moripek

    Hi Gorka ,
    I have used my own reader and programmed the
    microcontroller by myself.For you are using the Gemalto
    reader you can communicate with it via com port.You
    must have got a protocol containing the command with
    which you can program the reader.
    Good luck.

  • William

    hi,

    I have some trouble while Read/Write data to a standard file on the Desfire Ev1 card. When i using the DES key (default key) to Read/Write a file with communication setting (0x03), it seems good. I can Read/Write though the DES encryption. But while i change the key to 3DES. There is a problem. Here is my log.

    Session key: 689739801798A3C7F51474E391161AD0

    -> F501
    BD01000000080000
    3D010000000800002d21b790a3206306d607b4601f751bb8
    (Send 8 byte data “0102030405060708”)
    <- 917E(?)

    Thanks.

    • Felipe Andrade

      William,

      The message you are sending is correct. Which means that the session key you are using is not right. Could you post a log of the authentication, and the session key you believe you generate. Also, be aware that the formatting in these comments has some quirks, so try not to use less than and greater than signs.

      • William

        hi Felipe,
        Here is log of my session key general procedure. It is the same way but not same session key.

        Key: 00112233445566778899AABBCCDDEEFF
        RndA: 73F84DA38F00C5F8

        PCD: 0A00
        PICC: AFC29197BF294F8D1E ( RndB = A9D9A650ED69BD05)
        PCD: AF3FB4E85D80A263BA51CF1AEF94B9F325
        PICC: 00FD755A5AF48B9032

        Session Key: 73F84DA3A9D9A6508F00C5F8ED69BD05

        PCD: F501
        PICC: 000003EEEE000400
        PCD: BD00000000080000
        PICC: 0000000000000000 (Why not encrypted?)
        PCD: 3D000000000800009452d9941cbded3a75629ac35d80e3a1
        PICC: 7E (Lenght_Error?)

      • Felipe Andrade

        William,

        The reason you receive the data in plain mode when you read the file is because the access rights of the file are set to EEEE. This means that there is free access for to every operation on the file. Try setting the access rights to a specific key and you shouldn’t have a problem.

  • William

    Felips
    It works. Thanks.

    By the way, do you know how to use AES on the card?

  • seray

    Hi
    My project is creating a mobile payment application with NFC.We bought a reader (Obid Classic-pro(HF) ID Cpr40.30-usb) and Mifare tags. I am using Mifare DESFire because i think it is the most adequate transponder for payment. My problem is i am not able to run the DESFire commands because of the crypto processing errors. According to my reader’s manual, the reason of error is transponder. Desfire error codes which i am getting is usually 0x9D, 0xA0, 0x1C. I am using AES keys for authentication. I will send a video to you (The link is below). I am doing the same things exactly with the man in the video but he can run read and write processes successfully, i can’t because of the errors that i mentioned before.

    http://www.trikker.fi/downloads/Desfire EV1_Tutorial_640x480.mp4

    If you have any idea about my problem and its solution, please contact and help me.

  • seray

    how can i define a key for an application or file?

    For example i am creating application with this APDU

    CA 563412 0F 8D

    I found it from somewhere i can’t remember. The explanation is

    Create Application – ID=0x123456 – ApplikationMasterKey Settings=0x0F – AES encryption with 14 keys

    I understand that 563412 is application id, i didn’t understand the meaning of 0f and 8d. i am using AES keys for reader.

    And i am creating file with this APDU

    CD 01 03 3412 FF0000

    CreateStdDataFile : FileID = 1 – Communication Settings = 0x03 (AES Enryption) – AcessRights 0x34 0x12 [Read(Key)=1 Write(Key)=2 R/W=3 Acess=4] – Length = 255

    Here 01 is file ID, 03 again i am not sure what is it, and i have no idea about access rights. I am using them for reading or writing the card as desfire key number. For reading 01, writing 02…

    After all i am getting 1C error-illegal command code.

    I don’t know where is the error but i guess it is about defining keys for the cards.

    Are these APDU’s true? If it is true what should i do as an extra for defining keys to card.

    I need your answer.

    If anyone understand my problem, you can contact me from serayozdemir@hotmail.com or serayozdemir@gmail.com

  • Mustafa Moripek

    1. 8D means number of keys (it defines how many keys can
    be stored within this application).
    2. Meaning of application masterkey (0X0F) :
    Bit7-Bit4 :
    0X00 :Application masterkey
    authentication is necessary to
    change any key (default)
    0X01-0X0D :Authentication with the specified
    key is neccassary to change the key
    0X0E :Authentication with the key to be
    change is necessary to change the key
    0X0F :All keys within this applications are
    frozen

    Bit 3 :
    0 : configuration not changeable
    anymore
    1 : configuration changeable
    Bit 2 :
    0 : Create file and delete file
    is permitted only with
    authentification with appl.master
    key
    1 : Create and delete file without
    authentification
    Bit 1 :
    0 : Application master key authentification
    is necessary for GetFileID,
    GetFileSettings and GetKeySettings
    1 : Authentication not necassary to execute
    the above commands
    Bit 0 :
    0 : Application master key nomore
    changeable
    1 : Application masterkey changeable
    3. The meaning of communication settings :
    0 : Plain communication
    1 : Plain communication with DES/3DES
    MACing
    3 : Fully DES/3DES encrypted communication

  • Meph

    Hello,

    does anybody have some hints how to calculate a CMAC with AES Cipher in Java. I tried to follow an example from NXP with the SDK from bouncycastle but i wasn’t able to get the right values. I would be very grateful.

    Stefan

  • Marc

    Hello

    This blog is very interesting. I have found no more information on APDU commands on internet, thanks for your work.
    I’m working on this kind of project. I need help. I hope you could read this.
    Here are two file settings.

    Get file setting for file 0C
    – CLA=90, INS=F5, P1=00, P2=00, LC=01, LE=00
    – DATA=0C
    Response APDU:
    – SW1=91, SW2=00
    – DATA=0000317F200000

    Get file setting for file 01
    – CLA=90, INS=F5, P1=00, P2=00, LC=01, LE=00
    – DATA=01
    Response APDU:
    – SW1=91, SW2=00
    – DATA=0101417F800100

    I am in the 108057 application (Transport NF).

    I know that I have to authentificate with key 07 of this application.
    So I do :
    – CLA=90, INS=0A, P1=00, P2=00, LC=01, LE=00
    – DATA=07
    Response APDU:
    – SW1=91, SW2=AF
    – DATA=F7 9A BB 80 7C E4 85 BA

    The problem is that I don’t understand what I must do after this. On your page, we writted this :
    Authentication with key 00 (for PICC Application):
    –> 0a 00
    af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c
    f5 0c
    bd 0c 00 00 00 10 00 00
    <– 00 90 80 00 02 XX XX XX XX 6c 68 00 28 00 02 80 40

    Could you tell me why there is " 00 00 00 10 00 00 " after0C, please ?
    Thanks.

    Marc

    • Felipe Andrade

      I don’t think you read the blog post correctly.
      The authentication goes like this
      Reader: 0a 00
      Card: af a2 be cd 03 d8 46 cb 33
      Reader: af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c
      Card: 00 76 73 d9 49 71 3f f2 d1

      • Marc

        Oh sorry. My message isn’t clear.
        There are two questions :

        – concerning Authentification :
        I don’t understand why it goes like
        Reader: 0a 00
        Card: af a2 be cd 03 d8 46 cb 33
        ->Reader: af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c
        can you tell me why this parameter ?
        Card: 00 76 73 d9 49 71 3f f2 d1

        – Moreover, when we want to read data in a file. I don’t understand the parameters.
        bd 0c 00 00 00 10 00 00
        <– 00 90 80 00 02 XX XX XX XX 6c 68 00 28 00 02 80 40

        Thanks

      • Felipe Andrade

        lets say both the reader and the card have a shared DES3 key.
        Remember that the card can only perform encryption.
        Reader: 0a 00 (Authenticate with key 0)
        Card: af a2 be cd 03 d8 46 cb 33 (sends e(B), where B is a random 8 byte number)
        Reader: af b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c (reader generates random A and sends d(A) = b0 cc bc ed 8f c8 38 c9, followed by d(B’) using CBC = d(d(A) xor B’) = 08 dc e2 4d 86 ca ec 3c)
        Card: 00 76 73 d9 49 71 3f f2 d1 (This is e(A’))

        the reason why the card has to send e(A’) is to assure the reader that the card has the appropriate key. If someone were to be monitoring the communication between card and reader, they could use the same B (generated by the card) every time. And without knowing the key, complete a successful authentication. If the Card has to send e(B’) then knowledge of the key is necessary.

        When reading data from a file
        bd 0c 00 00 00 10 00 00 (0c specifies the file number, 00 00 00 specifies the starting index, 10 00 00 specifies the number of bytes to read. So this command reads 16 bytes from file 0x0C starting at index 0.)
        <– 00 90 80 00 02 XX XX XX XX 6c 68 00 28 00 02 80 40

  • Marc

    Thanks a lot.

    So I have not the key #7 for this application.
    I can’t read more concerning the file of this application.
    What a pity.

  • Marc

    hey
    Just a little question more.

    Do you think there is a error counter for the authentification ? I mean if I try wrong key for the authentification. There is no documentation about that.
    I don’t want to block my card ^^

    Thank.Bye.

    • Adam Laurie

      No, it’s not documented and testing would appear to confirm that it’s OK to fail auth as often as you like. I just ran the following script:

      $ while [ 42 ] ; do desfiretool.py 1 select 000000 auth 00 1122334455667788 ; done

      which (repeatedly) gave the result:

      Using reader: OMNIKEY CardMan 5×21 (OKCM0022602100142172731750393654) 00 01

      Card UID: 80D9EB58

      Selecting AID: 000000 (OK)

      Authenticating against Key 00 with key: 1122334455667788 Failed: Authentication error

      I then did:

      $ desfiretool.py 1 select 000000 auth 00 0000000000000000

      which gave:

      Using reader: OMNIKEY CardMan 5×21 (OKCM0022602100142172731750393654) 00 01

      Card UID: 80D9EB58

      Selecting AID: 000000 (OK)

      Authenticating against Key 00 with key: 0000000000000000 (OK)

      So i guess you’re OK! 🙂

  • Ján Lazár

    Hi guys,

    From beginning i would like to thank you all, especially Ridrix for all the information above. And of course I need help ;). It’s about documentation, I have ISO 7816-1,4,6,7,8,9, I have access to the NXP documentation. About NXP documentation, I don’t know which documents are relevant for me. I’m working with DESFire EV1, and so far I consider being important on NXP just these documents:

    from
    http://www.nxp.com/#/homepage/cb=%5Bt=p,p=/53420/71108/53422/53450%5D|pp=%5Bt=pfp,i=53450%5D
    just document MF3ICD4101DUD

    and from
    http://www.nxp.com/#/pip/pip=%5Bpip=MF3ICDX21_41_81_SDS,pfp=53450%5D|pp=%5Bt=pip,i=MF3ICDX21_41_81_SDS%5D
    protected archives (at the bottom of the page)
    – DESFire & DESFire SAM, Reader Software Library, Programmer’s Reference Manual
    – DESFire ev1 Reader API

    I suppose, there is much more, I just don’t know which ones. Could you guys post url’s of other relevant NXP documents(about authentication, creating application, …)

    About ISO/IEC 14443, I suppose, I’m gonna need parts:
    3 – here supposed to be information about cryptography and
    4 – here supposed to be commands description
    Is that right?

    Other sources I could use are:
    http://code.google.com/p/nfc-tools/wiki/libfreefare
    http://www.developer.nokia.com/Resources/Learning/
    http://www.nfc-forum.org/home/
    http://www.cryptopp.com/
    http://msdn.microsoft.com/en-us/library/aa924246.aspx
    do you have any other useful sources?

    Thanks
    Jan

  • Ján Lazár

    Those links are not working, this hopefully is gonna:
    http://www.nxp.com/#/ps/ps=%5Bi=53450%5D|pp=%5Bt=pfp,i=53450%5D

    for second link you click on MF3ICD4101DUD document

    or here is the path:
    Identification and security / Smart card ICs / MIFARE smart card ICs / MIFARE DESFire

  • PCSC Mifare Desfire Python API « marianobe

    […] Desfire cards to be used with PCSC readers. It is based on Desfire Functional Specification and this post has been very helpful. More news coming soon. Share this:TwitterFacebookLike this:LikeBe the […]

  • Alex

    Hi.

    First of all thanks for that blog that definitely helped me a lot.
    Yet I still have an issue…

    I’ve successfully performed an authentication (after PICC selection) with key-00, retrieved the key settings (0x0f) and I now would like to change it to 0x0e with the ChangeKeySettings command and I constantly get the INTEGRITY_ERROR (0x1e)… whatever I try.

    Here is what I do:
    * new key settings = 0e
    * CRC16 = 80 b8 (0xb880)
    * data buffer = 0e 80 b8 00 00 00 00 00
    * decrypted data buffer (key-00) = 3c 5b 1b 80 4a 1d a0 1b
    * data sent to card = 54 3c 5b 1b 80 4a 1d a0 1b

    * card answer = 1e

    I’ve been looking for days and can’t figure out what’s wrong with that.
    Could you give me a hint?

    Thanks,
    Alex

    • Mustafa Moripek

      Hi Alex
      it seems to be O.K. what you have done.Let me see your key and session key.Possibley they are not O.K.
      Mustafa Moripek

      • Alex

        Oh… should I DES decrypt with the session key and not the key I’ve done the authentication with (key-00) ?

        key-00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        sess. key: 88 ee b3 a9 4b 31 a3 20 64 3d 3e d0 ce e6 ca 6d

        If I use the first half of the session key to DES decrypt the data buffer I get the following: b3 47 98 a6 35 63 21 99

        Anyway… still get the integrity_error…

        Thanks,
        Alex

  • Mustafa Moripek

    Hi
    Yes you should single DES encrypt with the session key.But your session key is wrong.
    If the first half of the key you are authenticating with is equal to the second half of the key,you have to build your session key eight byte long.For you are using the default key all zeroes the first half is equal to the second half.For building the session key you have to put the first half of RndA and RndB together and use this session key for single DES
    encrypting.
    Good Lock.
    Mustafa Moripek

  • ajifa2

    Hello everyone,

    The information here is very helpful. And I really appreciate your great effort to aggregae useful information here. (many important notes, test vectors and links.)

    BTW, I am writing a Desfire_lib in Java. And thanks to this blog, I am almost done except for two thing. KINDLY HELP ME!!!

    I succeeded in Authentication, ChangeKeys, etc. in both DES and T-DES using NFC reader (ACR122U) in ADPU wrapping mode. (on Windows XP+PC/SC)

    Issue-1
    Read/Write to MACed file is OK.
    But problem is, I need to send MAC data (4 bytes) in separate ADPU Write packet. (orginal msg and MAC) Why can’t I send it in ONE flame???

    Issue-2
    I cannot Read/Write DES file.
    (Always result in “INTEGRITY_ERROR (CRC or MAC does not match.)”)

    1) plaindata ={0x00 11 22 33 44 55 66 77 88 99}
    2) CRC_16(plaindata)={0x 84 EB)
    3) msg_w_pad = {0x 00 11 22 33 44 55 66 77 88 99 84 EB 00 00 00 00}
    4) Decrypt_CBCSendMode(msg_w_pad, key {0x 01 23 45 67 89 AB CD EF}) /* Single DES in this case, key should be session key */
    5) DES_msg ={0x 8C 77 40 7E 02 4F 66 AD 43 1F F2 01 FA C5 1F 5C}

    Then send WriteData(DES_msg) ADUP paket.
    BUT PICC still response “AF” for further data.
    So I added zero_packet (0x 80 00 00 00 00 00 00 00), but it doesn’t work.

    What is expected for the last packet??

    Thank you very much for your kind guidance in advance!!!

  • Kjarrigan

    Hi @all
    this blog helped me a lot with my desfire implementation, but have some problems with desfire ev1 – AES Authentication. (des works fine, creating apps, file, etc). I always got AE – Authentication Error. I guess my encrypted Randoms are wrong but don’t see the problem. Maybe you can help: (Got a empty Card with Standardkeys.)

    Select Application
    => 5A 00 00 01
    AA 00
    92 af 3c 21 9a 30 7d 66 74 ca 27 a2 c6 4d 9b 73

    Then Leftshift by 8 Bit
    => af 3c 21 9a 30 7d 66 74 ca 27 a2 c6 4d 9b 73 92

    Now “generate” RndA
    => 00010203040506070001020304050607

    Now Encrypt RndA and RndB’
    XOR after encryption with 16 x 0x00
    crypto_1 => 26 16 77 8a db a8 4f 38 ee 32 87 9a 29 98 13 55

    XOR after encryption with RndA
    crypto_2 => 3f 0c c4 14 20 e1 9f 6f 1c b2 1c 5d 24 21 fd d6

    Send enc(RndA || RndB’)
    => AF 26 16 77 8A DB A8 4F 38 EE 32 87 9A 29 98 13
    55 3F 0C C4 14 20 E1 9F 6F 1C B2 1C 5D 24 21 FD
    D6
    <= AE

    Any ideas?

    • Kjarrigan

      For your interest. I’ve found the problem: The not (or bad) document IV-handling. In DES Authentication you reset the IV always to 0x00. In AES your IV for your encryption is the Enc(RndB) and for Decryption of RndA’ u use crypto_2.

      With the right session key generation my ChangeKey Command worked, too 🙂

      • Marek

        Hi!

        I’m playing with Desfire EV1. DES/3DES authentication and data handling is working perfect. I manage to change MasterKey to AES (for MasterKey it will be key no $80), but now I’m not able to login into my card anymore.

        Please find attached my session with Desfire Ev1:

        MasterKey: 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff

        >> AA 00

        << AF 70 3A C2 8A 14 25 27 07 5F BA 0E 9B D7 C9 87 E0

        ——–

        Enc(RndB) = 70 3A C2 8A 14 25 27 07 5F BA 0E 9B D7 C9 87 E0

        After DECRIPTION with AES 128 (IV=00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) – is IV correct?

        RndB = 94 C8 15 B4 E9 D3 19 EF D0 4F 8A 33 CF 8D C3 93

        Now I rotate left by 8 bits

        RndB' = C8 15 B4 E9 D3 19 EF D0 4F 8A 33 CF 8D C3 93 94

        My 'random' RndA will be:

        RndA = 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f

        Now I have to send to PICC following command:

        AF enc(RndA) enc(RndB') – Is this correct?

        enc(RndA) will be ENCRYPTED RndA with MasterKey, but what IV vector schould I use?

        enc(RndB') will be ENCRYPTED RndB with MasterKey, and IV vector schould be enc(RndA). Is this correct?

        Maybe someone can post full authentication session with AES key, so I can check my application.

        Regards!

  • tourougins

    Hi,
    can anyone tell me how can i calculate the CMAC to be sent after a changekey command ?
    thxs

  • Bruno

    Hello there!

    After a while without working on smartcards, here im back again with one (and night-skipping) doubt.

    I am trying very hard to make a C# polling mechanism work together with the GetVersion APDU wrapped desfire command without success.

    My scenario:

    I am using C# and P/Invoke to access the reader and smartcard (Mifare DESFire EV1 2/4/8K).

    I am using the APDU to wrap the GetVersion Command (90 60).

    I can successfully execute the getversion againts the card. Even several times (I have tried a for loop with 500 requests). Everything is working fine.

    My problem is: I need to implement a polling mechanism to monitor for card presented/removed events from reader.

    I am running this “polling” on another thread (have tried new Thread, background worker, etc).

    The problem is: When I run the GetVersion APDU command against the card while I am inside the polling mechanism, I receive a “91 1C” response from the card.

    91 1C means: ILLEGAL_COMMAND_CODE (Command not supported).

    This usually happens while sending the second frame of 0xAF (to retrieve more data).

    Im getting tired of this error and have tried several tricks (lock, AutoResetEvent and many others on C# and .net) to avoid this problem without success.

    I sincerely hope someone can help me on this!

    Cheers budys!

    Bruno

    • Bruno

      Just to add one more heads up:

      If I insert a Thread.Sleep of 400ms between the connecting to card (with SCardConnect) command and the DESFire GetVersion command it works like a charm!

      Weird. Is that a expected behavior?

      Bruno

      • Zack

        Bruno,
        you can use the SCardGetStatusChange function to check the status of the reader, and check if a card is present or not. by doing this you can keep track of the state of lots of readers at the same time really easily.
        Zack

  • marianobe

    Hello: I’ve written a Python implementation (an example) of AES-128 simmetric key diversification as described in document AN10922. In case you think it might be useful, here’s the link: https://gist.github.com/1409585

  • RAY MOH

    Hi all,

    If you are working on Desfire EV1 AES authentication (i.e. 0XAA), you can follow the following algo and it works

    http://books.google.com.hk/books?id=RptQEcaQtJ4C&lpg=PA196&dq=desfire%20aes&hl=zh-TW&pg=PA197#v=onepage&q=desfire%20aes&f=false

  • Amila

    Hi ridrix,

    I have stucked with the Desfire Authentication Command.
    I have shown below the APDUs

    ->0A 00
    AF C5 34 FC 90 76 C6 4C 62 65 7A D2 9E 4D 4D CF 58
    <- AE

    Key : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    IV : 00 00 00 00 00 00 00 00

    Can you tell me whats the wrong with this ?

    Thanks
    Amila

    • Mustafa Moripek

      High Amila,
      many steps are missing,therefore itis not possible to determine
      the error.Please write all steps from the beginning.The
      authentication procedure is describe at the start of this site.

      • Amila

        Hi Mustafa,

        I am really sorry, I have done a mistake when sending the question. Anyway I could overcome the issue with authentication. Thanks for your response, I’ll need your help in future.

  • AmandaG

    Hi all,

    I am new in smartcard programming and I ve got some trouble on Mifare DESFire ISO wrapping. The point is that I seems to have additionnal bytes on my response APDU. Namely on an application linked to 3 AES keys for a Get key settings command :

    cmd > 9045000000
    resp 9045000000
    resp< 0F83E524DE703EA850BD9100

    While I am expecting to have
    1byte for key settings || 1 byte for max No of key || MAC data

    I am missing something however the status codes are OK.

    Can you help me with this?
    Thanks in advance.

    Regards !

  • AmandaG

    Correct sequence
    cmd > 9045000000
    resp 9045000000
    resp< 0F83E524DE703EA850BD9100

  • Mustafa Moripek

    Hi Amanda,
    your command is not complete, the Le is missing.The iso APDU wrapping is as follows :

    cmd:
    cls ins p1 p2 lc(length of wrapped data) data Le
    90 native instruction 00 00 XX XX 00

    response:
    data length SW1 SW2
    XX XX native status code

    So the correct command string is :
    –> 90 45 00 00 00 00
    <– 0F 01 91 00

  • Amila

    Hi Mustafa

    I could successfully performed the Authentication command and I have a issue with ChangeKey, Please look at my situation mentioned below

    RANDOM_B : 75 fc 01 86 9d 90 96 09
    RANDOM_A : 01 23 45 67 89 ab cd ef
    Session Key : 75 fc 01 86 01 23 45 67 9d 90 96 09 89 ab cd ef
    OLD_KEY : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    NEW_KEY : 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01

    ChangeKey Commandis = C4(1 Byte) + KEYNO(1 Byte) + Deciphered Key Data (24 Bytes)

    Can you please explain me how can i create Deciphered Key data (24 Bytes)

    I really appreciate your help on this.

    Amila

  • Mustafa Moripek

    Hi Amilla,
    I think ,in your case,the key number you are authenticating with is the same as the key you want to change .So you have to proceed as follows:
    A two byte CRC is calculated over the new key data(16 bytes) and appended at the end.For the DES/3DES encryption is made using with frames of 8 bytes you must pad your data with 6 zeroes.Your
    plain data should look like this:

    [16 Bytes new key][2 Bytes CRC 00 00 00 00 00 00]

    Now you should DES encrypt this data with the session key.
    Good Luck
    Mustafa

  • Amila

    Hi Mustafa,

    Thank you so much for the quick response. I followed the things you advice and I am getting 1E response. I have lay down my data below.

    SESSION_KEY : 17 4e 28 39 01 23 45 67 22 f4 25 3d 89 ab cd ef
    NEW_KEY : 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
    CRC16 for NEW_KEY : ce bd
    NEW_KEY + CRC16 + 6 bytes PAD : 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 ce bd 00 00 00 00 00 00

    ENCRYPTED WITH SESSION KEY : aa 5c 99 58 d9 cd 9e 8d fc ab e8 2f 32 bc 92 3a 90 5c 41 c5 73 ab f8 e6

    FINAL COMMAND : c4 00 aa 5c 99 58 d9 cd 9e 8d fc ab e8 2f 32 bc 92 3a 90 5c 41 c5 73 ab f8 e6

    Please advice me to find the issue on this.

    Is there any problem with how i create the SESSION_KEY ?
    RANDOM_B : 17 4e 28 39 22 f4 25 3d
    RANDOM_A : 01 23 45 67 89 ab cd ef
    SESSION_KEY : 17 4e 28 39 01 23 45 67 22 f4 25 3d 89 ab cd ef

    Thanks
    Amila

  • Mustafa Moripek

    Hi Amilla,
    1E means either your CRC is wrong or your MAC is not correct.To calculate MAC you have to proceed as follows:
    1.You have to exor the first byte (01 01 01 01 01 01 01 01) with
    IV all zeroes,and 3DES encrypt it with session key.
    2.You have to exor the second byte (01 01 01 01 01 01 01 01) with
    the result of the first step, and 3DES encrypt it with session key.
    3.You have to exor the third byte (CRC1 CRC2 00 00 00 00 00 00) with
    the result of the second step, and 3DES encrypt it with session key.
    4.You append all of them to your command c4 00.

  • AmandaG

    Hi Mustapha,
    Thanks for your answer.
    I am wondering if it is not implementation choice of the tools I am using (since Lc and data fields are optional). I’ve got a correct status code and trying :
    cmd > 904500000000
    resp< 917E
    7E means length error
    Extra data was a CMAC value from my settings that doesn't appear all the time. I've fixed this.Thanks.

  • Mustafa Moripek

    Hi Amanda,
    iso command APDU looks like :
    CLA INS P1 P2 Lc Data Le
    90 45 00 00 00 00 00
    Data field is optional but Lc is not.Lc is the length of data field.
    If you don’t have any data the Lc=00.Therfore your command
    APDU 90 45 00 00 00 00 is correct and you should get the
    answer 0F 01 91 00.

  • Amila

    Hi Mustafa,

    Thank you so much for your support and I really appreciate . I got successful change key functionality.

    Amila

  • AmandaG

    Hi Mustapha,
    I am using PC/SC Diag from http://www.springcard.com/solutions/pcsc.html
    which is as they say a “quick’n’dirty software to exchange APDU”…
    Please can you help me on this.
    I’ve also got issue on ChangeKey. I am using AuthenticateIso cmd and key number used for authentication is the same as the key number to be changed
    3DES session key is F6C87AD0F4AD5CA52FBE35F612B442C6
    New key + CRC32 + Pad = 1111111111111111111111111111111168C9375800000000 => enciphered = E50E3E54226C67EE1CBE3881542E59A7AAAB6E5810306806
    The overall (wrapped) command is
    90C400001900E50E3E54226C67EE1CBE3881542E59A7AAAB6E581030680600
    I got AE(authentication error)response status.
    I’ve successfully authenticate before performing ChangeKey so I don’t get it. Any idea ?
    Thanks in advance for your answer.

  • Mustafa Moripek

    Hi Amanda,
    As far as I can see, there are two mistakes.
    1.The first half of your key is equal to the second half,so you
    have to use DES encryption and not 3DES.
    2.You should use CRC16 and not CRC32.
    Try to fix the issues.If there are still problems write down all the communication between reader and the card.
    Godd luck.
    Mustafa

  • Amila

    Hi Mustafa,

    I have two applications and each application has one standard file. For doing a specific function I have to update the both files in both application. How can we grantee the Atomic transaction of this function. It may be failed to update the second file once first has done successfully, due to RF signal issue or some other reason. How can we handle such situations, is there any native support from Desfire or we have to use some tricky things to handle this. If you have any idea please share.

    Thanks
    Amila

    • Mustafa Moripek

      High Amila,
      the only way to be sure that the transaction has been executed successfully is to read the files after write operation.But the Desfire has a property which enables you that the file doesn’t get destroyed during any write operation because of RF failure.During value operations, add or subtract operations, you have to send commit transaction command.Until that time the original data remains in their original values.The same thing you can make with plain data if you use backup data file instead of standard data file.For all changes are made in a mirror place you have to open your backup data file with double the length of your normal file.
      I hope this information helps you.
      Good luck
      Mustafa Moripek

  • Amila

    Hi Mustafa,

    Is there any crc16 implementation that can use inside the javacard applet. Since most of the crc implementation use int variables and cannot use them inside the javacard applet, Do you have any idea to overcome this ?

    Thanks & Regards
    Amila

  • Mustafa Moripek

    Hi Amila,sorry but I don’t have such a CRC implementation.
    Mustafa

  • Amila

    Hi Mustafa Moripek

    Is there any way to maintain cents in value file.

  • Mustafa Moripek

    High Amila,
    No there isn’t.Value Block data is four byte signed integer.You have to handle the exchange to cents in
    the firmware of your hostcontroller.
    Mustafa

  • Ján Lazár

    hi,

    my name is Jan Lazar
    i’m not able to use MFDESFire8 library with AES encription,
    my reader is OMNIKEY CardMan 5321 USB Reader,
    with brand new card just CRM_3DES_ISO, CRM_3DES_DF4 are working for following bit of code.
    i’m not able use CRM_AES, CRM_3K3DES

    could you give me any hint, what i’m doing wrong, thank you very much

    jan lazar
    janolazar@gmail.com

    code:

    BYTE klucAplikacieAES_K0[16] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    BYTE klucKarty_KO[24]; memset(klucKarty_KO,0,24);

    retsReturnCode = poCardObject->SelectApplication(0x00000000);
    funkcie->PopisChyby(“SelectApplication 0x00000000”, retsReturnCode, textBox);
    if(retsReturnCode!=0) return -2;

    retsReturnCode = poCardObject->Authenticate( 0,
    klucAplikacieAES_K0,
    CRM_AES ); // CRM_3DES_ISO // CRM_AES // CRM_3DES_DF4 // CRM_3K3DES
    funkcie->PopisChyby(“Authenticate CRM_3DES_ISO 0,24”, retsReturnCode, textBox);
    if(retsReturnCode!=0) return -2;

    retsReturnCode = poCardObject->FormatPICC(); funkcie->PopisChyby(“FormatPICC”, retsReturnCode, textBox);
    if(retsReturnCode!=0) return -2;

  • Narendra

    Dear All,

    i need help for desfire. We want to create,read & write in the Desfire card. We have Omnikey 5321 reader. Please provide me all set of APDU commands.

    Your help will be more appreciated.

    Thank
    Narendra

    • Meph

      Do you have some further information about the Card? Which encription, application, filenumber…

      • Narendra

        Actually i hv NXP desfire blank card, we have to create complete structure for card, so we don’t have any commands to start.

  • Amila

    Hi Mustafa,

    I am working on to change my all the logic to AES. When I send the first authentication command it gives AE. I know default cryptography is TDES. But I need to know how to change it to AES both PICC keys and Application keys. Can you please advice me to start authentication work with AES.

    this is the commands and responces.

    ->aa00
    <-ae

    Regards
    Amila

  • Amila

    Hi

    I have problem with the AES authentication. I have listed below output.

    PICC Challenge : c5 53 7c 8e ff fc c7 e1 52 c2 78 31 af d3 83 ba
    RND_A : 23 47 c1 55 7f 80 70 7a bd ef 86 bf 9d 96 5c a7
    RND_B’ : a0 35 3a 7d 29 47 d8 bb c6 ad 6f b5 2f ca 84 1e
    RND_A + RND_B’ : 23 47 c1 55 7f 80 70 7a bd ef 86 bf 9d 96 5c a7 a0 35 3a 7d 29 47 d8 bb c6 ad 6f b5 2f ca 84 1e

    Enciphered(RND_A + RND_B’) : 4f 32 f6 d2 ff af d9 f1 41 fd 33 b0 cb ab 70 50 9d 63 e8 a8 a1 b6 87 b7 4e 2e 11 71 fc 38 e4 ef

    I know problem is in the last enciphering (RND_A + RND_B’). Can someone advice me to overcome this issue.

    Regards
    Amila

  • Amila

    Hi Meph,

    Yes. Its FF not EF, I don’t how it happened, I copy and pasted it.

  • Amila

    Hi Meph/Mustafa

    AES authentication is succeeded. Now I am working on writing data to standard file with ciphered. In that case I couldn’t find a crc32 implementation yet. Can you please advice me to overcome this issue ?

    Thanks & Regards
    Amila

    • Meph

      I used the Java crc32 method. But you have to prepare the result to get the result the Card expects. If you use Java i could Show you my Code which works. (und wenn du (besser) deutsch sprichst kann ich auch gerne auf deutsch Antworten;) )

      • Amila

        Hi Meph,

        Thank you very much for the quick response.
        Yes, I am using java for my application, If you can show the method it’ll be a great help.

        Regards
        Amila

      • Meph

        I used this method. Don’t know if there is a better way but it works:)

        public byte[] crc32(byte[] input) {
        byte[] ret = new byte[4];
        CRC32 checksum = new CRC32();
        checksum.update(input);
        checksum.getValue();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        try {
        dos.writeLong(checksum.getValue());
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        byte[] crc32 = bos.toByteArray();
        for(int i=0;i3;i–){
        ret[j]=crc32[i];
        j++;
        }
        return ret;
        }

      • Marek

        function _CRC32(Buffer : array of byte; Offset,Length : word) : cardinal;
        var crc,poly,bit: cardinal;
        i,j : word;
        begin
        crc:=$ffffffff;
        poly:=$EDB88320;

        for i:=Offset to (Offset+Length-1) do
        begin
        crc:=crc xor cardinal(Buffer[i]);
        for j:=1 to 8 do
        begin
        bit:=crc and $00000001;
        crc:=crc shr 1;
        if (bit=1) then crc:=crc xor poly;
        end;
        end;

        _CRC32:=crc;

        end;

        This is CRC32 function from my DesFireAES API in Delphi. Works perfectly.

  • Amila

    Hi Meph,

    In the given source code, I think something is wrong on the following line

    for(int i=0;i3;i–)

    Thanks
    Amila

  • Amila

    Hi Meph,

    I tried to calculate following sample data, But it seems i am getting wrong result.

    Message : 3D020000000F0000112233445566778899aabbccddeeff
    Getting : d7 f5 32 5a
    Expected : 28 0A CD A5

    Can you see something wrong here ?

    Regards
    Amila

    • Meph

      Its working fine in my program with the method code i posted before.
      I get the same result After using the Java crc32 method. You have to prepare this result (the two for-Blocks in my code). First you have to invert it so you get (FF FF FF FF) A5 CD 0A 28 and then you have to read it from right to left (but always two numbers together). Then you get the crc32 value like in your example from the nxp document.
      I Hope you understand my Description. I’m Sorry for my english;)

  • Amila

    Hi Meph,

    Again thank you very much for the support….
    I think something has gone wrong when copying the code in the text area, I am getting result as d7 f5 32 5a(Before invert). Can you please email the code snippet to me.. my email is godwinamila@gmail.com

    Regards
    Amila

  • ADAM TSL

    Hi I have an AID 818181 with FID 01,
    the create command as CA2020200F01.
    Create File ID CD0100EEEE100000

    i have problem using Delete Application Command :
    DA202020 , it give me 7E (length Error) after master key authentication successful.

    Please advice.

  • ADAM TSL

    Can anyone share with me what is the default Key 01 if i have create the application ID of having two authentication key 0F 02 where the access right is 1111.

    I Always face 1E (Integrity Error)

    Thx in advance.

    • Amila

      Hi ADAM TSL,

      its 0x00,0x00…… (24 0s)

      Regards
      Amila

      • ADAM TSL

        Hi Amila,
        Thx for your feed back, i still struggling on the change key with all zero for Desfire Ev1 8K. Can you give some pointer.

        9A BF 4D 6C EA 77 5E D4 – RndB
        87 0C CB EE 0B CC 77 97 – RndA

        session key after 0a00 =
        87 0C CB EE 9A BF 4D 6C 0B CC 77 97 EA 77 5E D4

        session key 8 bytes (Des)
        -> 87 0C CB EE 9A BF 4D 6C

        new key = 0C CD C6 5D D5 D8 7D 11 11 11 11 11 11 11 11 11
        new key CRC16 = 00 7A

        b1 – 0C CD C6 5D D5 D8 7D 11
        b2 – 11 11 11 11 11 11 11 11
        b3 – 00 7A 00 00 00 00 00 00

        R1 (b1 Xor Iv) – 0C CD C6 5D D5 D8 7D 11
        R2 – des dec(r1) – AC FC 24 47 70 4A 62 FC *
        R3 – r2 xor b2 – BD ED 35 56 61 5B 73 ED
        r4 – des dec(r3) – 9E E1 17 EE 75 97 1F 10 *
        r5 – r4 xor b3 – 9E 9B 17 EE 75 97 1F 10
        r6 – des dec(r5) – 83 2D 6F 03 F8 38 00 DC *

        c401ACFC2447704A62FC9EE117EE75971F10832D6F03 F83800DC

        error 1E

      • Amila

        Hi ADAM TSL,

        Can you confirm the last command, because it should be
        c4 00 ac fc 24 47 70 4a 62 fc 9e e1 17 ee 75 97 1f 10 83 2d 6f 03 f8 38 00 dc

        Regards
        Amila

  • ADAM TSL

    HI Amila,

    The crypto data

    ac fc 24 47 70 4a 62 fc 9e e1 17 ee 75 97 1f 10 83 2d 6f 03 f8 38 00 dc

    is correct but i want to change key no 1, the session key is from authenticating with key 0A00.

    I’m referring to ChangeKey Command Example in Native TDES.
    case 1 : key number to b change key number for current authenticated session.

    regards,

  • Mustafa Moripek

    Hi ADAM TSL,
    in case the key number you use for authentication is different from the key number to be changed and change key key is set to a value not equal to 0X0E you have to generate the deciphered key data like follows:
    The new key and the current key are bitwise Xored (16 byte).CRC (2 byte) is calculated over the Xored data and appended at the end.Additionally a CRC (2 byte) of the new key is appended and after padding of zeroes (4 byte) DES/3DES deciphering operation is performed on the whole data.The three cryptogram blocks are chained using CBC send mode.
    Good luck

    Mustafa Moripek

  • Amila

    Hi Mustafa,

    I have a problem with Desfire Diversification, I don’t have NXP SAM AV2, I am trying to implement all the cryptographic operations including diversification in software level. The Desfire Card I am communicating with is working with real hardware SAM but not with my software SAM. Can u verify my following output,

    Key Diversification
    ————————————–
    Diversification Input : 00 00 00 02 00 90 00 00
    Key : B8 FB 8F 51 A3 EF C8 8F 41 2C 23 96 DD 59 45 A4
    Diversified Key : B8 FA F9 86 E5 C2 3F A7 C3 C5 4C 3E A2 B7 7D F4

    DESFIRE Authentication
    ————————————–
    Application Key : B8 FA F9 86 E5 C2 3F A7 C3 C5 4C 3E A2 B7 7D F4

    -> 5A 00 00 01
    0A 00
    AF C9 1F CB 60 DE 47 71 70 CE DE EC E4 D9 6A 95 D3
    <- AE

    Thanks & Regards
    Amila

    • Amila

      RANDOM_B : DC EF B2 52 48 6A 15 A4
      RANDOM_A : 01 01 02 03 04 05 06 07

    • Marek

      Look for NXP document AN10922 in google. This document is public and describe in details proper diversification process (compatible with SAM) for various cards. You will find there also some examples so you can test your code.

      • Amila

        Hi Mark,

        Thanks for the response. I actually followed that document, I have a doubt that I am doing something wrong,
        Please see input and output of my diversification algorithm.

        Key : B8 FB 8F 51 A3 EF C8 8F 41 2C 23 96 DD 59 45 A4
        INPUT : 00 00 00 02 00 90 00 00
        Diversified Key :B8 FA F9 86 E5 C2 3F A7 C3 C5 4C 3E A2 B7 7D F4

        Thanks & Regards
        Amila

      • Marek

        That my results:

        Master Key: B8 FB 8F 51 A3 EF C8 8F 41 2C 23 96 DD 59 45 A4
        DivInput: 00 00 00 02 00 90 00 00
        ———-
        Div Key: 1D 24 26 45 4A CF 8E 9F D3 73 CE 15 E3 73 20 38

        Did you try to test your program with the example from AN10922??

  • Amila

    Hi Marek,

    I tried your output, its not working….

    Regards
    Amila

  • Ionut P.

    Hello ridrix,
    I found your forum very interesting and helpful.
    Unfortunately we are working with Elatecs TWN3 Mifare NFC transponder that offers DESFire cards support.
    The support we got from Elatecs developers they stated that the communication with DESFire cards is done using this syntax:
    t0F
    data is created using ISO14443-4 protocol frame and that we have to place the DESFire protocol data into the INF-field using I-Blocks.

    Could you please provide us with an example of how we could authenticate? We would greatly appreciate it.

  • Christina Szabo

    Hello everyone.
    Does anyone have a java function to ENCIPHER/DECIPHER?

    I have done this:

    byte[] input = is the PICC reply after A0 00
    byte[] masterKeyBytes = “00000000”.getBytes();
    byte[] ivBytes = “00000000”.getBytes();
    Cipher cipher = Cipher.getInstance(“DES/CBC/NoPadding”);
    Key encryptionKey = new SecretKeySpec(masterKeyBytes, “DES”);
    cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));
    bytes[] plainText = cipher.doFinal(input);

    But i always get strange results… and i cant figure out why. I would love some points how to fix it.
    Exemple how my decryption looks like:
    i get the input:
    AF EA 18 DE FF 52 0E CD
    And after deciphering its: 43 DA 7C 69 DE 5F D0 6F
    Is that correct?

    Thank you very much

  • shiv

    Hello i am new here, Please tell me How to load an application on desfire card?now i am using SCM Microsystem’s Card Reader to communicate with the desifre card.
    i want to load a small C code on the card for encryption.
    and also provide the link for desfire memory organization..
    thanks in Advance..

  • shiv

    How to Load an application on DESfire card. Now I am using SCM Microsystem’s Card Reader to communicate with DESFire Card..

    • Amila

      Hi shiv,

      In Desfire, you can’t load application like in smart card, Its sort of a stored value card, you only can create application in the card it self by sending a command. Read the specs carefully.

      Regards
      Amila

  • Amila

    Hi.

    Does anyone familiar with the NXP SAM AV1. I have few issues with SAM_AuthenticateHost

    Regards
    Amila

  • Mustafa Moripek

    Hi Amila ,
    what is the issue?
    Mustafa

    • Amila

      Hi Mustafa,

      I am trying to do the SAM_AuthenticateHost. In that case second command is getting failed with 90 1E (Correct Execution. Authentication failed)
      this is command and responses

      -> 80 A4 00 00 02 00 00 00
      80 A4 00 00 10 04 24 4E 95 C5 A5 F3 0A 1B A9 00 74 26 19 0E F7 00
      <- 90 1E

      SAM KEY : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

      Regards
      Amila

  • Amila

    Hi Mustafa.

    Data is getting missed in this editor. Please use this

    -> 80 A4 00 00 02 00 00 00
    80 A4 00 00 10 04 24 4E 95 C5 A5 F3 0A 1B A9 00 74 26 19 0E F7 00
    <- 90 1E

    SAM KEY : 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00, 0×00

    Regards
    Amila

  • Amila

    Hi Mustafa.

    Again

    Enk(RANDOM_B) : 4e 74 06 d5 c5 92 af f7
    RANDOM_B : d3 1d 1f 84 5b 22 96 2c
    RANDOM_B’ : 1d 1f 84 5b 22 96 2c d3
    Enciphhered Data1 : 04 24 4e 95 c5 a5 f3 0a
    enkno(RANDOMA + RANDOMB’) : 04 24 4e 95 c5 a5 f3 0a 1b a9 00 74 26 19 0e f7

  • Mustafa Moripek

    Hi Amila,
    can you please write the communication in the following format:
    -> 80 A4 00 00 02 00 00 00
    80 A4 00 00 10 ekNo(RndA+RndB’) 00
    <- 90 1E
    Mustafa

  • Mustafa Moripek

    Hi Amila,
    can you please write the communication in the following format:
    -> 80 A4 00 00 02 00 00 00
    -> 80 A4 00 00 10 ekNo(RndA+RndB’) 00
    <- 90 1E
    Mustafa

    • Amila

      Hi Mustafa,

      See below the communication as you requested.

      -> 80 A4 00 00 02 00 00 00
      80 A4 00 00 10 04 24 4E 95 C5 A5 F3 0A 3A D5 01 BF CB 0B 2A 8F 00
      <- 90 1E

      RANDOM_A : 05 3F 41 DA 27 26 E4 29
      SAM KEY : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  • Mustafa Moripek

    Hi Amila,
    can you please write the communication in the following format:
    -> 80 A4 00 00 02 00 00 00
    80 A4 00 00 10 ekNo(RndA+RndB’) 00
    <- 90 1E
    Mustafa

  • Amila

    Hi Mustafa

    -> 80 A4 00 00 02 00 00 00
    80 A4 00 00 10 04 24 4E 95 C5 A5 F3 0A 3A D5 01 BF CB 0B 2A 8F 00
    <- 90 1E

    RANDOM_A : 05 3F 41 DA 27 26 E4 29
    SAM KEY : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

  • Amila

    Hi Mustafa,

    Something wrong with the wordpress. Can you give your email I can send the output

    Regards
    Amila

  • Mustafa Moripek

    Hi Amila ,
    evrything seems to be O.K.Are sure you are using single DES
    for decryption,for the key is all zero.
    Mustafa

    • Amila

      Hi Mustafa.

      Yes. Probably the key I am using wrong. I got the key from the card provider. Let me check that.
      Thank you very much for the quick response.

      Regards
      Amila

  • Mustafa Moripek

    Good Luck
    Mustafa

  • Gabriel

    Hi,

    I am newbie for smart card but I’ve successfully authenticated using DES. Now I am trying for AES, and when I request Random B(16 bytes) from PICC, it gives me AE. The card is a new blank card with default keys and settings.
    ->aa00
    0a00
    1a00
    <-AF871081A8BDB379E1

    Even thou I don't know the 1a00 command, I just used 0a00 for requesting Random B.

    Thanks,

  • Gabriel

    Hi all,
    I am having a problem with PICC master key changing, could anyone check and point out what my problem is?
    https://www.dropbox.com/s/wfvpy795tsbyjtz/change%20key%20log.txt
    Thanks for the attention.

  • jorge

    hi
    this is jorge .
    i am able to do authentication .
    but while creating file it is returning 0x0e
    i created only one aid

  • Mustafa Moripek

    Hi Gabriel,
    Error code 1E means CRC error.I have checked your CRC, it is
    correct.I have checked your data with the session key you have
    given,your calculating of CBC parts are all correct.The only issue
    can be tahat your session key is not correct and the PICC calculates
    wrong CRC.
    Check your code part which builds the session key.
    Good luck.
    Mustafa

  • Gabriel

    Hi Mustafa,
    Thank you for the prompt help and verification of my result. I will check my code per suggested and keep you informed.
    Thanks,
    Gabriel

  • ChrisKing

    Hi All,
    I have a problem about change key.
    Old Key is “00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00”
    New Key is “00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00”
    Following is my flow chart

    PCD: 0A 00 // Authenticate
    PICC: AF 73 F4 D5 28 26 F3 38 31

    RndA is “00 01 02 03 04 05 06 07”
    RndB is “D1 A5 6D 00 6D B7 DF 5E”

    PCD: AF 49 1E 89 0D E9 AC E9 32 5F 96 79 AF 60 54 F4 8C
    PICC:00 B7 D1 DA 7C E0 DD 98 6B

    The DES_SessionKey is “00 01 02 03 D1 A5 6D 00”
    The 3DES_SessionKey is “00 01 02 03 D1 A5 6D 00 04 05 06 07 6D B7 DF 5E”

    I calculated CRC16 then change key key data is
    C4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 37 49 00 00 00 00 00 00

    Then do decipher use DES_SessionKey
    C4 00 98 37 36 08 51 1D 96 4C 98 37 36 08 51 1D 96 4C 3A D7 5E 3E 34 EB E3 2E

    But I got the 0x1E,I don’t know where is wrong?
    Can help me please?

    • Gabriel

      Hi ChrisKing,
      Search keyword “March 7th, 2012 at 11:57” in this blog, this might help you out.
      Good luck,
      Gabriel

    • Ali

      Hi ChrisKing ,
      If you don not get your answer yet tell me.
      May be i can help you.
      Ali

    • Sergio

      Hi ChrisKing!
      I’m sorry I haven’t answer for your question because I can’t authenticate.
      I found data from your comment quite good and test it in my code, but I have smth wrong with 2nd PCD message, can You waste some of your time and help me?
      You wrote:
      “PCD: 0A 00 // Authenticate
      PICC: AF 73 F4 D5 28 26 F3 38 31
      RndA is “00 01 02 03 04 05 06 07″
      RndB is “D1 A5 6D 00 6D B7 DF 5E”
      PCD: AF 49 1E 89 0D E9 AC E9 32 5F 96 79 AF 60 54 F4 8C
      PICC:00 B7 D1 DA 7C E0 DD 98 6B”

      I tried the same and here what I get:
      encryptedRandB = 0x73, 0xF4, 0xD5, 0x28, 0x26, 0xF3, 0x38, 0x31 // I hardcoded It
      decryptedRandB = 0xD1, 0xA5, 0x6D, 0x00, 0x6D, 0xB7, 0xDF, 0x5E // works fine like in your app
      randA = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 // same as in your app
      arrayTwo = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xA5, 0x6D, 0x00, 0x6D, 0xB7, 0xDF, 0x5E, 0xD1 // my randA + shifted decryptedRandB
      decryptedArrayTwo = 0x49, 0x1E, 0x89, 0x0D, 0xE9, 0xAC, 0xE9, 0x32, 0xED, 0x92, 0x31, 0xD8, 0xEE, 0x3D, 0x1C, 0xE1 // Here is error! 1st 8bytes are the same as yours, but second 8 are not.
      Where I made mistake, help please? I do it in DECRYPT SEND MODE (1st step randA XOR IV that is all ’00’, then Decrypt it; 2nd step shifted decryptedRandB XOR IV that is decrypted randA from 1st step, then Decrypt it; 3rd step concatenate this arrays)
      Seems like mistake in 2nd step, but I can’t find it.
      Thank you very much!

  • Gabriel

    Hi Mustafa,
    Thanks a lot for your suggestion that saved a lot of my time and I got it right now. As you mentioned its my code block that build wrong session key.
    Thanks,
    Gabriel

    • Bruno Bertechini

      Hi Gabriel,

      How did you solved the session key problem to change the master key to AES ? Im using C# and I am able to change to 3DES. But now im preparing to move to AES (restarting this project after 1 year or so 😉 )

      Would you mind to share your changeKey code from Blank to AES ?

      Thanks a lot!

      Bruno

  • jorge

    after authentication i am creating aid ..i have problem in creating data file it is giving 0x0e ..can any one help me

    • Mustafa Moripek

      Hi Jorge,
      your file length must be to high.The 0X0E means out of eeprom.
      You get this error message when the file length (the last three
      bytes ) in your command is to high.
      Good luck…
      Mustafa

  • Gabriel

    Hi Mustafa,
    I now have successfully changed default DES key to TDES keys and AES keys. Although DES and TDES authentication is alright, I have problem in AES authentication. I did refer to previous QnA posted about AES authentication but still in vain. Could you please point out what I did wrong for this authentication.

    https://www.dropbox.com/s/mrnpc1mol44q8tm/AES%20change%20key%20log.txt

    • Gabriel

      Hi Mustafa,
      Its ok now. I could authenticate with AES key. I mistakenly used decryption instead of encryption.
      Thanks,
      Gabriel

  • Amila

    Hi

    Does some one implemented NXP Desfire TDES Key Diversification(SAM AV1) using java or any other language ?

    Thanks
    Amila

    • Amila

      Hi All,

      I have listed below the Input and output of my programme, can someone please validate this ?

      Key : 30 9F 44 6D 01 2F D8 EC 3C 93 78 57 BB 1F 7B AC
      INPUT : 00 00 90 00 02 00 00 00
      Key version : 01
      After Diversification : e1 90 2b 6f 7a 31 c6 9d a8 f7 79 90 78 7a fe 28
      Replace Key version : e0 90 2a 6e 7a 30 c6 9d a8 f7 79 90 78 7a fe 28

      Regards
      Amila

  • Gabriel

    Hi,
    Could anyone please guide me to calculate MAC and CMAC?? I tried with some test vectors but ended up with unexpected results…
    https://www.dropbox.com/s/t04ahd2hg1iiqsu/mac_calc.txt
    Thanks,
    Gabriel

  • Amila

    Hi Mustafa

    I have stucked in Desfire Diversification can you give me some help to sort out the issue ?

    Regards
    Amila

  • Roy

    anyone know is there any method can do XOR before DES ?
    I tried following code:
    byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00 };
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    SecretKey s = new SecretKeySpec(key, Algorithm.TEDE.toString());
    Cipher cipher = Cipher.getInstance(“DESede/CBC/NoPadding”, “BC”);
    cipher.init(Cipher.DECRYPT_MODE, s, ivParameterSpec);
    byte[] deciphered_data = cipher.doFinal(enciphered_data);
    It seems to do XOR after DES

    • Adam Laurie

      Just do the XOR yourself and call the DES routine with a NULL IV every time. Use the crypted output of each block as the source data for the XOR of the next block (i.e. you are effectively maintaining your own IV).

      cheers, Adam

  • andreaciardulli

    Hi All,

    Sorry Mustafa,
    can you help me?
    I try to write an autentication/change key program in java for DesFire 8k
    EV1

    I successfull change my PICC key from
    oldKey = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    to
    newKey =0A 0B 0C 0D 0E 0F 0A 0B 2F CB F6 1B DF A7 F5 9C

    so now i want to go back to old key
    to do this now i have to use 3Des enc/decription for autenticate key 0x00 is it right??

    so i select AID 0x00
    APDU >>>: 90 5A 00 00 03 00 00 00 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 45 25 1E 20 33 BD 31 60 F5 89 85 42 3B 98 30 5E 00
    APDU <<<: 91 AE

    Autentication Error
    is my 3DES right?

    • Andrea

      Copy and paste problem
      i try to write again

      just an information i try autentication on a brand new picc
      using key 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
      all ok
      but i achive the same results using key
      01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01

      is it normal?

      • Lewis

        Yes. In 3DES, the least significant bit is not used for encryption/decryption. It is used as a parity bit

  • Andrea

    I made another try
    select picc
    autenticate picc 0x00 … 0x00
    format picc (so i can repeat my test without so much work)
    i create an app 01
    selecte 01 app
    autenticate with key 0x00
    change key to 0xff .. 0xff
    autenticate again with key 0xff
    changed back to 0x00

    enc/dec used allways des

    i repeat the above test using 0x02 …0x02 key insted of 0xff .. 0xff
    but when i try to autenticate again with key 0x02 i cant autenticate

    the dump of my test is here
    https://dl.dropbox.com/u/58962371/picc.txt

    i also try to copy/paste it

    commandSELECT_PICC —————-
    APDU >>>: 90 5A 00 00 03 00 00 00 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 A6 57 37 A3 8B 5F E8 56 00
    APDU <<>>: 90 FC 00 00 00
    APDU <<>>: 90 CA 00 00 05 01 00 00 0F 01 00
    APDU <<>>: 90 5A 00 00 03 01 00 00 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 57 56 3F 77 4C FE E7 60 00
    APDU <<>>: 90 C4 00 00 19 00 48 2A C1 3C 95 84 59 61 1D B8 92 5C F7 93 AC 07 98 ED 39 11 3D DF FD 56 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 CA AA AF 4D EA F1 DB AE E5 02 E8 DF 32 65 44 71 00
    APDU <<>>: 90 C4 00 00 19 00 3C 37 A5 45 D4 CE 35 0C DD B5 15 91 54 4F C9 11 5D E8 6E 74 AA 64 E8 38 00
    APDU <<>>: 90 5A 00 00 03 00 00 00 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 AA 39 C4 87 D0 7E 90 B5 00
    APDU <<>>: 90 FC 00 00 00
    APDU <<>>: 90 CA 00 00 05 01 00 00 0F 01 00
    APDU <<>>: 90 5A 00 00 03 01 00 00 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 48 28 19 77 C0 D9 C6 E8 00
    APDU <<>>: 90 C4 00 00 19 00 20 EE B7 40 D8 DB D2 FB 0E E0 B0 41 AB 1E 43 CB 70 B5 DC DE 61 2A 41 86 00
    APDU <<>>: 90 0A 00 00 01 00 00
    APDU <<>>: 90 AF 00 00 10 C4 AF 51 BD 0A 0F 8A DD 03 EA 58 A9 C5 BD E9 77 00
    APDU <<<: 91 AE

    • Andrea

      commandSELECT_PICC —————-
      APDU -> 90 5A 00 00 03 00 00 00 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 A6 57 37 A3 8B 5F E8 56 00
      APDU 90 FC 00 00 00
      APDU 90 CA 00 00 05 01 00 00 0F 01 00
      APDU 90 5A 00 00 03 01 00 00 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 57 56 3F 77 4C FE E7 60 00
      APDU 90 C4 00 00 19 00 48 2A C1 3C 95 84 59 61 1D B8 92 5C F7 93 AC 07 98 ED 39 11 3D DF FD 56 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 CA AA AF 4D EA F1 DB AE E5 02 E8 DF 32 65 44 71 00
      APDU 90 C4 00 00 19 00 3C 37 A5 45 D4 CE 35 0C DD B5 15 91 54 4F C9 11 5D E8 6E 74 AA 64 E8 38 00
      APDU 90 5A 00 00 03 00 00 00 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 AA 39 C4 87 D0 7E 90 B5 00
      APDU 90 FC 00 00 00
      APDU 90 CA 00 00 05 01 00 00 0F 01 00
      APDU 90 5A 00 00 03 01 00 00 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 8C A6 4D E9 C1 B1 23 A7 48 28 19 77 C0 D9 C6 E8 00
      APDU 90 C4 00 00 19 00 20 EE B7 40 D8 DB D2 FB 0E E0 B0 41 AB 1E 43 CB 70 B5 DC DE 61 2A 41 86 00
      APDU 90 0A 00 00 01 00 00
      APDU 90 AF 00 00 10 C4 AF 51 BD 0A 0F 8A DD 03 EA 58 A9 C5 BD E9 77 00
      APDU <- 91 AE

      • Mustafa Moripek

        Hi Andrea,
        there is something wrong with encrypting RndA(all zeroes).
        I have checked your data:
        When encrypting RndA with the keys all FF or all 00 I get
        exact the same numbers like you.But when I decrypt
        RndA with the key all 02 I get following numbers:
        3D 8A 71 E3 25 CE C2 96.
        I hope this will help you to find the issue,good luck.
        Mustafa

      • Andreandrea

        So my problem can bee my des/3des encryption i have to check my code.
        can some one suggest me a java implementation for des/3des so i can check ?

  • Folkert van Heusden

    Does anyone know what statuscode ‘0x3f’ means?
    Could not find it in the specifications (http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf).

  • Andreandrea

    Hi Again Mustafa
    I tried again using key twoKey16 (0x02 .. 0x02)
    encrypting eightZero = (0x00..0x00)
    encry = C4 AF 51 BD 0A 0F 8A DD

    if i use the same key and the same input but the decrypt algo
    it get me
    decry = 8A 71 E3 25 CE C2 96

    is it right?

    • Mustafa Moripek

      Hi Andrea,
      only the first number (3D) is missing.
      The encryption during communication between PCD and PICC
      works as follows : PCD always decrypts the data and the PICC
      always encrypts.
      Mustafa

  • Andreandrea

    sorry copy and paste error
    decry = 3D 8A 71 E3 25 CE C2 96
    so my des algo works fine?

  • Adam Laurie

    Yes, 3D8A71E325CEC296 is the correct output of 0000000000000000 decrypted with 0202020202020202.

  • Gabriel

    Hi Mustafa,
    Could you guide me to get session key when the randomA and randomB has 16 bytes each for AES authentication/operation.
    Regards,
    Gabriel

    • Mustafa Moripek

      Hi Gabriel,
      the authentication with AES keys are similar to authentication
      with DES/3DES.You have to use command code 0XAA instead of
      0X0A.For encryption you have to use AES algorithm.
      You must use a tag with chip MF 3 IC D 41 ,tags with chip
      MF 3 IC D 40 don’t support AES keys.
      Good Luck
      Mustafa

  • Gabriel

    Hi Mustafa,
    Sorry for my late reply (seems notification is not working properly).
    The tag is with MF3ICD41, I can send the command 0xaa and get response(16 bytes rndB). What I am not clear is building session key. For DES, the session key is build with first nibble of rndA and first nibble of randB; for TDES, its first nibble of rndA+ first nibble of randB+second nibble of rndA+ second nibble of rndB. For AES, its randA and rndB is 16 bytes each, and do not know which nibble to manipulate.
    Thanks and best regards,
    Gabriel

    • Mustafa Moripek

      Hi Gabriel,
      You build the session key as follows:
      Session Key = RndA byte 0..3 + RndB byte 0..3 +
      RndA byte 12..15 + RndB byte 12..15
      Good luck
      Mustafa

  • Gabriel

    Hi Mustafa,
    Thank you so much for your kind info and guidance. I got it working now.
    Best Regards,
    Gabriel

  • Amila

    Hi Mustafa,

    Is it possible to get the key from Desfire SAM AV1 using some other authentication ?.

  • Tom

    Hi Mustafa,

    I have succesfully authenticate the card using 0x00….. default key using DES/CBC/NoPadding mode.. and its ok.. here i needs to generate MAC for command data 00112233445566778899AABBCCDD0000(with padding) using 16byte key A908E976D518D0B9AE1D7F7A04CB0154 with 3DES standard encryption.. For check the validity i use example NXP Desfire EV1 features and Hints spec…

    My java code :

    Cipher cipher = Cipher.getInstance(“DES/CBC/NoPadding”);

    DESKeySpec kspec = new DESKeySpec(key);
    SecretKeyFactory kfact = SecretKeyFactory.getInstance(“DES”);
    SecretKey key1 = kfact.generateSecret(kspec);

    IvParameterSpec IvSpec = new IvParameterSpec(ivzeros);
    cipher.init(Cipher.ENCRYPT_MODE, key1,IvSpec);
    res = cipher.doFinal(data);

    Bu the result i got is D78070B8294E6045DD3AB3C11E01769A

    According to the example it should be 8CF67F76B9CCD298874801630C759151 AND mac IS 87480163

  • Tom

    Hi Mustafa,

    Sorry, i have solved the problem…. The answer is use

    Cipher cipher = Cipher.getInstance(“DESede/CBC/NoPadding”);

    and the key should be K1K2K3 where K1=K3

    I have learn lot of desfire implementation related details from your comments.. Thank you very much…..

    Cheers,
    Tom

  • Tom

    Hi Mustafa,

    Can you help me in this matter….
    I have successfully authenticate card with key version 0x00(master key all zeros)
    Then i try simple commands including get Versions and settings.
    Now I need to create applications and files… For that i am trying to use key version 00 as application key(AMK).
    1 – Can i use CMK(Card Master Key) as Application master key..?
    2 – How can i add more than one key versions to cards for used with applications and files..?(eg. Key 1 for app1 file1 write and read…..)
    Please help me in this matter…..

    • Mustafa Moripek

      Hi Tom,
      these are defined within the key settings.Depending
      on the configuration of the application key settings
      and PICC master key settings you determin the
      behaviour of the desfire card.Let me explain you both
      the PICC master key settinds and application key
      settings.
      PICC Key settings:
      bit7(MSB)-bit4 RFU
      bit3 1 PICC master key allowed if authenticated
      with PICC master key
      0 configuration no more changeable
      bit2 1 Create appl. is permitted without authentication,
      delete application requires authentication
      with PICC master key
      0 Create and delete application is permitted
      only with PICC master key authentication
      bit1 1 GetApplicationID and GetKeySettings command
      without authentication
      0 GetApplicationID and GetKeySettings command
      after succesfully authentication with PICC
      master key
      bit0 1 PICC Master key changeable
      0 PICC master key nomore changeable
      Application Master Key settings:
      bit7(MSB) -bit4 Accessrights for changing the application keys
      0X0 Application master key authentication is
      neccessary for changing any key
      0X1..0XD Authentication with the given key is neccessary
      0XE Authentication with key to be changed is neccessary
      0XF All keys except application master key within tis
      application are not changeable
      bit2 1 Create/delete file without authentication
      0 Create/delete file only with application master key
      authentication.
      bit1 1 GetFileID,GetFileSettings and GetKeySettings
      without authentication
      0 The above mentioned commands after
      authentication with application master key
      bit0 1 Application master key changeable
      0 Application master key not changeable

      I hope these information will help you.
      Mustafa

      • Tom

        Hi Mustafa,

        Thanks for you quick reply for me…
        I understand about key settings that you mentioned above post..
        Actually i need to know , suppose a card have 3 key versions
        0x00 – master key
        0x01 – some app key
        0x02 – another app key
        0x03 – key for some file inside above app

        What i need to know is….
        1 – How can i define key version 0x01(1) with its value… any command….??
        2 – When i change AMK(version 00) to version 0x01(another key) can i use above oxo1 for another application or file.. Are both key versions exists in the card(After key change) to use for another purpose.. ???
        Please help me…..

  • Mustafa Moripek

    Hi Tom,
    I think key versioning is not the right thing you are looking for.
    Please download the application manual AN10922 of NXP
    to read the details of key versioning.
    You can create different keys for each application but you access
    all the files in the same application with the same application
    master key.
    Mustafa

    • Tom

      Hi Mustafa,

      I think i have found the answer for my question…. I can continue my development.. Thanks.. I have another small question.
      Suppose we use
      –> 6a
      <– 00 00 80 57 01 80 57

      So the application ID's are 578000 and 578001.. So why Desfire always send the results like that..? (LSB first and MSB last)..

      Thank you very much for the instructions…

      Tom

  • Mustafa Moripek

    Hi Tom,
    this how the producers have made it .You cannot change it.
    Mustafa

  • justin atom

    any one can pls explain how to calculate crc32 in c

    • Tom

      Hi justin,
      You can understand the procedure in Java language…

      Data – byte[] which include data to calculate crc32

      Checksum checksum = new CRC32();
      checksum.update(Data, 0, Data.length);
      long _chv = checksum.getValue();
      long crc32 = ~_chv & 0x00000000FFFFFFFF;
      ByteBuffer crc32Buf = ByteBuffer.allocate(8);
      crc32Buf.order(ByteOrder.LITTLE_ENDIAN);
      return crc32Buf.putLong(crc32).array();

      You can convert this code structure to C.. I am not expert in C..
      Cheers,
      Tom

  • Vladica

    We have a task to send APDU command 90 60 00 00 00 and we get the answer 04 01 01 01 00 18 05 91 AF. This answer gives each Desfire card that is not personalized.
    We have Multi iso RF Reader, with RS232 interface.
    Dll functions in RFID READER DLL have features that communicate with the card in order to send commands and accepting responses (reader.RDR_DESFire command and reader.RDR_SendCommandGetData command). But when I send the required command, response card is its UID number, no what is expected. Do you have any examples about ways to communicate with Desfire EV1 card (initializacion, native APDU commands, extends native APDU commands…)and MULTI ISO READER?
    Or, maybe, you help mi directly, in java code..

  • Tom

    Hi Mustafa,

    I got two serious(for me) questions to get clarify.. Not from elementary desfire card level but from implementation level.

    1 – (Easy question) can we maintain file interconnection within same application inside desfire card…?(eg. one file used or update another file data inside same application)

    2- Can we introduce a PIN(in card side), to restrict card access(or to restrict file access) by validating user input pin(eg. from terminal side) with original PIN inside the card….? And How..? Are any predefined structure(like OwnerPIN() in Java Card) for PIN management inside Desfire Card..?

    Can you give me some ideas …

    Thank you
    Tom

    • Mustafa Moripek

      Hi Tom,
      I try to answer your questions.
      1.You can interconnect different files in the same application.
      In such a case I would configure the file settings in a way
      that you need not to authenticate each time you want to access
      any file.You only authenticate during selecting of the application.
      2.You can create an aplication and in it a file where you can store
      a PIN.The reader can read this number and compares it
      with a keyed in number.Only on match of both numbers it
      allows to proceed.
      I hope this information helps you
      Mustafa

      • Tom

        Hi Mustafa..

        Thank you very much for your answers and can you clarify me the following situation…

        According to your provided procedure for implement PIN inside card do we need to provide restrictions in terminal level code or can we introduce some mechanism(inside card) to get access to the desired property of the card(eg.file access) when once we validate PIN with terminal input.

        Can you help me in this matter…
        Thank You
        Tom

  • Mustafa Moripek

    Hi Tom,
    there is no mechanism inside the card.You have to handle
    it on the terminal side.
    Mustafa

  • Andy

    Hi Mustafa…

    I have 2 questions for you.. Can you help me on them…

    1 – I use Desfire EV1 card and i successfully authenticate the card using Desfire Native DES mode.
    Master Key : 0000000000000000(8-byte)

    Random A : 4112011A11120C22
    Random B : B60E3A8DB96343DA
    Session Key : 4112011AB60E3A8D

    I use single DES algorithm. In Java “DES/CBC/NoPadding” format. What i need to know is when i change master key can i use 16byte long new key?(i have existing 8byte long mater key inside card)

    2 – When i use Triple DES for one session inside a card with a particular key, can i use same key and different algorithm to authenticate card in next session…?

    Please help me in above questions…
    Thanks.

    • Mustafa Moripek

      Hi Andy,
      1-When authenticating with a Desfire card you have to use
      the key which is inside the card.If you want to use another
      key you have to change the key of the card with the
      change key command.
      If you want use 16 byte key you must pay attention which
      algorithm you want to use.If you want to use single DES
      then you have to make the first eight byte of the key
      equal to the second eight byte.Otherwise you have to
      use triple DES for encryption.
      2-If you mean the card master key or application key,yes
      you can use them each time you authenticate until you
      change the key.But if you mean the session key ,it is
      used only for one session.During authentication process
      a session key is calculated and used for each encrypted
      communication. In the next session a new session key will
      be calculated.

      Mustafa

  • Tom

    Hi Mustafa,

    So far i did lot of things in Desfire Cards with the help of this blog.. It seems again i need some help from you mustafa…

    My Problem,

    I Have succesfully create an application with key settings 0x0F0E and change its original key succesfully.

    Basic Key = 0x0000000000000000
    New Key = 0x000102030405060708090A0B0C0D0E0F
    Existing Key VERSION of Application = 0x00

    Then i need add new keys to application.(key number 0x01, 0x02.. etc)

    Existing Key = 0x000102030405060708090A0B0C0D0E0F
    New Key = 0x001122334455667708090A0B0C0D0E0F
    New Key Version = 0x01

    >>900A0000010000
    <>success
    Triple DES Session Key : 4112011A3EE15CAC11120C2277B0A15F

    Then i Xor existing key with new key
    (0x000102030405060708090A0B0C0D0E0F^0x001122334455667708090A0B0C0D0E0F)=0x00102030405060700000000000000000

    Generate CRC’s and add then. Finally padding
    001020304050607000000000000000003C597CE500000000

    Encrypt them in Native triple des send mode with session key
    E2DD1C36C12901149BFC12F0A4DB211D1455F4840C1FCF55

    >>90C400001901E2DD1C36C12901149BFC12F0A4DB211D1455F4840C1FCF5500
    <<911E

    It is said the application can handle 14 keys.. so i am going to add new key to used for application.. Simply i am trying to do that.. But fails… Can you help me…

    Thanks
    Tom

    • Mustafa Moripek

      Hi Tom ,
      i think the issue is you try to change a new key in the way of changing an existing key.The key number 0X01 is a new key
      and is 0X0000000000000000.So you have act accordingly.like you have changed the key number 0X00.
      Mustafa

      • Tom

        Hi Mustafa,

        I solved the problem.. Thank you very much.. The point i miss is, when i create application with 14 keys, default all zero keys are filled to all new positions… Then i can solve the problem…
        Thanks again..

        Tom

  • Gabriel

    Hi Mustafa,
    I tried to change AES key of PICC master key and I receive 001E Error. Could you please help guide me which part has the problem. I inverted the CRC32 but still getting the same error.
    https://dl.dropbox.com/u/98005924/Change_AES_Key.txt
    Thanks and best regards,
    Gabriel

  • Fernando

    Hi….
    I did the change key command successfully yesterday. Thank to this ridrix and you all. But, now i’m having big problem. All authentication steps were OK before i changed the key yesterday.
    I changed the default key (0x00 16bytes) of key 0 to 0x11 11 11 11 22 22 22 22 33 33 33 33 44 44 44 44 after I selected AID 00 00 00. Then, my authentication got error which is 0xAE. Last time i used default key (0x00 8bytes) (using single DES) in every authentication and everything was fine. But now I can’t delete AID or format the card because I can’t authenticate with AID 00 00 00. Here is how i did.

    First, i chose the AID 00 00 00. Then, I authenticate with key0. Then, the following shows how I make the change key command.
    “key data”=11 11 11 11 22 22 22 22 33 33 33 33 44 44 44 44 1C BC 00 00 00 00 00 00 (24 bytes) (16 bytes key+ 2 bytes CRC16+ zero padding)

    >Decrypt first 8 bytes of key data with 1st half of session key using CBC
    >>>decrypted value1 is the FIRST BLOCK

    >decrypted value1 (XOR) second 8 bytes of the key data
    >the result 8 bytes is decrypted with 1st half of session key using CBC
    >>>decrypted value2 is the SECOND BLOCK

    >decrypted value2 (XOR) third 8 bytes of the key data
    >the result 8 bytes is decrypted with 1st half of session key using CBC
    >>>decrypted value3 is the THIRD BLOCK

    Then, i sent the change key command like this
    >C4 00 + FIRST BLOCK + SECOND BLOCK + THIRD BLOCK

    Then, the cad replied 0x00 which mean successful.
    So, can someone tell me is change key command wrong? what is needed in authentication after change key?

    • Gabriel

      Hi Fernando,
      If PICC Default DES key(8 bytes) is changed to TDES (16 bytes key) or AES (16 bytes key), you may try request RandomB with command AA00 (for AES) and 0A00 or 1A00 (for TDES) for the new authentication process.
      Hope this help,
      Gabriel

      • Fernando

        Hi Gabriel,
        I can’t send “AA 00” and “1A 00” to request RndB, i got error code 1C which is illegal command code. “0A 00” is the one i’m using now and it can request RndB and when i send 16 bytes of RndA and RndB, i got AE (authentication error) :(((

    • Ali

      Hi Fernando ,
      Would you mind tell how get 1c bc for crc 16 (11 11 11 11 22 22 22 22 33 33 33 33 44 44 44 44 ) please?

  • Mustafa Moripek

    Hi Gabriel,
    I think the issue is the second byte 0X80.The command format for
    changing the key is:
    Command Code (0XC4),Key number(0X00…0X0D),decrypted key data.
    For you are trying to change the PICC master key the second byte
    has to be 0X00.
    Mustafa

    • Gabriel

      Hi Mustafa,
      Thanks for your suggestion. It still gives me same error(1E).Last time I changed PICC default master key(DES) to AES using command C4+80+deciphered key data. It is successful and I can authenticate. But cannot change existing AES to a new AES key.

      There I found one more problem. I created an application CA 12 34 56 0F 0E and tried to change its default key(DES) to AES using C4+00+deciphered key data, it changed to TDES key rather than AES. I think I am missing some points for this change. Could you please help?
      Thanks and Best Regards,
      Gabriel

      • Mustafa Moripek

        Hi Gabriel,
        I don’t know whether you have solved the problem allready but I want to give you some suggestions.
        1.I think you don’t need to exor the old key with the
        new one.This you do if the number of the key you
        change is different then the number you authenticate.
        In your case you are trying to change the master key,
        and therefore you authenticate with master key.
        2.You have to add one byte key version and CRC32
        calculated over the new key and padding.
        3.You have to chain the blocks using CBC send mode.
        Try these suggestions,I think you will be able to change
        the key.
        Good luck
        Mustafa

  • Gabriel

    Hi Fernando,
    Since PICC’s default DES has been changed to TDES, I think, you may need to use TDES encryption method with your current key TDES 16 bytes for authentication.
    TDES and DES authentication process is the same. Only encryption method differ.
    Good Luck,
    Gabriel

  • Fernando

    Hi, Gabriel. Thank for your explanation. I got my authentication working already. My authentication steps were wrong in the first place even though i authenticated successfully with my default key (0x00 16 bytes) last time. Now my authentication is OK even after i do change key.
    But now, i got a problem in changekey again. I could change the key if the KeyNo used for authentication s the SAME as the keyNo to be changed. But i could not change a key if the KeyNo used for authentication is DIFFERENT from the KeyNo to be changed (or) the ChangeKey key setting is set not equal to 0xE. The error code is 0x1E. It is mentioned in Desfire datasheet that two sets of CRC16 are supposed to append behind 16 bytes data. I don’t know how to do change key command if the KeyNo are different. You can look at my first comment (Nov 9th) if you wanna know about how i do change key.

    • Jesse Yang

      Hi Fernando,

      I have the same problem that after I changed the PICC master key, the authentication process failed. And I found that only when the former 8 bytes and the latter 8 bytes of the new key are different, the authentication process fails. Could you provide some information on how you solved this problem? I guess it should be the 3des decryption’s problem. Thanks very much!

  • Gabriel

    Hi Fernando,
    As I understand, the default key 16 zeros whose first 8 bytes zeros and last 8 bytes zeros are identical, you may use DES auth process(not TDES) to change to new key with 16 bytes whose first 8 bytes and second 8 bytes are different.
    Good luck,
    Gabriel

  • Gabriel

    Hi Mustafa,
    Thank you for your kind suggestions and attention. I haven’t yet solved that. I am confused with key versions. I checked the default key version it says 00, after I changed DES to TDES it says 55 and after I changed DES to AES it says 77. Should the command be C4+New AES Key+new AES key version+CRC32 of new AES key+ padding? And what should be the new AES key version in this case.
    Thanks and Best Regards,
    Gabriel

  • Gabriel

    Hi Mustafa,
    The log for change key process is
    https://dl.dropbox.com/u/98005924/aestoaeschangekey.txt
    Thanks

    • Mustafa Moripek

      Hi Gabriel,
      The change key command should look like:
      C4 + 00 (key number) + Encrypted data
      The data to encrypt should look like:
      0f0e0d0c0b0a09080706050403020100 (New Key)
      77 (Key Version) + 4Bytes CRC32 calculated over new key +
      Padding
      I hpoe this time you will succed.
      Mustafa

  • Gabriel

    Hi Mustafa,
    I am sorry to bother you again and again. I am still receiving the same 1E error. The log is https://dl.dropbox.com/u/98005924/aestoaeschangekey.txt
    Thanks and Best Regards,
    Gabriel

  • Mat

    Hi Mustafa,

    i have some questions about usage of Desfire 4K and SAM AV1 or SAM AV2. Can you comment to them please? i tried to select an application on SAM card. it responded with “6985” status words. it means “Conditions of use not satisfied”. i think i have to unlock it with Sam_AuthenticateHost . is it correct? What is the apdu command to do it? Actually i don’t know flow between SAM and Desfire Card to read/write data from DesfireCard. Could you explain it please? What does host mean exactly? does it refer to the contactless reader? i searched all of these issues but i couldn’t read data from desfire card yet.

    thanks in advance

  • Tom

    Hi Mustafa,

    I have new Desfire cards which have default key.. I can authenticate card using Native DES and success..
    But when i try to authenticate PICC using AES, it gives filloeing error.. Can u advice me in this matter..
    >>AA00
    <<91AE

    Thanks
    Tom

    • Mustafa Moripek

      Hi Tom,
      if the card, you are trying to authenticate,is a virgin
      card the default key is a DES/TDES key.First you have to
      change the key to an AES key then you can authenticate
      using AES.For this you have proceed as follows:
      Send following command to PICC: 0XC4 + 0X80 + DES/TDES decrypted key data.
      The decrypted DES/TDES key data you build as follows:
      IV= all zeroes
      Result1 = IV exor of first half of DES/TDES dec( new key)
      Result2 = Result1 exor second half of DES/TDES dec( new key)
      Result3 = Result2 exor DES/TDES dec( CRC16 of new key +
      padding)
      After changing the key you cannot authenticate with command
      0A,you will get error 1C (illegal command code).
      I hopethis will help you to change your key.
      Good luck.
      Mustafa

      • Tom

        Hi mustrafa,

        I have successfully overcome the issue. Thank you very much.Now what i need to now is i tried to change AES key(PICC Master) inside the card. According to specs came from NXP they required to calculate crc32 over

        ex crc32(C4 00 01020304050607080102030405060708 01)

        My question is when i use ISO wrapped command style(CLA+INS+PI+P2…..) should i calculate crc32 over all components or just CLA and Key NO + data.. can you help me in this matter…..

        Thanks

  • Mustafa Moripek

    Hi Tom,
    you have to build the CRC32 only over the new key data,nothing else.
    Mustafa

    • Tom

      Hi mustafa…

      I successfully change the AES key into DES key… Most important thing is to change this keys i have to calculate crc32 over all command..

      Such that..
      crc = crc32(C4+’00’+’New Key(16bytes)’)

      then,
      encipheredData = encBySessionKey(newKey+crc+pad)

      Then i send
      >>90C40000[Len][KeyNo][encipheredData]00
      <<9100

      So is it strange to calculate crc32 over command(C4)+keydata when we using AES change key function..Not like DES or TDES.. Pls check it out…!

      Thanks for your kind help.
      Cheers..

      Tom

  • Ali

    Hello
    Sorry for my inconvenience
    in many documents wrote the APDU of creating value file in desfire Ev1 Native mode.
    but i want the APDU of it in Iso mode Would you mind help me please?

  • Franz

    Hi,

    i have allready successful change the default main key 00 00 … 00 to
    to 00 11 22 … FF with return code 9100. But now i’m not able to
    authenticate with the new key. Can somebody help me please.

    Card: Desfire
    ATR: 3B8180018080
    key: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
    rndA_D: 14 D3 8F DB 8D C5 0F F8
    COMMAND SEND: 90 0A 00 00 01 00 00
    COMMAND RETURN: EE C7 E4 16 C1 1C E0 0D 91 AF
    rndB_E: EE C7 E4 16 C1 1C E0 0D
    rndB_D: A8 A2 37 95 9C 86 76 FD
    rndB_R: A2 37 95 9C 86 76 FD A8
    dkNo_D: 14 D3 8F DB 8D C5 0F F8 A2 37 95 9C 86 76 FD A8
    dkNo_E: 3F 31 A8 A1 5A 9F D8 C6 9D F7 63 4C 41 6B 5A B1
    COMMAND SEND: 90 AF 00 00 10 3F 31 A8 A1 5A 9F D8 C6 9D F7 63 4C 41 6B 5A B1 00
    COMMAND RETURN: 91 AE

    _E means ENCRYPTED
    _D means DECRYPTED

    Decryption and Encrypting was done by the followinf methods (JAVA)

    public static byte[] encrypt3DES(byte[] key,byte[] data) throws Exception {
    Cipher cipher = Cipher.getInstance(“DESede/CBC/NoPadding”,”BC”);
    cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key,”DESede”),new IvParameterSpec(new byte[8]));
    return cipher.doFinal(data);
    }

    public static byte[] decrypt3DES(byte[] key,byte[] data) throws Exception {
    Cipher cipher = Cipher.getInstance(“DESede/CBC/NoPadding”,”BC”);
    cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key,”DESede”),new IvParameterSpec(new byte[8]));
    return cipher.doFinal(data);
    }

    Franz

  • Mustafa Moripek

    Hi Franz,
    There are some points which are not clear to me.You
    mention RndA_D but you don’t mention RndA.When
    communicating with PICC, PCD always
    DES/3DES decrypts and PICC always DES/3DES
    encrypts.If the data RndA_D is really decrypted data
    then you are decrypting it twice befor sending it to
    PICC.
    Anaother issue is that your TDES decrypting
    algorithm is not working properly.When
    decrypting your command return (rndB_E:
    EE C7 E4 16 C1 1C E0 0D) I get
    following result: RndB_E=51 E4 89 15 80 05 47 AD

    Mustafa

  • Franz

    Hi Mustafa,
    RndA_D is not allready decrypted. RndA_D is a random generated key (by myself). I have rename it now to RndA. The TDES decryption algorithm works fine now (now i have the same result as you). the problem
    was that i have encrypted rndB_E (i simply forgot it to change it back after
    playing a little bit around). but now i am still not able to authenticate:

    ATR3B8180018080
    key: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
    rndA: B7 1F AA B7 2D 3C 4F 50
    COMMAND SEND: 90 0A 00 00 01 00 00
    COMMAND RETURN: 8A 8E E9 C5 99 B6 4A 5C 91 AF
    rndB_E: 8A 8E E9 C5 99 B6 4A 5C
    rndB_D: 52 63 DA C1 FF 2C EA 14 (TDES decrypted rndB_E)
    rndB_R: 63 DA C1 FF 2C EA 14 52 (Rotated rndB_D)
    dkNo_D: B7 1F AA B7 2D 3C 4F 50 63 DA C1 FF 2C EA 14 52 (rndA+rBR
    dkNo_E: 2A 6E 50 C5 0A B3 8F BB F1 B8 C1 08 33 D7 12 D0
    COMMAND SEND: 90 AF 00 00 10 2A 6E 50 C5 0A B3 8F BB F1 B8 C1 08 33 D7 12 D0 00
    COMMAND RETURN: 91 AE

    I am not sure if the step dkNo_D to dkNp_E is correct. TDES encrypt dkNo_D with the key 00 11 22 … FF to dkNo_E

    Thank you for the help.

    franz

    • Mustafa Moripek

      Hi Franz,
      when sending data to PICC you use CBC format.With your data
      it looks like follows:
      RndA = B7 1F AA B7 2D 3C 4F 50
      3DES_decrypted RndA = 31 C3 51 43 66 3E 7A 00
      Encrypted RndB = 8A 8E E9 C5 99 B6 4A 5C
      3DES_decrypted RndB=52 63 DA C1 FF 2C EA 14
      RndB ‘= 63 DA C1 FF 2C EA 14 52
      (3DES_decrypted RndA) exor (RndB ‘) = 52 19 90 BC 4A D4 6E 52
      3DES_decrypt above result = D7 08 FE E9 F2 3B 66 9E
      Data to PICC = AF 31 C3 51 43 66 3E 7A 00
      D7 08 FE E9 F2 3B 66 9E
      I hope this will help you to authenticate.
      Mustafa

  • Franz

    Hi Mustafa,

    DES/TDES is working fine now. But now i want to try AES encryption. I allready change the key to a AES key (key# 0x80). Also I am able now to get RandomB with command 90 AA. Command 90 0A fails now, which is
    also ok. (the old and new key is 00 00 … 00)
    But the authenticate fails:

    key: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    rndA: 86 86 17 31 16 42 3F 67 0C E8 4B 9C 03 BD 32 93
    rndA_D: F1 FE 8E AF 24 77 04 E7 A6 CB EA 4E BB E5 48 1D
    COMMAND SEND: 90 AA 00 00 01 00 00
    COMMAND RETURN: 8F 27 30 30 EF A8 DE 12 63 14 F5 18 24 3C 1F 42 91 AF
    rndB: 8F 27 30 30 EF A8 DE 12 63 14 F5 18 24 3C 1F 42
    rndB_D: 82 BB 21 0B A1 8E 36 22 59 03 5F 1E B6 1C B2 28
    rndB_R: BB 21 0B A1 8E 36 22 59 03 5F 1E B6 1C B2 28 82
    rndB_X: 4A DF 85 0E AA 41 26 BE A5 94 F4 F8 A7 57 60 9F
    rndB_XD: 49 27 4A 5E 59 04 5D 76 D9 AA CA 65 3A D0 37 71
    COMMAND SEND: 90 AF 00 00 20 F1 FE 8E AF 24 77 04 E7 A6 CB EA 4E BB E5 48 1D 49 27 4A 5E 59 04 5D 76 D9 AA CA 65 3A D0 37 71 00
    COMMAND RETURN: 91 AE

    I think that my AES decryption method is not working correct. Can you
    please take a look on it?

    Thank you.
    Franz

    • Franz

      Hi,
      i have fixed it. With AES you have to encrypt and not to decrypt the
      Randoms.
      Franz

    • janex

      Hi Franz,
      I’m also trying to authenticate using AES. I have shared authentication key.
      I send authentication command (90 AA 00 00 01 00 00) and receive proper RandomB from card.
      How to compute rndB, rndB_D, rndB_R, rndB_X, rndB_XD and how to compute next command, which should be sent to card?
      Thanks for advice.

  • Ali

    Hi,
    I need the APDU of change key in ISO mode.
    Can any buddy help me .

  • Ali

    Hi @all
    i want to Athenticate with desfire in native mode .
    Here is my code .
    i selected master (AID = 0x00 0x00 0x00) .
    and my key to encryption and decryption is :
    key = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F

    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards

    AID = 0x00 0x00 0x00)
    key = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0x00

    ==>> 90 0A 00 00 01 00 00
    <> 90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    <<== 91 AE

    please help me

  • Ali

    Hi @all
    Here is my complete post

    i want to Athenticate with desfire in native mode .
    Here is my code .
    i selected master (AID = 0×00 0×00 0×00) .
    and my key to encryption and decryption is :
    key = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    ==>> 90 0A 00 00 01 00 00
    <> 90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    <<== 91 AE
    please help me

  • Ali

    Hi @all
    i want to Athenticate with desfire in native mode .
    Here is my code .
    i selected master (AID = 0×00 0×00 0×00) .
    and my key to encryption and decryption is :
    key = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    >> 90 0A 00 00 01 00 00
    <> 90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    <<91 AE
    please help me

    • Mustafa Moripek

      Hi Ali,

      write your complete communication with the desfire
      card in following order so I can see what is the issue:
      Authentication key
      Challenge to PICC (0A , Key No.)
      Response of PICC (AF , Ek(RndB))
      Challenge to PICC (AF , Dek(RndA+RndB’))
      Response of PICC

      Mustafa

  • Ali

    Sorry for my inconvenience
    I dont kwon what some of my code not be copied
    Hi @all
    i want to Athenticate with desfire in native mode .
    Here is my code .
    i selected master (AID = 0×00 0×00 0×00) .
    and my key to encryption and decryption is :
    key = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    send to card >> 90 0A 00 00 01 00 00
    receive from card <> 90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    receive from card << 91 AE
    please help me

  • Ali

    Hi @all
    i want to Athenticate with desfire in native mode .
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    Here is my code .
    90 0A 00 00 01 00 00
    5B 57 69 C7 CE 4B 16 7B 91 AF
    enciphered RandB = 5B 57 69 C7 CE 4B 16 7B
    deciphered RandB` = 17 8D 23 57 10 C9 32 D5
    one byte lshitf RandB`.
    RandB“ = 8D 23 57 10 C9 32 D5 17
    Generate Rand A = 43 9D 17 8E 9A 5F BA 70

    concatenate Rand A With Rand B“ = 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17

    enciphered Rand A = Rand B“ = 9E ED DC 4F BC E7 BE BD 09 02 CF 99 F7 40 34 7B

    90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    91 AE
    please help me

  • Ali

    Hi @all
    i want to Athenticate with desfire in native mode .
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    Here is my code .

    > 90 0A 00 00 01 00 00
    90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    < 91 AE
    please help me

  • Ali

    Hi @all
    i want to Athenticate with desfire in native mode .
    in Step 2 when i concated 8 bytes rand A with 8 bytes rand B and Encrypt it to send to PICC.i receive 91 ae and i dont khow why .can any one help me.
    best regards
    AID = 0×00 0×00 0×00)
    key(for enciphering and deciphering) = A0 0B 7A CA BE EC 26 5A 96 9D F9 46 50 48 F5 5F
    KeyNumber = 0×00
    Here is my code .
    i send 90 0A 00 00 01 00 00
    And receive 5B 57 69 C7 CE 4B 16 7B 91 AF
    enciphered RandB = 5B 57 69 C7 CE 4B 16 7B
    deciphered RandB` = 17 8D 23 57 10 C9 32 D5
    one byte lshitf RandB`.
    RandB“ = 8D 23 57 10 C9 32 D5 17
    Generate Rand A = 43 9D 17 8E 9A 5F BA 70
    concatenate Rand A With Rand B“ = 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17
    enciphered Rand A = Rand B“ = 9E ED DC 4F BC E7 BE BD 09 02 CF 99 F7 40 34 7B
    i send 90 AF 00 00 10 43 9D 17 8E 9A 5F BA 70 8D 23 57 10 C9 32 D5 17 00
    And receive 91 AE
    please help me

  • Mustafa Moripek

    Hi Ali,
    Before sending data to PICC you have to decrypt it,
    because PCD always decrypts and PICC always
    encrypts.When decrypting you have to use Triple
    DES algorythm for the first half (the first 8 bytes)
    are not equal to the second half.When you send
    data longer than 8 bytes you have use CBC send
    mode.That means you have to exor the result
    of the decryption of the first eight byte with the
    second half and decrypt it.Your last challenge
    should look like as follows :
    90 AF 00 00 10 (Dec(RndA) + Dec(Dec(RndA)^RndB’)) 00
    Good luck.
    Mustafa

    • Wen

      Hi Mustafa,

      I created an application with
      Key-settings: 0xEF
      Num-keys: 0x81 (only master key, AES).

      I’m having problems changing that application key. Would you be able to help me?

      1. I select the application (OK)
      2. Then authenticate using AES default key which is all zeros (OK)
      2.a) Resulting session key is:
      randA: 67 32 c4 29 06 c5 0f 1f af d9 ef 61 2b d3 3b ab
      randB: 0b 18 5a 3e 6c 08 50 a6 bc 93 2f f9 52 fd 4d 52
      sessionKey is: 67 32 c4 29 0b 18 5a 3e 2b d3 3b ab 52 fd 4d 52
      3. Finally I try chaning the AES key and I get an Integrity Error.

      I’m doing the following:
      New AES key= 01020300000000000000000000000000
      Key version= 00
      CRC32 of new AES key= 69 cb b1 71 (I hope it is correct)
      IV= 00000000000000000000000000000000
      payload=AES_Encrypt(newAESkey||00||69cbb171||padding=all_zeros)
      payload=d4 93 d8 b9 5f 97 f2 72 aa b1 c4 ca de b8 74 1a b1 1f c3 2c a1 39 c3 a8 3c 3f 2e 68 40 f8 fd d2
      I used the session key and IV for the encryption.

      COMMUNICATION:
      >> 90 c4 00 00 21 00 d4 93 d8 b9 5f 97 f2 72 aa b1 c4 ca de b8 74 1a b1 1f c3 2c a1 39 c3 a8 3c 3f 2e 68 40 f8 fd d2 00
      << 91 1e

      • Mustafa Moripek

        Hi Wen,
        your CRC32 algorithm is O.K. but there is another
        issue you have to correct.You have to build CRC32
        over Command + KeyVersion + New Key (C4 00 01
        02 03 00 00 00 00 00 00 00 00 00 00 00 00 00).
        Good luck.
        Mustafa

      • Wen

        Thank you for you help. Unfortunately it is still not working.

        After selecting the application and authenticating using AES, I did:
        CRC32(c4 + 00 + 01 02 03 00 00 00 00 00 00 00 00 00 00 00 00 00)
        CRC32 is: fd 25 74 8e

        Then encrypted (with session key):
        sessionKey is: 0c 3a 4e f2 83 0e ae ff 81 d8 5d e1 fe cd ed a9
        AES_Encrypt(01 02 03 00 00 00 00 00 00 00 00 00 00 00 00 00 + 00 + fd 25 74 8e + 00 00 00 00 00 00 00 00 00 00 00)
        Cipher text is: b0 87 dc 14 69 f8 cd ff eb 4b 70 37 13 b9 a7 8d dc 76 49 f1 83 74 40 d9 8a 18 cd 13 73 71 bf 07

        >> 90 c4 00 00 21 00 b0 87 dc 14 69 f8 cd ff eb 4b 70 37 13 b9 a7 8d dc 76 49 f1 83 74 40 d9 8a 18 cd 13 73 71 bf 07 00
        << 91 1e

        Any idea of what I could be doing wrong?

      • Mustafa Moripek

        Hi Wen,
        I made a mistake.The correct proceeding is as follows:
        CRC32 over : Cmd(C4) + Key No. +New Key +
        New Key Version
        AES over : New Key + New Key Version + CRC32 +
        Padding
        Payload : Cmd (C4) + Key No. + AES cipher data
        Try this you will succed in changing the key.
        Mustafa

      • Wen

        It’s working, thank you Mustafa!

      • Chris

        Thanks for posting this. I’m having the same problem and must be very close to resolving it thanks to the information here. I was wondering what the correct payload was above? I figure to get the cipher data we do AES_Encrypt(01 02 03 00 00 00 00 00 00 00 00 00 00 00 00 00 + 00 + 0a fd 8b 53 + 00 00 00 00 00 00 00 00 00 00 00)
        which gives payload:
        Cmd (C4) + Key No.(0) + cipher data (b0 87 dc 14 69 f8 cd ff eb 4b 70 37 13 b9 a7 8d cd 27 24 a3 71 83 88 28 f3 62 10 a9 62 84 b3 96)

        Is that correct?

        Thanks,
        Chris

  • Ali

    Hi Mustafa
    Thank you so mach for helping me. i got successful authentication .But there is another problem :
    I want to change key Master (Aid = 0x00).
    my key is 0x00.

    I do every thing that you tell amila in ((March 5th, 2012 at 11:36))
    here is my data after xor and enc : 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40 A6 E1 43 FE 2B 21 0A 2A 7B A1
    And i send :
    90 c4 00 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40 A6 E1 43 FE 2B 21 0A 2A 7B A1 00
    i receive : 91 7e ( LENGTH_ERROR )

    And if i send:
    c4 00 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40 A6 E1 43 FE 2B 21 0A 2A 7B A1 00

    i receive : 67 00 ( wrong length )

    And if i send:

    90 c4 00 00 19 00 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40 A6 E1 43 FE 2B 21 0A 2A 7B A1 00

    i receive : 91 1e ( INTEGRITY_ERROR )

    can you help me please ?

    • Mustafa Moripek

      Hi Ali,
      I cannot check your data for I don’t have the
      complete communication,but I think I know where the issue is.
      The correct format is:
      90 cmd 00 00 Length Parameter Le
      cmd = C4
      Length = 18 ( 24 bytes)
      Parameter = 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40
      A6 E1 43 FE 2B 21 0A 2A 7B A1
      Le=00

      The challenge should look like :
      90 C4 00 00 18 98 39 23 79 C8 6E AD 0F A6 45 F1 9F B4 40
      A6 E1 43 FE 2B 21 0A 2A 7B A1 00

      The 00 between Length(19) and 98 shouldn’t be there.
      For you have written 19 as length you don’t get length
      error,you get 1E (integrity error) which means the CRC
      doesn’t match with the correct one.If you fix this I think
      you wil get the key changed.
      Mustafa

  • Ali

    Hi @All,
    I create an application with one file.(file_id = 0x09)
    I want to write 13(=0x0d ) bytes Data in that file .I used this command :
    90 cd 00 00 14 09 00 00 00 0d 00 00 13 byte data 00
    I receive 91 f0
    91 f0 means FILE_NOT_FOUND While the if i create another file with file_id = 0x09
    I receive 91 de (douplication eror )
    Can anybody help me please ?

    • Mustafa Moripek

      Hi Ali,
      Command format for creating standard data file
      is as follows:
      90 Cmd(CD) 00 00 Length File No. Com.Set
      Access Rights(2 bytes) File Size (3 bytes) Le(00)
      Command format for writing data into a file
      is as follows:
      90 Cmd(3D) 00 00 Length File No. Offset(3bytes)
      Length(3 bytes) Data ( up to 52 bytes)

      Mustafa

  • Ali

    Hi Mustafa ,
    Thank you for reply me and supporting me.
    I am in holiday at now.
    I back to my work at Saturday and tell you the result of of my challenge .

  • Cem

    hi mustafa,
    ı am trying to authenticate PICC level of Desfire EV1 with AES.I can authenticate created applications with AES but PICC level authentication returns me AE.
    crc operations must be done but which steps ı must follow can you help me?

    thanks

  • Mustafa Moripek

    Hi Cem,
    write the complete comunication with the PICC
    so that I can see where the issue is.
    Mustafa

  • Berk

    Hi Mustafa,and the other whole helpful follwer of the ridrix.
    I am workimg on desfire ev1 cards with android.I have same problem as Cem.I can authneticate with both AES AND DES/3DES and can create applications with AES authenticaiton mode.But I have some problem to change keys especially picc key to communucate with AES.I am writing the steps I tried below:

    1)resulult1=XOR(first key with new key)
    2) reslut2=reslult1 || crc16(result)
    3)result3=result2 || crc16(new key)
    4)result4=result3 || 4 byte with zero
    5)result5=dec with session key(result4)

    then I trancive result5 which appended 0x80 to head with the command 0xC4. But I couldnt achieve to change key and got some error code especially NO such key. I will be glad if you help Thank you.

  • Ali

    Hi Mustafa,
    Finally i Can create a file and write in it.
    Thank you.
    But i have my problem about change key yet.
    I have a question in change key :
    Should i do this steps :
    1.Exor the first byte (01 01 01 01 01 01 01 01) with
    IV all zeroes,and 3DES encrypt it with session key.
    2.Exor the second byte (01 01 01 01 01 01 01 01) with
    the result of the first step, and 3DES encrypt it with session key.
    3.Exor the third byte (CRC1 CRC2 00 00 00 00 00 00) with
    the result of the second step, and 3DES encrypt it with session key.
    4.Append all of them to your command c4 00.
    And if your answer is yes , would you mind tell me an example please.?

  • Mustafa Moripek

    Hi Ali,
    yes you have to proceed like you have discribed.With
    following difference,you have to use 3DES decrypt.
    PCD always decrypts and PICC always encrypts.
    If you cannot change the key , write the complete
    communication and I can verify your result.
    Mustafa

    • Ali

      Hi Mustafa;
      I created an application With AID = { 0×05, 0×00 ,0×00} and Key setting {0x1f } And the number of Key = {0×08}:
      90 CA 00 00 05 05 00 00 1F 08 00
      I want to use change key command :
      NEW_KEY : 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
      CRC16 for NEW_KEY : CC 69
      NEW_KEY + CRC16 + 6 bytes PAD :00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF CC 69 00 00 00 00 00 00 = My Data

      1) Select the Master Application.

      2)Authenticate with keyNumber =0×01.

      Rand A = C1 C9 C0 7E 19 71 30 C8
      Rand B = 07 D1 DC 5E 51 2E 84 24
      Session key = C1 C9 C0 7E 7 D1 DC 5E 19 71 30 C8 51 2E 84 24
      3)Select My Application ( AID = {0×05, 0×00, 0×00} )

      4)Xor First Byte of My Data with vector (= 00 00 00 00 00 00 00 00 )
      for (int i = 0; i < 8; i++)
      {
      step1[i] = (byte)((MYData[i]) ^ (0×00));
      }

      5) Decrypt step1 with session key .
      Decstep1 = 6D CE 52 30 74 EB 81 A9

      6) Xor the second byte of My Data with Decstep1
      for (int i = 0; i < 8; i++)
      {
      step2[i] = (byte)((MyData[i + 8]) ^ (Decstep1[i]));
      }

      7)Decrypt step2 with session key

      Decstep2 = BA 4F D9 58 E6 86 8B 32

      8)Xor the third byte of MyData with Decstep2

      9) Xor the second byte of My Data with Decstep1
      for (int i = 0; i < 8; i++)
      {
      step2[i] = (byte) ((MyData[i +16]) ^ (Decstep2[i]));
      }
      10) Decrypt step3 with session key .

      Decstep3 = EB AD 2A 13 49 8E 01 03

      FINAL COMMAND : 90 c4 00 00 18 6D CE 52 30 74 EB 81 A9 BA 4F D9 58 E6 86 8B 32 EB AD 2A 13 49 8E 01 03 00
      I receive 91 7e

      And if :
      FINAL COMMAND : 90 c4 00 00 19 03 (= the key number i want to change ) 6D CE 52 30 74 EB 81 A9 BA 4F D9 58 E6 86 8B 32 EB AD 2A 13 49 8E 01 03 00
      I receive 91 1e

  • Gabriel

    Hi Mustafa,
    Could you please guide me the use of CRC32 for AES in Desfire?
    I explored two versions of CRC32 scheme.
    When calculated to hex string 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff
    first one gives 84 07 75 9B and second one gives 7B F8 8A 64.
    Best Regards,
    Gabriel

  • Ali

    Hi Mustafa;
    I created an application With AID = { 0x05, 0x05 ,0x05} and Key setting {0x0f } And the number of Key = {0x08}:
    90 CA 00 00 05 05 5 05 0F 08 00
    And create a standard data file with File_Id = { 0x09 } :
    90 CD 00 00 07 09 00(ComSet) 71 27 (Access Rights) 40 00 00 (Size) 00
    And writing in that file :
    90 3D 00 00 14 09 00 00 00 (offset) 0D 00 00 (length) 13 byte data 00
    I can do Correctly all of them .
    But i can’t change key.
    For change key i do :
    1)Select Master
    2)Authenticate with master
    3)Select AID = 05 05 05 .
    4)Authenticate with AID.
    And use this code :
    90 C4 00 00 00 19 00 24 byte Data 00
    I Receive 91 1e = Mac error
    I Have Some questions :
    1)In the step 4 i should authenticate with which Key ( i use 00 And give a correct Authenticate)
    2)You tell me that i shouldn’t put 00 after 18.(The 00 between Length(19) and 98 shouldn’t be there.) Now my question is : How can i specified the key that i want to changed.
    3)How can i attain the 24 bytes data.
    Thanks a lot.
    Ali

  • Ali

    Hi Mustafa;
    I created an application With AID = { 0×05, 0×00 ,0×00} and Key setting {0x1f } And the number of Key = {0×08}:
    90 CA 00 00 05 05 00 00 1F 08 00
    I want to use change key command :
    NEW_KEY : 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
    CRC16 for NEW_KEY : CC 69
    NEW_KEY + CRC16 + 6 bytes PAD :00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF CC 69 00 00 00 00 00 00 = My Data

    1) Select the Master Application.

    2)Authenticate with keyNumber =0x01.

    Rand A = C1 C9 C0 7E 19 71 30 C8
    Rand B = 07 D1 DC 5E 51 2E 84 24
    Session key = C1 C9 C0 7E 7 D1 DC 5E 19 71 30 C8 51 2E 84 24
    3)Select My Application ( AID = {0x05, 0x00, 0x00} )

    4)Xor First Byte of My Data with vector (= 00 00 00 00 00 00 00 00 )
    for (int i = 0; i < 8; i++)
    {
    step1[i] = (byte)((MYData[i]) ^ (0x00));
    }

    5) Decrypt step1 with session key .
    Decstep1 = 6D CE 52 30 74 EB 81 A9

    6) Xor the second byte of My Data with Decstep1
    for (int i = 0; i < 8; i++)
    {
    step2[i] = (byte)((MyData[i + 8]) ^ (Decstep1[i]));
    }

    7)Decrypt step2 with session key

    Decstep2 = BA 4F D9 58 E6 86 8B 32

    8)Xor the third byte of MyData with Decstep2

    9) Xor the second byte of My Data with Decstep1
    for (int i = 0; i < 8; i++)
    {
    step2[i] = (byte) ((MyData[i +16]) ^ (Decstep2[i]));
    }
    10) Decrypt step3 with session key .

    Decstep3 = EB AD 2A 13 49 8E 01 03

    FINAL COMMAND : 90 c4 00 00 18 6D CE 52 30 74 EB 81 A9 BA 4F D9 58 E6 86 8B 32 EB AD 2A 13 49 8E 01 03 00
    I receive 91 7e

    And if :
    FINAL COMMAND : 90 c4 00 00 19 03 (= the key number i want to change ) 6D CE 52 30 74 EB 81 A9 BA 4F D9 58 E6 86 8B 32 EB AD 2A 13 49 8E 01 03 00
    I receive 91 1e

  • Ali

    Hi Mustafa;
    I need your help strongly.

  • Mustafa Moripek

    Hi Ali,
    I made a mistake when writing the APDU format.
    The correct format is as follows :
    90 Ins 00 00 Lc(Length of data=19) File No.(03)
    24 Bytes of Data Le=00
    But there are other mistakes.First I have checked
    your data and realized that you didn’t use 3DES
    decryption.Second issue is you are changing
    key No.3 but you are authenticating with key No.1.
    If the key number you are authenticating is
    different then the key number you want to change
    than you have to proceede as follows:
    The new key and the current key are exored.
    And CRC (2bytes) of the exored data is appened.
    Additionaly CRC (2bytes) of the new key is
    appended after padding with zeroes (4 bytes).After
    this you proceede as you have done but use
    3DES decryption for the first half of the session
    key is not equal of the second half.
    Good Luck
    Mustafa

    • Ali

      Hi Mustafa,
      I am sorry for my inconvenience.
      Thank you so much for your assist and guide .
      Finally i can changed a key in native mode after many attempt and ask many question from you.
      Without your help i can not success.
      There is one problem that i have yet :
      How can i calculate crc 16 and crc 32 of some data.
      for example i have one function that i do not know its implementation.That Function calculate the crc 16 of data for me and i do not know how it work.For example that function give me
      37 49
      for : 00 00 00 00 00 00 00 00
      I want to know how it work.
      I try many online calculate for 00 00 00 00 00 00 00 00
      But i can reach 37 49 from all of them.
      Or How can i calculate the crc 32 of some data (I need That code or one comprehensive site that calculate it for me)
      Please help me.

      • Ali

        Hi mustafa ,
        I do a mistake .
        That function give me 37 49 for 24 bytes 00
        And give me 32 07 for 24 bytes 11

    • Mustafa Moripek

      Hi Ali,
      with the code I have given the link of you can calculate it.
      If you want to read more about the crc try following
      link : http://www.repairfaq.org/filipg/LINK/F_crc_v3.html
      Mustafa

  • Mustafa Moripek

    Hi Ali,
    there are many algorithm on web you can use for
    calculating CRC 16.Try the code on site:
    http://www8.cs.umu.se/~isak/snippets/crc-16.c
    Mustafa

  • Ali

    Hi Mustafa ,

    I have one question and it is so important for me to find answer of this:
    In March 7th, 2011 at 16:56 T you tell Bruno :
    (( to use is : 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F .
    The CRC16 for this key is 77 F5 ))
    I want to know how do you calculate it . That is the answer of my first question in January 22nd, 2013 at 13:57 .
    Please help me.
    Best Regards.
    Ali

  • Mustafa Moripek

    Hi Ali,
    No the POLY should be 8408 and start CRC not FFFF
    but 6363.
    Mustafa

  • Ali

    Hi Mustafa,
    i used your code in C ,and C# compilers .
    in both of them i received ( ffafa9af ) for (0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF )
    While the i should received CC 69.
    Here is my code :
    Can you tell me what is my mistake?

    byte[] Data = new byte[16]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };

    crc16(Data,16);

    public UInt64 crc16(byte[] data_p, int length)
    {
    int i;
    uint data;
    uint Polynome = 0x8408;
    uint crc = 0xffff;

    if (length == 0)
    return (~crc);
    do
    {
    for (i = 0, data = ((uint)0xff & data_p[i]); i >= 1)
    {
    if (((crc & 0x0001) ^ (data & 0x0001))!=0)
    crc = (crc >> 1) ^ Polynome;
    else crc >>= 1;
    }
    length–;
    } while (length>0);

    crc = ~crc;
    data = crc;
    crc = ((crc <> 8) & 0xff));

    return (crc);
    }
    If you send me a code that give cc 69 for 00 11 22 33 … ff
    you oblige me
    a.program.ali@gmail.com
    Best Regards
    Ali .

  • Ali

    Hi Mustafa,
    Thank you for all of your helps.
    Without you i do not think i can change keys in desfire.
    But here is some problems :
    I create an application with this setting 1f 08
    ( I explain the the following lines to another readers and i know you know all of them)

    ((( 1f 08 in setting : means in that application i have 8 keys that when
    i want to change one of them (( except 0x01 =(the firs 4 bit in the 1f) and 0x00(=master key in application ) )) i should to authenticate with the key 0x01 and if i want to change 0x01 and 0x00 i should authenticate with master. )))

    I can change key PICCMaster key and every keys in that application except 0x01 and 0x00.
    for example when i want to change 0x01 i do this steps :
    1) Select master
    2 ) Authenticate PICCMaster and receive SesssionKey
    3) Select that application
    4) Used the decrypted ( NEW_KEY + CRC16 + 6 bytes PAD ) = 24 bytes with SesssionKey
    5 ) I send this and i give 91 ae
    And if i try this :

    1) Select master
    2 ) Authenticate PICCMaster and receive SesssionKey
    3) Select that application
    4) Authenticate Application and receive SessionKey2
    5) Used the decrypted ( NEW_KEY + CRC16 + 6 bytes PAD ) = 24 bytes with SessionKey2
    6 ) I send this and i receive 91 1e

    And another problem that i have is :
    How can i do iso Change Key (with crc32).?
    I replace Crc16 with Crc32 and can not change a key .

  • Ali

    Hi Mustafa ,
    Sorry for my inconvenience.
    Finally i can change the Application Master Key and Changekey key.
    But here is some problems :
    I create an application with this setting 0f 08.
    I can change every key, even 0x00 and 0x01.
    But if I change 0x00 , when i want to change another key i receive 91 1e .
    While the i can change the key before i changed 0x00.
    I create an application with this setting : 1f 08.
    And i can not change the key after changing ChangeKey key either.

  • Mustafa Moripek

    Hi Ali,
    bit 0 of PICC and bit 0 of application masterkey settingsbyte
    defines wether the changing of the key is allowed or not.If it is
    zero like in your case the key is frozen and you cannot change
    it any more.You should use f9 if you want that the key is
    changeable.
    Mustafa

  • Ali

    Hi Mustafa ,
    Thanks.
    I do a mistake in explain my problems.
    I set it (the bit 0 ) to 1 for allowing change.
    I set 0f in create application , for change a key i need to ayuthenticate with key 0x00 .
    I can change any key with default MasterKey or default ChangeKey key , that means the bit 0 is not 0.
    But if i Change the ChangeKey key or MasterKey and use it (the MasterKey or ChangeKEy key after changing ) for authenticate and create SessionKey , i did not change any key again .While the i can change it before change the MasteKey or ChangeKey key.

  • Ali

    Hi Mustafa ,
    I explain correctly what i do :
    I create an application with this setting 1f 08.
    For change key :(for example 0x03)
    1)I select that Application.
    2)Authenticate with keyNumber 0x01and attain the Sessionkey (16 bytes).
    3)Xor the OldKey and NewKey of 0x03( the Key i want to change). = XoredData
    4)Append the CRC16 of XoredData to XoredData.
    5)Append Crc16 of NewKwey to XoredData .

    MyData = XoredData + crc16 Xored data + crc16 NewKey.

    6)Decryption MyData with the first byte of SessionKey.
    I received 91 00 that means the key changed correctly.

    But if I change the ChangeKey Key and if i want change a key (the Oldkey and Newkey are same the OldKey and NewKey of 0x03 ) i can not change it and i receive 91 1e .While the if i do this before change ChangeKey key , i can change it.
    And it is my problem
    Best Regards
    Ali

  • Mustafa Moripek

    Hi Ali,
    I don’t know wether I have understand you correctly,
    but I give you the rules for key setting,you may be able
    to find the issue than.
    The bits 7(MSB) to 4 are holding access right for changing
    application keys.If those bytes are 0 it means you have
    to authenticate with application master key.If it is between
    0X01 to 0X0D authentication with this specified key is
    neccessary to change any key.If it is 0X0E you have to
    authenticate with same key you want to change.
    I hope this info will help you to find the issue.
    Mustafa

    • Ali

      Hi Mustafa ,
      Thanks.
      I know it and i can change any key in native mode.
      But if i change application master key or change key key , i can not change any key again.
      I receive 91 1e.
      I want to know if i change the application master or change key key is that effect in other keys or not?
      And if it is not effect in other keys why give me 91 1e?
      Can i send you my code?
      Best regards
      Ali

  • Ali

    Hi Mustafa ,
    I indebted you all of my knowledge about desfire functions .
    Let me put it in other words :
    Certainly you can change the application masterkey or changekey key.
    Here is my question :
    Can you change the other keys after change application masterkey or changekey key ?
    Or you first change the other keys and then change the application MasterKey or ChnageKey key?( The job that i do it)
    And if your answer be yes that mean you can change the other key after changing application MasterKey or ChangeKey key ,
    Would you mind give me a real data that with that data you can correctly change keys after changing application MasterKey or ChangeKey key please?
    Best Regards
    Ali

    • Mustafa Moripek

      Hi Ali,
      sorry for delayed answer.You must be able to change any
      key after changing application master key or change key key.
      I will test it and let you know the result.
      Mustafa

  • Arvind

    Hi All,

    I am getting problem to authenticate DesFire ev1 card with Master keys in Adroid (using TDES), I followed these steps
    1. >> 905a00000300000000 (sending PICC selection Command )
    <>900A0000010000
    << getting RndB
    3. Then I deciphered RndB and Prepare RndB as per doc right shift
    4. After that i generate RndA
    5. then add RndA+RndB
    6. Then Enciphered RndA+RndB and send to card
    I am getting 901C Response from card, which is Illegal command .

    I m using Iv(initial vector as 00000000) and masterkey for encipher and decipher, please help to solve this issue. I also tried with (default key(like 0000….). I dueled checked that enciphered and deciphered is giving the right value

    Thanks,
    Arvind

  • Arvind

    Hi All,

    For further understand this issue, i m sending here these command and response
    Select PICC
    Send Command >>905a00000300000000
    Response <> 900A0000010000
    Response <> 0BBF991C55119BB141C3E90F6DC9E1C8
    Response << 911C

    Thanks,

    • Mustafa Moripek

      Hi Arvind,
      there are many issue in your data above.First thing is you
      have to decrypt data before sending to PICC.PCD always
      decrypts and PICC always encrypts.To your authenticate
      command you have received 16 bytes response.If the
      Desfire card is configured for DES/3DES algorithm you
      get 8 byte response.If it is configured for AES algorithm
      you get 16 bytes.To find out how it is configured make
      following test: Send ‘Get key settings’ command to the
      PICC:As response you will get two bytes.First byte is
      key settings and second byte is Number of Keys.The two
      MSB (bit7 and bit6) give the operation art.If they are 00
      then the PICC is configured for DES/3DES if they are 01
      then PICC is configured for 3K3DES and if they are 10
      then the PICC is configured for AES.For AES you
      authenticate with command 0XAA and for 3K3DES
      you authenticate with command 0X1A.
      Good Luck
      Mustafa

      • Arvind

        Thanks Mustafa,
        Its a copy and paste problem , I am pasting again that response. I checked key settings it shows 01, and I authenticate with 0x1A and following the response 1C (illegal command)
        //Seletion of AID 010000
        Command send 905a00000301000000
        Response << 9100

        //Authentication with masterkey
        Command send 901A0000010000
        Response << DFA7AB8C704978DF91AF

        // Generating RandomB and RandomA
        After removing 91AF ————-: DFA7AB8C704978DF
        initial IV : 0000000000000000
        deci RndB ———: 448AB5CD132D787A
        RndB' shift———: 8AB5CD132D787A44
        changed IV : DFA7AB8C704978DF
        RndA ———: 1122334455667788,
        Before enciphered RndA_RndB ———: 11223344556677888AB5CD132D787A44
        enciphered RndA RndB ———: D91049E51A2AF57C1BA42C1FE8FC538C
        changed IV : 1BA42C1FE8FC538C

        // Sending RandomA and RanmdomB
        Command send : 90AF000010D91049E51A2AF57C1BA42C1FE8FC538C00
        Response : 911C

        could you please provide me your mail id, so that i can send you this log to u.

        Thanks,
        Arvind

      • Mustafa Moripek

        Hi Arvind,
        1C means illegal command code and you get
        this answer when command code is not
        suppoerted.For example if you send the
        commnad 90 AF … before sending 90 1A you
        get the answer 1C.Therefore I assume you
        send something else between command 1A
        and the AF.My mailaddress is
        mustafa.moripek@gmail.com .Send me the whole conversation between PCD and PICC so I can
        try to find the issue.
        Mustafa

      • Bruno

        Hi Mustafa,

        I want to configure a blank desfire EV1 card directly to use AES mode.

        I know I need to change the masterkey to AES.

        I need some advise on concepts here.

        1. In order to change the master key to AES, do I need to perform a 0x0A or 0xAA authentication ?

        2. If I need to perform a 0xAA auth before change the masterkey to AES, do I need to changeKeysettings first?

        3. If I need to perform a 0x0A auth before change the masterkey to AES, I need to tell the PICC the new key would be AES instead of 3DES. By reading NXP docs, this should be at the “KeyNumber” (First Parameter) to the change key. I have already tried that but it telss me 0x40 (no key found for that number).

        Can someone please help me to understand this concept?

        Bruno

  • Wen

    Hi,

    I authenticate using an application master key (AES) and then ask for the list of file ids (there is none). I get this back: f6 c0 04 cd 00 a5 9e 7b.

    I’m assuming this is a CMAC? How should I proceed to verify if the CMAC is correct going from my session key?

    Thanks you

    • Wen

      I have a working implementation of CMAC but I can never get my values to match what is returned by the card. Which key should I use when calculating the CMAC?

      If I receive something like (02 03 XX XX XX XX)h where X is the CMAC, should I use only (02 03)h as input without modification?

      • mk

        Hi, i have exactly the same problem, also trying the GetFileIDs command.
        I think that the session key is used for CMAC generation.
        After session key generation, you also have to reset your IV to zero, but don’t do it after each cbc crypto operation, as it stays as it is between the new EV1 crypto methods.
        I try to figure out whether you have to cmac the command byte you send to the PICC (for example getFileIDs, 0x6F). I think you have to do that, but the resulting cmac is not sent, only the command byte.
        When i’m trying to verify the received mac, i dont know if only the data is cmaced, or also the status byte. If someone knows that, please answer 🙂

        I’m not using APDU wrapping yet.
        My AES session key is: 01 02 03 04 B8 9E F7 1D 0D 0E 0F 00 24 B4 2D BE
        cmac subkeys:
        sk1: 9C 5B CB 80 ED 7D B5 36 C6 8D ED A1 08 04 CB E0
        sk2: 38 B7 97 01 DA FB 6A 6D 8D 1B DB 42 10 09 97 47

        I’m sending the 0x6F command for (getFileIDs) just after the authentication is done, so IV is all zero, and calculate the cmac on the command byte:
        IV: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        Padded data before cmac: 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        CMAC: 9D 11 D0 DD 09 F0 0B FA 89 02 E7 0F ED 7F 75 B8

        I’m receiving the answer then:
        00 02 84 73 95 39 3B 95 60 55 53

        00 is the status code, 02 is a file i created, rest is CMAC to be verified
        after that, i’m calculating the CMAC for 00 02 (don’t know if the status bit is CMACed, too, both gives me the wrong result.)

        IV: 9D 11 D0 DD 09 F0 0B FA 89 02 E7 0F ED 7F 75 B8
        Padded data before cmac: 00 02 80 00 00 00 00 00 00 00 00 00 00 00 00 00
        CMAC: 4F A0 A2 E1 E2 A0 46 72 70 73 39 88 A8 EF 94 2E

        could someone verify this? i tested the cmac algorithm itself, it works, so i’ve forgotten something else…
        thanks for any help ^^

      • Wen

        Hi mk,

        I still haven’t figured out how to properly verify the CMAC.

        I did try calculating it with your values and the first CMAC you calculate is equal to mine but on the second CMAC calculation (received) I’m getting a different value:

        CMAC sent:
        9d 11 d0 dd 09 f0 0b fa 89 02 e7 0f ed 7f 75 b8
        CMAC received (using session key and using CMAC sent as IV, calculated on 00 02 …):
        a1 90 a9 88 93 19 eb 3b e5 2e 6e 85 14 06 c6 73

        I thought my CMAC algorithm was correct but I may be doing something wrong. If you get yours to work please let me know.

  • mk

    I’m using libfreefare as reference for cmac calculation. if padding is neccesary you xor the padded data with the second subkey, if no padding is performed the data is xored with the first subkey. after that the result is encrypted, using cbc send mode.
    the cmac function is here:
    https://code.google.com/p/libfreefare/source/browse/libfreefare/mifare_desfire_crypto.c

    here are CMAC examples to check against

    Click to access Updated_CMAC_Examples.pdf

    so i’m pretty sure that cmac calculation isn’t the problem, stilly trying to figure out which data has to be CMACed

  • mk

    ok, it works now for me!
    sorry, my session key was wrong, i changed my authentication code and got distracted by cmac stuff 😀 forgot rotating randomA right after checking if auth went ok.

    session key: 00 01 02 03 E3 27 64 0C 0C 0D 0E 0F 5C 5D B9 D5
    Session sub-keys:
    sk1: 7A 11 44 93 B2 E2 B1 D4 EA E6 31 E5 F4 D4 4F 58
    sk2: F4 22 89 27 65 C5 63 A9 D5 CC 63 CB E9 A8 9E B0

    CMACing the command byte 0x6F is right.
    Padded data before cmac: 6F 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    CMAC: CD C0 52 62 6D F6 60 CA 9B C1 09 FF EF 64 1A E3

    my reader gives me the following answer:
    00 02 07 A0 39 1B 25 3D 12 57

    where 00 is the status code, and 02 is a file id, rest is CMAC.
    i tried CMACing 00 02 and got wrong results.
    then i swapped data and status byte, which turned out to be right, i don’t know why. maybe my reader does APDU framing in the background so that actually the status byte is at the end? i don’t know… i’m using this one http://www.stronglink-rfid.com/en/rfid-modules/sl032.html

    this is the result…
    Padded data before cmac: 02 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00

    CMAC: 07 A0 39 1B 25 3D 12 57 89 CF AE E3 6F 26 9F 58

    • Wen

      I’m glad it is working for you! I also got it working and have been checking libfreefare.

      I was using the CMAC from a crypto library which wasn’t handling well the external IV for the second CMAC calculation.

    • Bruno

      mk, would you please share your AES authentication algorithm ?

      I cant get this working

      My encryption is not right I always get 0xAE from the card. Would you mind to share some bytes here 🙂

      Bruno

  • Ali

    Hi
    I want to Read a record .
    i Create a record with FileID 0x04 Successfully.
    I do this Steps:
    1)select the Application
    2)authenticate with that application
    3)From offset = 0x00 0x00 0x00
    4)Number Of recors = 0x00 0x00 0x01
    5)APDU = 90 bb 00 00 07 (=LC) 04 (=fileID) 00 00 00 00 00 01 00
    i send this and receivr 91 be
    Can anybody help me ?

    • Mustafa Moripek

      Hi Ali,
      be means boundary error.In the file you try to read
      are not as much records as you want to read.The
      one you have written as number of records is MSB.
      That means you want to read more then one million
      records.
      Mustafa

  • Smith

    Hello Mustafa,

    This is regarding Desfire SAM AV2. The Problem i unable to connect to SAM using normal PC/SC contact reader. can you please help me to solve this issue.

    1 – Is there any specific hardware to connect Desfire SAM?
    2 – Please share your view about SAM and their communication with PC/SC readers..
    3 – Are there any source which describes the SAM Communication..

    Thanks

    • Mustafa Moripek

      Hi Smith,
      for I have built my own reader I don’t have any idea how
      a PC/SC contact reader can read a SAM card.I used
      information (user manual,datasheets) of the producer.
      Try to get information from the producer of SAM.If you
      have any specific problem later on I can try to help.
      Good luck
      Mustafa

  • Ali

    Hi Mustafa.
    Another question.
    I want to change the file setting to 11 11 (change the access rights).
    If my FileID be 0x03 and my ComSetting be 0x00.
    I used this command:
    90 5F 00 00 04 03 00 11 11 00
    I send this and receive 91 7e(Length Error)
    I do not know what is my mistake.
    Please help me.

    • Ali

      Hi Mustafa.
      I solved this .
      Thank you for all of your help.

      • Ali

        Hi Mustafa,
        In ChangeFileSetting i have a problem.
        when i set the change key access right to e ( free access) in create the file , i can change the file setting .
        But if i set it to another byte 9for example 0x03) < and i want to change access rights afthe authenticate with the changeAccessrightKey (0x03 in here) i receive 91 7e Can you heipme

    • Miha

      What was the solution?

  • Morris Hirsch

    Dear Mustafa,

    I’m writing you in the hope that you might tell me where my mistake is in the changekey-process for a 0xAA authentication. I read all the above comments (and learned a lot of them…thanks for that !) on this topic but I am not able to find my mistake.

    I created an application (application 01) with several AES keys which all have the standard value 00…00. The application was created with the “CA 01 00 00 0E 85” command. Changekey should change one of them, but it does not. I authenticate with the application master key and get a 0x1E error.
    The following data is used:

    Authentication process:
    – – – – – – – – – – – –
    send> 0x0A
    rec af 56 e0 f0 9e 9e df 1d 72 62 ca af c8 56 97 0c 62 6d 87 02 40 57 b7 a7 11 64 2f 74 88 12 62 36 01
    rec “C401” + AESCBC(C401 + newkeyXORoldkey + newykeyversion + crc32[c401 + newkeyXORoldkey + newykeyversion] + crc32(newkey) + “00000000000000”)
    = C401 + AESCBC(C401+11…11+00+2AB7E18A+A7C83697+00000000000000)
    = C401 + “3c 22 90 33 44 c5 36 82 33 65 90 2e fc 0c be db f1 77 80 a1 fb 93 37 a8 64 e2 b8 c3 cc 6f 73 42”

    The AESCBC calculation was performed as follows:
    1st unencrypted CBC-plainblock w/o IV: 11111111111111111111111111111111
    1st unencrypted CBC-plainblock w/ IV: 0x7b6fffd7d20a5130e0ad40084e494c90L
    1st encrypted CBC-plainblock (w/ IV): 3c22903344c536823365902efc0cbedb
    2nd unencrypted plainblock (i.e. w/o XOR): 002AB7E18AA7C8369700000000000000
    2nd unencrypted CBC-plainblock (i.e. with XOR): 0x3c0827d2ce62feb4a465902efc0cbedbL
    2nd encrypted CBC-plainblock: f17780a1fb9337a864e2b8c3cc6f7342

    The overall result is an 0x1E error. As I spent several days finding the error, I came to a point where I hope you might help – of course only if you find the time to do so.

    Thank you,
    Morris.

    • Morris Hirsch

      I should explicitly remark that the authentication procedure works perfectly. My initial remark from above “I authenticate with the application master key and get a 0x1E error” might be misleading:
      Not the authentication but the changekey spawns that 0x1E error.

    • Morris Hirsch

      And I found a typo. The authentication takes place via 0xAA (and not 0x0A). I use the AES method.
      Do I have to submit the CRC values in LittleEndian format or in BigEndian ? I tried both variants and still got the 0x1E error.

  • Morris Hirsch

    Apparently this website’s editor filters the “greater than” and “less than” symbols, therefore a part of my posting is missing. Here the version with all information:

    Authentication process:
    – – – – – – – – – – – –
    send: 0xAA
    rec: af e5 62 d8 7b 8b c4 5e 74 19 02 0c f1 1e 54 29 82
    send: af 56 e0 f0 9e 9e df 1d 72 62 ca af c8 56 97 0c 62 6d 87 02 40 57 b7 a7 11 64 2f 74 88 12 62 36 01
    rec: 6a 7e ee c6 c3 1b 40 21 f1 bc 51 19 5f 58 5d 81

    AES-sessionkey: 00112233e2aa7694445566774e7095ae
    RndA: 00112233445566770011223344556677
    RndA2: 11223344556677001122334455667700
    RndB: e2aa7694704bf7a7c49a2e064e7095ae
    RndB2: aa7694704bf7a7c49a2e064e7095aee2

    From the preceding authentication process (AES authenticate with application master key, which is also 00…00):
    IV: 6a7eeec6c31b4021f1bc51195f585d81 (=AESCBC(RndA’))

    The AUTH process works properly, even a manual decryption of the last data chunk sent by the PICC (i.e. AESCBC(RndA’)) yields the correct result.

    • Morris Hirsch

      Changekey:
      – – – – –
      Key to be changed is key01, which has the default value 00…00.
      Newkey should be 11…11.

      CRC32:
      1) crc32[c401 + newkeyXORoldkey + newykeyversion]
      = crc32(c401+11…11+00) = 2AB7E18A
      2) crc32(newkey)
      = crc32(11…11) = A7C83697

      With these information the following command is sent:
      send> “C401” + AESCBC(C401 + newkeyXORoldkey + newykeyversion + crc32[c401 + newkeyXORoldkey + newykeyversion] + crc32(newkey) + “00000000000000”)
      = C401 + AESCBC(C401+11…11+00+2AB7E18A+A7C83697+00000000000000)
      = C401 + “3c 22 90 33 44 c5 36 82 33 65 90 2e fc 0c be db f1 77 80 a1 fb 93 37 a8 64 e2 b8 c3 cc 6f 73 42”

      The AESCBC calculation was performed as follows:
      1st unencrypted CBC-plainblock w/o IV: 11111111111111111111111111111111
      1st unencrypted CBC-plainblock w/ IV: 0x7b6fffd7d20a5130e0ad40084e494c90L
      1st encrypted CBC-plainblock (w/ IV): 3c22903344c536823365902efc0cbedb
      2nd unencrypted plainblock (i.e. w/o XOR): 002AB7E18AA7C8369700000000000000
      2nd unencrypted CBC-plainblock (i.e. with XOR): 0x3c0827d2ce62feb4a465902efc0cbedbL
      2nd encrypted CBC-plainblock: f17780a1fb9337a864e2b8c3cc6f7342

      • Mustafa Moripek

        Hi Morris,
        İf the card is a virgin card you use the default key
        all zeroes and you have to authenticate with the
        command code 0X0A and use DES-3DES algorithm
        for decryption.If you want use AES encryption
        with the new key you must make the 2MS bits of
        key number 10.In your case the command string
        after authentication with 0X0A should be:
        C4 + 81 + 3DESdecr with session key(newkey+
        CRC16+padding).
        Goog luck
        Mustafa

  • Mustafa Moripek

    Hi Ali,
    when you change file settings with keysettings 0X0E,
    the command format is: 5f File No. Com.Setting
    Access Rights (2 bytes) totally 5 bytes
    when you change file settings with a special key
    (in your case 0X03),the command format is :
    5F File No. New de or enciphered settings
    (8/16 bytes depending on which encryption
    you use – 3DES/AES)
    Mustafa

  • Trong Quyen

    Hi Mustafa,

    I’m newbie in Desfire EV1 card.
    In my project, i used the reader PN512.
    I’ve done following: REQA, CL1, CL2, RATS, PPS. Everything’s ok.
    But there is no answer from PICC when I implement to select the application:

    5A 00 00 00
    or
    90 5A 00 00 03 00 00 00 00
    Here is my code:

    void AID_Select(void)
    {
    PN512_Write(0x0A,0x80); // Flush FIFO
    PN512_Write(0x09,0x5A); // Native command select PICC
    PN512_Write(0x09,0x00);
    PN512_Write(0x09,0x00);
    PN512_Write(0x09,0x00);
    //
    PN512_Write(0x12,0x00); // Disable TX,RX CRC
    PN512_Write(0x13,0x00);
    PN512_Write(0x0D,0x80); // Transmit
    //
    PN512_Read(0x06); // No Error Status
    PN512_Read(0x0A); // 0x00 -> 0 byte in buffer -> there is no response? I don’t know why.
    PN512_Read(0x09); // Data is not correct?
    }

    void RFID_Desfire(void)
    {
    PN512_Config();
    Mifare_REQA();
    Mifare_ATQ();
    Mifare_Anticoll_1();
    Respond_SNR_1();
    Mifare_Select_1();
    Respond_SAK();
    Mifare_Anticoll_2();
    Respond_SNR_2();
    Mifare_Select_2();
    Respond_SAK();
    RATS();
    PPS(); // Everything is ok until the below function
    AID_Select();
    }

    Please give me the suggestions.

    Best regards,
    Trong Quyen

  • Mustafa Moripek

    Hi Trong,
    are you sure your other coomands are working
    properly?
    The code after writing to fifo should be as follows :
    PN512_Write(0×12,0×00); // Enable TX,CRC
    PN512_Write(0×13,0×00); // Enable RX,CRC
    PN512_Write(0×1D,0×00); // Enable parity
    PN512_Write(0×01,0×0C); // Transceive command
    PN512_Write(0×1D,0×80); // Transmit 8 bit length
    Good luck
    Mustafa

    • Trong Quyen

      Hi Mustafa,

      Thank for your feedback.
      I’m sure 100% that other commands are working.
      With this PN512 config, I’ve used to communicate with mifare UL successfully.
      My code is:

      void PN512_Config(void)
      {
      PN512_Write(0x01,0x0F); // Soft reset
      PN512_Write(0x0C,0x10); // Initiator
      PN512_Write(0x15,0x40); // 100% ASK
      PN512_Write(0x18,0x55); //
      PN512_Write(0x19,0x4D); //
      PN512_Write(0x26,0x59); //
      PN512_Write(0x27,0xF4); //
      PN512_Write(0x14,0x83); //
      PN512_Write(0x01,0x0C); // Transceive
      }
      void Mifare_REQA(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x26);
      PN512_Read(0x0A);
      PN512_Write(0x0D,0x87);
      }
      void Mifare_ATQ(void)
      {
      PN512_Read(0x06);
      PN512_Read(0x0A);
      PN512_Read(0x09);
      PN512_Read(0x09);
      }
      //
      void Mifare_Anticoll_1(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x93);
      PN512_Write(0x09,0x20);
      PN512_Write(0x12,0x00);
      PN512_Write(0x13,0x00);
      PN512_Write(0x0D,0x80);
      }
      void Respond_SNR_1(void)
      {
      PN512_Read(0x06);
      PN512_Read(0x0A);
      MifareCard_UID[0] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[1] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[2] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[3] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[4] = UART0_Putc(PN512_Read(0x09));
      }
      void Mifare_Select_1(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x93);
      PN512_Write(0x09,0x70);
      PN512_Write(0x12,0x80);
      PN512_Write(0x13,0x80);
      PN512_Write(0x09,MifareCard_UID[0]);
      PN512_Write(0x09,MifareCard_UID[1]);
      PN512_Write(0x09,MifareCard_UID[2]);
      PN512_Write(0x09,MifareCard_UID[3]);
      PN512_Write(0x09,MifareCard_UID[4]);
      PN512_Write(0x0D,0x80);
      }
      void Mifare_Anticoll_2(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x95);
      PN512_Write(0x09,0x20);
      PN512_Write(0x12,0x00);
      PN512_Write(0x13,0x00);
      PN512_Write(0x0D,0x80);
      }
      void Respond_SNR_2(void)
      {
      PN512_Read(0x06);
      PN512_Read(0x0A);
      MifareCard_UID[0] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[1] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[2] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[3] = UART0_Putc(PN512_Read(0x09));
      MifareCard_UID[4] = UART0_Putc(PN512_Read(0x09));
      }
      void Mifare_Select_2(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x95);
      PN512_Write(0x09,0x70);
      PN512_Write(0x12,0x80);
      PN512_Write(0x13,0x80);
      PN512_Write(0x09,MifareCard_UID[0]); // Data from Respond SNR
      PN512_Write(0x09,MifareCard_UID[1]);
      PN512_Write(0x09,MifareCard_UID[2]);
      PN512_Write(0x09,MifareCard_UID[3]);
      PN512_Write(0x09,MifareCard_UID[4]);
      PN512_Write(0x0D,0x80);
      }
      void Respond_SAK(void)
      {
      PN512_Read(0x06);
      PN512_Read(0x0A);
      PN512_Read(0x09);
      }
      //
      void RFID_Process(void)
      {
      PN512_Config();
      Mifare_REQA();
      Mifare_ATQ();
      Mifare_Anticoll_1();
      Respond_SNR_1();
      Mifare_Select_1();
      Respond_SAK();
      ReadData_PN512();
      LCD_cls();
      // STS Process /
      STS_Process();
      }
      void RATS(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0xE0);
      PN512_Write(0x09,0x00);
      PN512_Write(0x12,0x80);
      PN512_Write(0x13,0x80);
      PN512_Write(0x0D,0x80);
      //
      PN512_Read(0x06);
      PN512_Read(0x0A);
      UART0_Putc(PN512_Read(0x09));
      UART0_Putc(PN512_Read(0x09));
      UART0_Putc(PN512_Read(0x09));
      UART0_Putc(PN512_Read(0x09));
      UART0_Putc(PN512_Read(0x09));
      UART0_Putc(PN512_Read(0x09));
      }
      void PPS(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0xD0);
      PN512_Write(0x09,0x11);
      PN512_Write(0x09,0x00);
      PN512_Write(0x12,0x80);
      PN512_Write(0x13,0x80);
      PN512_Write(0x0D,0x80);
      //
      PN512_Read(0x06);
      PN512_Read(0x0A);
      PN512_Read(0x09);
      }

      void AID_Select(void)
      {
      PN512_Write(0x0A,0x80);
      PN512_Write(0x09,0x5A); // Native select PICC
      PN512_Write(0x09,0x00);
      PN512_Write(0x09,0x00);
      PN512_Write(0x09,0x00);
      //
      PN512_Write(0x12,0x00); // Disable TX,RX CRC
      PN512_Write(0x13,0x00); // (Enable CRC: 0x80)
      PN512_Write(0x1D,0x00); // Enable parity
      PN512_Write(0x01,0x0C); // Transceive
      PN512_Write(0x0D,0x80); // Transmit
      //
      PN512_Read(0x06); // 0x00: No Error Status
      UART0_Putc(PN512_Read(0x0A)); // 0x00 -> 0 byte in buffer -> there is no response? It should be 1
      UART0_Putc(PN512_Read(0x09)); // It should be 0x00
      }
      void RFID_Desfire(void)
      {
      PN512_Config();
      Mifare_REQA();
      Mifare_ATQ();
      Mifare_Anticoll_1();
      Respond_SNR_1();
      Mifare_Select_1();
      Respond_SAK();
      Mifare_Anticoll_2();
      Respond_SNR_2();
      Mifare_Select_2();
      Respond_SAK();
      RATS();
      PPS();
      AID_Select();
      }

      As you see, I’ve put some data bytes to the terminal:
      – The first 16 bytes:
      88 04 6A 54 B2 21 80 1D 80 3C 06 75 77 81 02 80
      -> CT- UID[3] – BCC1 – UID[4] – BCC2 – ATS[6]

      – The last 2 bytes:
      00 77 -> FIFO Level after read command – The response of SelectApplication 5A 00 00 00
      -> They should be: 01 00
      It means that there is no answer from PICC after SelectApplication command

      I’ve tried follow your guide in AID_Select() function.
      Please give me your comments and suggestions.
      Thank you very much.

      Best regards,
      Trong Quyen

      • Trong Quyen

        HI Mustafa,

        Now, I’m trying to communicate with Mifare Desfire EV1, but using the commands of MF3ICD40 Desfire.
        Perhaps, the commands of Desfire EV1 are different from Desfire.
        Do you think so?

        Best regards,
        Trong Quyen

  • Mustafa Moripek

    Hi Trong,
    I see that you enable CRC for TX and RX within
    commands RATS and SELECT.Why do you disable
    CRC in Select Application command.With the
    instructions I have mentioned previously I always
    can select application.
    Mustafa

  • Trong Quyen

    Hi Mustafa,

    Follow the datasheet of MF3ICD40, some commands need CRC and some commands don’t need.
    Example:
    – REQA, CL1, CL2: Don’t need CRC
    – Select_CL1, Select_CL2, RATS, PPS: Need CRC

    And also follow datasheet of MF3ICD40, i don’t see CRC was appended follow the native command frames.
    However, I’ve also tried with CRC, but the results are same, there is no answer from PICC.

    Do you think the commands of Desfire EV1 and Desfire are same?
    Now I’m working with Desfire EV1 (MF3ICD41) but using the commands of Desfire (MF3ICD40).
    Because I don’t find any datasheet about MF3ICD41 on Internet.

    Follow the datasheet, it seems too easy to implement some commands as GetVersion, SelectApplication…
    I see the native commands are not too different from other commands like REQA, RATS, PPS…But in fact…

    Please see the code again and help me to find if i’ve missed any step.
    Thank you very much.

    Best regards,
    Trong Quyen

  • Mustafa Moripek

    Hi Trong,
    my code looks like :
    PN512_Write(0x0A,0×80);
    PN512_Write(0x12,0×80);
    PN512_Write(0x13,0×80);
    PN512_Write(0x1D,0×00);
    PN512_Write(0x09,0×5A);
    PN512_Write(0x0A,0×00);
    PN512_Write(0x0A,0×00);
    PN512_Write(0x0A,0×00);
    PN512_Write(0x01,0×0C);
    PN512_Write(0x1D,0×80);
    PN512_Read(0x0A);
    and is functioning well.I am not at office now.
    Tomorrow I will check with different card types
    and let you know the result.
    Mustafa

    • Trong Quyen

      Hi Mustafa,

      I think, you mean:
      void AID_Select(void)
      {
      PN512_Write(0x0A,0x80); // Flush FIFO
      PN512_Write(0x12,0x80); // Enable TX, RX CRC
      PN512_Write(0x13,0x80);
      PN512_Write(0x1D,0x00); // Enable parity
      PN512_Write(0x09,0x5A); // Native select PICC
      PN512_Write(0x09,0x00); // (Not 0x0A)
      PN512_Write(0x09,0x00);
      PN512_Write(0x09,0x00);
      //
      PN512_Write(0x01,0x0C); // Transceive
      PN512_Write(0x0D,0x80); // Transmit 8 bit, (not 0x1D)
      //
      PN512_Read(0x0A);
      }
      Maybe, you’re missing in typing (0x09 instead of 0x0A, and 0x0D instead of 0x1D)
      Note:
      0x09: FIFO
      0x0A: FIFOLevel
      0x0D: BitFramingReg

      Follow datasheet, I think the section of code above is correct.
      But in fact, there is still no answer from PICC.

      And, what do you think about the steps:
      void RFID_Desfire(void)
      {
      PN512_Config();
      Mifare_REQA();
      Mifare_ATQ();
      Mifare_Anticoll_1();
      Respond_SNR_1();
      Mifare_Select_1();
      Respond_SAK();
      Mifare_Anticoll_2();
      Respond_SNR_2();
      Mifare_Select_2();
      Respond_SAK();
      RATS(); // E0 80
      PPS(); // D0 11 00
      // Fail from here
      AID_Select();
      }

      I think, after RATS and PSS, I have to do some config else follow ISO 14443-3, ISO 14443-4.
      But I don’t know what it is.

      I also ask for help to the guy from Mifare Team, but I don’t understand his answer, perhaps you do.

      http://www.mifare.net/micommunity/forum/mifare-smartcard-ics/mifare-desfire/using-pn512-communicate-mifare-desfire-ev1-card/#msg2333

      And, could you try this code in your side (if you have the hardware PN512)?
      Thank for your ardor.

      Best regards,
      Trong Quyen

  • Mustafa Moripek

    Hi Trong,
    yes you are right the 0A’s schould be 09,but
    1D is correct (ManualRCVReg 0x1D).Without this it
    doesn’t work properly.I have seen your conversation
    at the above link.In my code I have also a
    routine for exchange data with picc usin T=CL protocol.
    But I am not sure whether it is neccessary ,I
    have to test it.But it takes some times because
    I have to make some changes on my test pcb.
    I let you know when I have the result.
    Mustafa

  • Mustafa Moripek

    Hi Trong,
    I have checked the select application command.
    Yes you should use PCB.And the command should
    look like:
    void AID_Select(void)
    {
    PN512_Write(0x0A,0×80); // Flush FIFO
    PN512_Write(0×12,0×80); // Enable TX, RX CRC
    PN512_Write(0×13,0×80);
    PN512_Write(0x1D,0×00); // Enable parity
    PN512_Write(0x09,0×0A); // PCB
    PN512_Write(0x09,0×00); // CID
    PN512_Write(0×09,0x5A); // Native select PICC
    PN512_Write(0×09,0×00);
    PN512_Write(0×09,0×00);
    PN512_Write(0×09,0×00);
    //
    PN512_Write(0×01,0x0C); // Transceive
    PN512_Write(0x0D,0×80); // Transmit 8 bit, (not 0x1D)
    //
    PN512_Read(0x0A);
    }
    For I used CID and no NAD PCB is 0A.
    If you don’t use CID nor NAD the PCB should 02.
    And “transmit 8 bit” should be writen to register
    0D not to 1D (as you recognized correctly).
    Good luck
    Mustafa

  • Trong Quyen

    Hi Mustafa,

    Thank for your help.
    Now, I can implement the SelectApplication function.
    I’ll need your more help about RFID, SAM AV1,2 on next time.
    Thank you once more time.

    Best regards,
    Trong Quyen

  • Rasmus

    Hello.

    Ive been trying for several days to get the change key command to work.
    I have been reading alot of these comments, which helped me get the authentication working.

    Now im trying to change the 1. key in the selected application.

    Selecting Application.

    Authentication with default key all 0x00.
    Random A : E8-02-25-BD-DD-6D-DE-8B
    Random B : 09-73-7F-BB-21-E8-FB-13
    Session Key : E8-02-25-BD-09-73-7F-BB-DD-6D-DE-8B-21-E8-FB-13

    Change Key 1 to
    00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F

    Using first half of the session key to create the create the command.

    Block 1
    00-01-02-03-04-05-06-07

    Block 2
    08-09-0A-0B-0C-0D-0E-0F

    Block 3
    77-F5-00-00-00-00-00-00

    Doing the XOR/deciphering on each block.

    Block 1
    5A-9E-99-DC-1C-D2-1F-46

    Block 2
    64-5F-4D-BE-80-BA-DF-C8

    Block 3
    A5-F0-46-33-E3-3F-4A-83

    APDU Command :
    90-C4-00-00-19-01-5A-9E-99-DC-1C-D2-1F-46-64-5F-4D-BE-80-BA-DF-C8-A5-F0-46-33-E3-3F-4A-83-00

    I get the 0x1E Error.

    Hope someone is able to tell me what im doing wrong.

    Best Regards
    Rasmus

  • SN

    Hi all ,
    I need help in implementing ISO-7816 command set supported by MIFARE DESFire. I am able to implement basic native commands but implementing iso commands is seeming difficult.Can someone give an example for implementing APPEND RECORD Command(INS-‘E2’).

    Regards
    SN

  • Tom

    Hi Mustafa,

    I got a problem about ATS.. Here i am trying to use configured ATS with my Desfire EV1 card… But i need to get my Old ATS(ATS already in the card) and Append before newly configured ATS data such as

    [Old ATS] + [My New Data] = Newly configured ATS.

    What i need to know is how i get the ATS from the card.. In specs they provide that command begins with E0 will give ATS… But i unabl eto do that.. Please note that i use a ACS PC/SC reader to retrieve ATS.. Please help me ..

    Thanks.

  • Mustafa Moripek

    Hi Tom,
    the format for request answer to select command is :
    E0 Parameter CRC0 CRC1
    The high nibble of the parameter byte is maximum
    frame size and the low nibble is CID (logical
    number of addressed PICC).
    Mustafa

  • Giwrgos V

    Hello all! First of all i would like to thank all the people that have shared here their information 🙂
    I have successfully done some basic operations of desfire card like authentication, file creation/read/write. I have been faced a really strange problem. I have created i std DataFile with the appropriate command :
    Command: 91 CD 00 00 07 00 00 0E 0E A0 00 00 00
    Response: 91 0E

    I know the error means “Insufficient NV-Memory to complete command” , the weird thing is that i have successfully created one std data file at first. Then i deleted it and tried to create a different one (with the same FileNo), every time i was trying to create the file i was able to use less file size until now that i can’t use any file size! I tried even to remove the application and create it from scratch and now i am getting the same error at the create Application command! Is that the normal behavior of the card, should i try to format it?
    Any help will be really appreciated!
    Thanks for your time anyway!

  • Mustafa Moripek

    Hi Giwrgos,
    allocated memory blocks associated with the delete files
    are not set free.To release memory blocks for reuse,the
    whole NV-memory needs to be erased using the
    Format command.
    Mustafa

  • Ali

    Hi
    I want to get the list of all of Applet in java card.
    I Select MasterAplet and do pin verify with it.
    My question is how
    can i get the list of all of AID in java card?

  • Giwrgos V

    Hello ali! The command you are looking for is the GetApplicationIDs(). The command code (without wrapping) is 0x6A. If you send this byte to the card you will get a response with the application aids! The first response will have untill 19 Aids, if your card has more than 19 applications the response will start with byte 0xAF which means that you have to send the byte 0xAF to the card to get the rest of the aids.

  • Ali

    Hello Giwrgos .
    Thank you.
    I think 90 6a get the AID of a Desfire card. I send this APDU and receive all of AID of a Desfire card.My problem is what can i get the AID of the all of applets on a SAM card.If your answer is 6a would you mind specify me the calss and instruction of this command.

  • Ben Spinner

    I am having a problem with Authentication of AES. Really I am trying to decrypt the message after authentication. My authentication is a success and I am trying to decrypt the return message and verify it against RANDA and I can’t seem to decrypt it properly. I have managed to do this successfully with DES. I am pretty sure that it has something to do with my IV for AES. I start with 16 byte 0x00 array to encrypt the message after that I am not sure what to use as my IV. Any help would be greatly appreciated

    • Coenos

      Hi Ben,

      could you give me an example of AES authentication sequence ?(assuming you are building in java)
      That would be of great help 🙂
      Thanks,
      Coenps

  • Arcariane

    A bit advertising but could be helpful for some people. Just started a new open source sdk project (LGPL license) for RFID development with various chips and readers supported.
    Developed in C++, can be called in C# through a COM layer: http://liblogicalaccess.islog.com
    DESFire en DESFire EV1 support, but key diversification and SAM still need to be implemented.

  • Amila

    Hi All,

    Can someone propose a good Plastic Card Printer we can use for printing Desfire platic cards.

  • Miha

    I’m trying to create standard file after the authentication (1A). Authentication works, I have right crc algorithm, but when I send the command i get 917E response: length error. I’m using DES encryption

    Session key:
    0BE19314EA2A362E0BE19314EA2A362E

    Command before crc, padding and encryption:
    90CD0000090200000311110F000000

    data with crc32 and padding:
    0200000311110F000045812F87800000

    APDU Encr: 90 CD 00 00 10 C2 5F 1C B0 79 D7 12 84 DF 8F EE CC F5 25 DD 5F 00
    Receiving data

    Does anyone know what’s my problem?

  • Mustafa Moripek

    Hi Miha,
    I don’t know wether you have solved the problem
    already.As far as can see, the issue is that you
    haven’t append the CMAC.If you authenticate
    in TDES stnadard mode ( with command 0X1A)
    you have to append CMAC.
    Mustafa

  • Coenos

    Hi I’m doing AES authentication and here is the result, I get CA returns and the AE. what am I missing?

    05-29 12:07:39.675: V/VRS_DEBUG(30570): GET VERSION: 60
    05-29 12:07:39.685: V/VRS_DEBUG(30570): Result: AF04010101001A05
    05-29 12:07:39.685: V/VRS_DEBUG(30570): GET VERSION: AF
    05-29 12:07:39.690: V/VRS_DEBUG(30570): Result: AF04010101031A05
    05-29 12:07:39.690: V/VRS_DEBUG(30570): GET APPLICATION IDs: 6A
    05-29 12:07:39.700: V/VRS_DEBUG(30570): Result: CA
    05-29 12:07:39.700: V/VRS_DEBUG(30570): SELECT VRS APP: 5AB013F5
    05-29 12:07:39.705: V/VRS_DEBUG(30570): Result: 00
    05-29 12:07:39.705: V/VRS_DEBUG(30570): AES AUTH: AA00
    05-29 12:07:39.720: V/VRS_DEBUG(30570): Result: AFB3A43E813F6985F3E566E1060F5A7DA3
    05-29 12:07:39.720: V/VRS_DEBUG(30570): AUTH KEY: 2F920CE517274066BD04E24CDD0FE7CF
    05-29 12:07:39.730: V/VRS_DEBUG(30570): Result: CA
    05-29 12:07:39.730: V/VRS_DEBUG(30570): GET VRS FILE ID: 6F
    05-29 12:07:39.735: V/VRS_DEBUG(30570): Result: AE
    05-29 12:07:39.735: V/VRS_DEBUG(30570): GET VRS KEY SETTINGS: 45
    05-29 12:07:39.740: V/VRS_DEBUG(30570): Result: AE
    05-29 12:07:39.740: V/VRS_DEBUG(30570): GET VRS KEY VERSION: 6400
    05-29 12:07:39.745: V/VRS_DEBUG(30570): Result: 0000

  • Sajith

    Hi i am doing AES authentication using java(not using native commands) so i refered the NXP documentation.and i also use SCL010 reader to read mifare desfire ev1 card read and write.so i am new to nfc related java secure element development.so i read the authentication flow and how it works.i already implemented the java library for read the data from desfire card.can anyone tell me how to authenticate using java (if have any code implementation it will help so much)

    Thanks
    SSV

  • janex

    Hi all,
    I have problem with Mifare DESFire EV1 AES authentication.
    Please look at my communication flow:
    http://pastebin.com/CaC8nj7p

    My AES encryption method:
    http://pastebin.com/N4gxkehE

    I encrypt with 16byte IV (all 0x00).

    My encryption method is incorrect or there is something wrong with randoms computations?

    Thanks

  • Zack

    Mustafa, If you are still monitoring this blog I was hoping I could get your advice. I have come back to trying to change the key on the card after a long break because of other project, and I still get this integrity error 0x1E.

    After looking at a lot of the other comments on the blog, I figured it must be 1. Generating the session key, 2. the method used for encryption 3. the chaining used when actually attempting to change the key.

    old key 0x00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
    IV 0x00-00-00-00
    new key 0x00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F

    So first i authenticate with the default key:
    Authenticating
    Send command, Recieve Encrypted number
    Encrypted RND-B: 0x26-F1-FC-86-59-E9-F3-C6

    Create response data
    Decrypted RND-B: 0x48-54-77-A8-D0-90-D9-D5
    Decrypted, Rotated RND-B: 0x54-77-A8-D0-90-D9-D5-48
    RND-A: 0x18-A4-50-9E-B6-5F-70-2E
    Appended RND-A + RND-B: 0x18-A4-50-9E-B6-5F-70-2E-54-77-A8-D0-90-D9-D5-48

    Encrypted Appended RND-A + RND-B: 0x62-F2-1E-05-F8-63-7B-2B-29-43-3B-DD-B3-87-E3-D4

    Send command reply bundle with encrypted information
    Decrypt returned data
    Returned RND-A rotated and encrypted: 0xDD-4F-27-77-0B-97-75-16
    Returned RND-A rotated and decrypted: 0xA4-50-9E-B6-5F-70-2E-18
    Returned RND-A decrypted: 18-A4-50-9E-B6-5F-70-2E
    Success
    Generate Session Key
    Session Key: 18-A4-50-9E-48-54-77-A8

    Then from this i try to change the key:

    R1 = 01-00-03-02-05-04-07-06
    R2 = 49-A5-6B-95-06-78-EE-35
    R3 = 41-AC-61-9E-0A-75-E0-3A
    R4 = 8C-B1-A1-99-BF-9E-04-59
    R5 = FB-44-A1-99-BF-9E-04-59
    R6 = 27-07-66-26-33-5A-B2-63

    so R2 with R4 with R6 will give:
    49-A5-6B-95-06-78-EE-35-8C-B1-A1-99-BF-9E-04-59-27-07-66-26-33-5A-B2-63

    and the final apdu:

    90-C4-00-00-19-00-49-A5-6B-95-06-78-EE-35-8C-B1-A1-99-BF-9E-04-59-27-07-66-26-33-5A-B2-63-00

    At first I assumed it must be something wrong with my changekey function an generating the apdu, but I have tested the output with all the relevant data i can find on this blog and it matches the output. That also means that my encryption functions should also be valid if they are matching all the valid encrypted output I have seen on this blog. So the only remaining cause I can think of is that I am generating the session key incorrectly. But I cannot see where this is occurring.

    Is there something perhaps you could see pleeeeeeeeaaaaassseeee?

  • Mustafa Moripek

    Hi Zack,
    I think your DES decryption algorithm
    is not correct.When decrypting your new key
    with your session key
    (18-A4-50-9E-48-54-77-A8-
    18-A4-50-9E-48-54-77-A8) I have got :
    R2=F7-11-62-12-75-8B-21-14
    Don’t forget you have to decrypt
    your data when sending to the PICC.
    Mustafa

    • Zack

      Hi Mustafa, As it turns out I was using an incorrect previous key for the operation. (It was all 1s and not all 0s) I have fixed it but I am still getting the same error. Also note that by changing the old key being used to the correct one, my output data matched the data you stated in your previous comment. So with the latest attempt I got the following data, using the same code that I used to match the input data to your output:

      Authenticating
      Send command, Recieve Encrypted number
      Encrypted RND-B: DF-4A-95-96-B9-4E-6B-72

      Create response data
      Decrypted RND-B: 30-94-0E-D4-43-DD-14-6E
      Decrypted, Rotated RND-B: 94-0E-D4-43-DD-14-6E-30
      RND-A: F7-05-45-7C-4F-9E-09-AA
      Appended RND-A + RND-B: F7-05-45-7C-4F-9E-09-AA-94-0E-D4-43-DD-14-6E-30

      Encrypted Appended RND-A + RND-B: 27-BD-F6-36-42-6F-B6-0E-4D-96-81-17-7E-89-8A-0A

      Send command reply bundle with encrypted information
      Decrypt returned data
      Returned RND-A rotated and encrypted: 27-FA-82-6B-18-20-64-3E
      Returned RND-A rotated and decrypted: 05-45-7C-4F-9E-09-AA-F7
      Returned RND-A decrypted: F7-05-45-7C-4F-9E-09-AA
      Success

      Generate Session Key
      Session Key: F7-05-45-7C-30-94-0E-D4

      R1 = 00-01-02-03-04-05-06-07
      R2 = CE-EA-5A-C0-88-9E-6D-B8
      R3 = C6-E3-50-CB-84-93-63-B7
      R4 = EE-C9-25-44-56-F4-A4-3B
      R5 = 99-3C-25-44-56-F4-A4-3B
      R6 = D3-78-DB-D1-56-EC-68-64

      If this is correct this time, then I can only imagine the problem being with generating the session key. But having said that if there was a problem handling RNDA and RNDB I would imagine that the authentication procedure would have failed.

      Zack

  • Mustafa Moripek

    Hi Zack,
    the problem is not the key,your DES
    decrypting algorithm does not working
    properly.With your new session key
    I have got R2=AE-33-02-58-A9-B0-A0-43.
    Mustafa

    • Zack

      But I use the exact same code I used to get
      R2 = F7-11-62-12-75-8B-21-14
      using Session key = 18-A4-50-9E-48-54-77-A8

      Literally the only thing I have done to the code is switch out the old session key for the new one and I get the R2 I gave you in my last message. How can it be correct in one case and not the other given that the session key is the only thing that is different?

      Zack

  • Mustafa Moripek

    Hi Zack,
    sorry I couldn’t answer earlier,for I was so busy.
    I checked your data again and you are right
    your calculation is O.K.Last time I made a
    mistake when copiying your session key in
    to my program.The 1E (integrity error) has
    to do with CRC error.It has nothing to do with
    session key.If you successfully authenticate
    then the session key is O.K.I checked your
    CRC wich is also correct.
    Are you changing the key with which
    you authenticate.If the key number you
    are authenticating with is different then the
    number you want change then you have to
    proceed as follows:
    16 Bytes new key xored with the old key +CRC16
    of the old key xored with the new key +CRC16 of
    the new key +padding.
    I hope this information helps you,
    good luck.
    Mustafa

    • Zack

      Hi Mustafa,
      Thanks for trying. Yes I am trying to change the masterkey from the default all zero key. So I am authenticating with the all zero key (slot 0) and trying to change that to the one I have been typing out in the examples I have been posting :S

      ah, let the ever continuing head/wall bashing commence.

      Thanks, Zack

  • Ali

    Hi Zack
    I changed master key in native Authentication and could not change master key in iso mode.
    if this help you tell me and i tell you how change master keyin native mode.
    Ali

    • Zack

      Hi Ali,
      I didn’t even know changing the key in iso mode was a possibility, I have been using the native wrapped command style with an omnikey 5321 v2 CL desktop reader
      Zack

  • Pat

    Hi Ali,
    Like Zak I am using the omnikey 5321 v2 and wrapping the command but keep getting the CRC / Mac error. I have attempted both native and ISO mode and cant get it to change from default key values to my new key. I would be interested to see how you done it.
    Paddy

  • Ali

    Hi Zack
    that is right .Authentication in native mode has a complicated command.

  • janex

    Hi,
    I authenticated using AES (0xAA), generated correct session key, but I cannot read file (crypto mode 0x03).
    My CMAC method is working good.

    Here’s my flow (i call getFile just after auth, so IV is reset to 00):

    1. getFileCommand
    >90BD000007 (Le) 00 (fileNo) 000000 (offset) 0B0000 (dataLength) 00

    2. getFileResponse
    <136767D408D92616D64DFB463902030D 9100(ok)

    3. IV = CMAC(getFileCommand) using session key.
    Should I CMAC whole command (90BD000007000000000B000000)?

    4. decrypt trimmed (without 9100 suffix) getFileResponse – using AES secret key and IV updated in 3.

    I should now see data+crc32(data)+padding,
    but I make mistake somewhere and cannot read data from file.

    Any ideas what is wrong in my flow?

    • Coenos

      Can you post your entire sequence ?

    • juvee

      Hi,

      I have same problem. There are my sequence:

      Authentication process:
      – – – – – – – – – – – –
      send: 0xAA
      rec: AF 5C4D8C128BE281D5C2D9435FCD0E7C07
      send: AF 0BCAEF0F2E626798A70B5931E25E4909 F4299ACFCAE70E2413CC76EC00341905
      rec: AB0E8BA8F605C19F865207FBFA5B23F8

      AES-sessionkey: 001122334FA059774455667750317546
      RndA: 00112233445566770011223344556677
      RndA2: 11223344556677001122334455667700
      RndB: 4FA05977503175466103D579CE0EC8E9
      RndB2: A05977503175466103D579CE0EC8E94F

      is my session key [1st 4 byte randA; 1st 4 byte randB; 2nd 4byte randA; 2nd 4byte randB] correct?

      after generate session key successfully, i will read file. Which I use as initial vector if i decrypt that message?
      is AB0E8BA8F605C19F865207FBFA5B23F8 right?

  • wei

    Hi,

    I had some authentication problems with desfire.Below is the log of the authentication processs

    to card: 90 5A 00 00 03 00 00 00 00
    from card; 91 00
    to card: 90 0A 00 00 01 00 00
    from card: 02 61 59 3C 85 71 C4 F9 91 AF
    to card: 90 AF 00 00 10 9D 82 EA 76 08 94 34 05 B9 1B A9 3D 6B 14 CB 54 00
    from card: 69 85

    Ek(RndB) = 02 61 59 3C 85 71 C4 F9
    RndB = 2E A9 16 97 7D 6F 39 51
    RndB<<8 = A9 16 97 7D 6F 39 51 2E
    RndA = C5 4F D1 24 4E DE B5 2F
    Dk(RndA + RndB') = 9D 82 EA 76 08 94 34 05 B9 1B A9 3D 6B 14 CB 54

    Here are fragment of my code:

    Public Function DesfireCryto(ByVal recvRndB As Byte(), ByRef sentRndA As Byte()) As Boolean

    Dim rndB_Ek() As Byte = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
    For i = 0 To 7
    rndB_Ek(i) = recvRndB(i)
    Next

    ' RndB = Decipher Ek(RndB)
    Dim rndB(7) As Byte
    Dim default_Key() As Byte = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
    DecryptWithTriDes(rndB_Ek, default_Key, rndB)

    ' RndB' = RndB << 8
    Dim rndB_LeftShift(7) As Byte
    For i = 0 To 6
    rndB_LeftShift(i) = rndB(i + 1)
    Next
    rndB_LeftShift(7) = rndB(0)

    ' RndA = New Generator Pseudo-Random number
    Dim rndA(7) As Byte
    System.Security.Cryptography.RandomNumberGenerator.Create.GetNonZeroBytes(rndA)

    ' Concatenate RndA + RndB'
    Dim rndA_Concat_rndB(15) As Byte
    For i = 0 To 15
    If i < 8 Then
    rndA_Concat_rndB(i) = rndA(i)
    Else
    rndA_Concat_rndB(i) = rndB_LeftShift(i – 8)
    End If
    Next

    'Dim final_output(15) As Byte
    DecryptWithTriDes(rndA_Concat_rndB, default_Key, sentRndA)

    End Function

    Public Sub DecryptWithTriDes(ByVal original_data As Byte(), ByVal key As Byte(), ByRef decipher_data As Byte())

    Dim tDESalg As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()

    'tDESalg.Key = key
    tDESalg.Mode = CipherMode.CBC
    tDESalg.Padding = PaddingMode.Zeros
    tDESalg.IV = New Byte() {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

    Dim mi As MethodInfo = tDESalg.GetType().GetMethod("_NewEncryptor", BindingFlags.NonPublic Or BindingFlags.Instance)
    Dim par() As Object = {key, tDESalg.Mode, tDESalg.IV, tDESalg.FeedbackSize, 0}
    Dim tDesDecryptor As ICryptoTransform = mi.Invoke(tDESalg, par)

    Dim mStream As MemoryStream = New MemoryStream(original_data)
    Dim cStream As CryptoStream = New CryptoStream(mStream, tDesDecryptor, CryptoStreamMode.Read)

    cStream.Read(original_data, 0, original_data.Length)
    decipher_data = mStream.ToArray()

    cStream.Close()
    mStream.Close()

    End Sub

    Please help to identify my error. thank.

  • Quy Nguyen

    Hi Mustafa,

    I created a linear record file with FID 02.(record size is 4 bytes,number of record is 31).

    I have written successfully:90 3b 00 00 0a 02 00 00 00 03 00 00 11 22 33 00

    I want to read three records,and my APDU command is:
    90 bb 00 00 07 02 00 00 00 03 00 00 00
    The result is 91BE.I absolutely understand the meaning but i couldn’t find out to reuse it.Would you help me?
    Sincery,

  • Giwrgos V.

    Hello again! I am trying to write the data of a 1455 byte file into a std data file.
    I have created the file with the appropriate size: 0xAF 0X05 0x00
    Then i would like to add the actual data, so the first command i send is the following :
    90 [3D] 00 00 3B [01] [00 00 00] [AF 05 00] [00 00 00 02 00 00 00 14 54 18 A1 DA DC 56 8E 8A 1E 77 34 CA EE 21 0C FB BE 93 C6 46 00 00 06 B9 04 00 01 31 00 00 01 40 4D F4 EA 26 00 00 00 01 00 05 58 2E] 00

    I have put in brackets the command parameters with the following order : Cmd – File no – Offset – Length – Data
    I hope its easier to read now 😉

    But i am getting the following error:
    android.nfc.TagLostException: Tag was lost.
    android.nfc.TransceiveResult.getResponseOrThrow(TransceiveResult.java:48)

    The error occurred at the transceive command and i dont have any idea what it is! I have successfully written small amount of data (less than 53).

    I am assuming the problem is that the tag doesn’t reply with the “AF” command on time but this is just a thought.

    Did anyone have faced this problem ?

    Thanks in advance!

    • Giwrgos V.

      I have done some tests and found the solution! I have found that if the data length are max 47 bytes i can write big files without problems! So instead of the 52 bytes limit that is written on Phillips Product Specification document the actual limit is 47 bytes for the first command and 54 (instead of 59) for every other!

  • kasun

    Hi all, Im working on a smart card project, This is my first, so i could im using defire ev1 card, i could connect the card and iv done till creating an application.. the apdu i used is

    90 CA 00 00 05 00 00 03 01 04 00

    i got the 9100 as operation successful.

    But when i tried to create and std data file using

    90 CD 00 00 07 01 03 47 31 0F 00 00 00

    919E – parameter error occured,

    i dont know much about Access Rights communication settings.

    i think those parameters are invalid here.

    pls can any one tell me what is the correct APDU to create a std data file.

    Thanks..

    • Shehzad

      Hi kasun,

      Here, you have defined that you would be using only 4 keys in your application. In your create std data file command just try using numbers between 0 – 3 for the access rights and i think this should get you through.

  • Jerry Wood

    Thanks to everyone who has unknowingly helped me out :-).

    I have managed to succesfully des authenticate a desfire EV1, then change the PICC master key to AES. What I am struggling with now is the process to authenticate the AES key. (This is mainly because I haven’t yet got NXP to reply so I can get the documentation under an NDA.)

    I have working code for aes encryption & crc32 but it is not clear to me going through the examples above what the actual steps for aes are. Can anyone please explain the process and provide some example outputs so I can use them to verify/get the code in the right sequence?

    Just to be clear; I’m using desfire EV1, aes and trying to authenticate the PICC master key and getting the response 0xAE so the card is seeing what I’m sending but doesn’t like it. I don’t want to send any code output because I think it is completely wrong at this point and would confuse.

  • Shehzad

    Hi @all,

    I have been trying to write encrypted data to Desfire EV1 using SAM (AES encryption) but I am unable to do so.

    As with SAM, it can encrypt at the max 0xEC i.e. 236-bytes in one frame for AES encryption. But for example i want to write around 456 bytes of data to the Desfire card. So I am not able to figure out how the second frame should me made.

    The 1st command that i send is :
    80 – ED- AF – 08 – EC – [3D 07 000000 C80100 — 228 byte data –] – 00
    (within bracket is the DESFIRE cmd to be encrypted).
    SAM responds with the encrypted value.

    The next command that i send is :
    80 – ED- 00 – 08 – EC – [3D 07 000000 C80100 — next 228 byte data –] – 00
    SAM responds with the encrypted value.

    But, now I assume that this frame format is wrong hence the encrypted value is wrong and therefore after writing to DESFIRE card this entire encrypted value, I either get 0xAE (Authentication Error) or 0x7E(Length Error) as the error.

    I think somewhere the DESFIRE header that is passed in the next frame is wrong. Kindly help me to identify the problem here.

    Thanks in advance!

    • Shehzad

      Hi everyone,

      With trial and error, I seem to have got this SAM encryption proper.
      As I had guessed, the problem was in the frame formation for the 2nd chunk of 228 -bytes. The DESFIRE header was causing the problem.

      Finally, Relieved! 😉

      • Bruno Bertechini

        Can you please help me with the bais algorythm to use SAM together with DESFire EV1 ?

        Thanks a lot

        Bruno

      • Shehzad

        Hi Bruno,

        I can surely help you with it. But before that, can you tell me the actual configuration of the SAM that you are using i.e. (a) AV1 or AV2 mode
        (b) present key configuration (c) what type of key you are intended to use etc.

        Also, tell me have you worked with SAM or DESFIRE EV1 individually before?

        –Shehzad

  • Andras Liptak

    Dear All,
    I am struggling with AES perso for Desfire. i am simply can not prodcue the correct CRC32 result. I try to get the above written data:
    C40001020300000000000000000000000000
    CRC32 is: fd 25 74 8e

    But I have no success.
    Could you please sombody send me a tool which calculates the correct CRC32?
    Or what are the parameters: ploynom, XOR value, init vector, etc.
    thank you in advance for any help,
    Andras

  • Andras Liptak

    Hello again,

    I managed to calculate the correct CRC. e.g. using this site: _http://www.fileformat.info/tool/hash.htm. It gives a CRC32 data, and the final value is it’s inverze value.

    However my chnage key command is still not successful:
    -my session key is: 0001020343FC15310C0D0E0F64395E76
    -new key value: 11111111111111111111111111111111
    -data for CRC: C4001111111111111111111111111111111100
    -CRC32 is: 65b301cb
    -AES cipher data: 11111111111111111111111111111111 + 00 + 65b301cb + 0000000000000000000000

    -cipher text is: 4A3D048D512D767EA54E08C79EA177E3EB65780ECE86573C2C5B1B71BADE959C

    everything seems to be ok, but after I send my command, I get back error 0x1E.

    Does anyboday have idea what could be wrong?
    Thanks in advance for your comments,
    Andras

    • Shehzad

      Hi Andras,

      I think the CRC32 that you are attaching to your data is reversed i.e. it should be CB01B365. Try this and I think this will get you through.

      Also, make sure that your InitVector is initialized to zero before proceeding for changeKey command. DO NOT use the InitVector from the previous AES Authentication.

      -Shehzad

  • akdrmrk

    Hi

    I want to access mifare desfire ev1 4k..I am using for authenticate { 0xAF 0xA2 0x00 0x00 0x05 0x01 0x00 0x04 0x00 0x60 } , the software returned 90 00. so it can be authenticate with this APDU.

    Then; I want to update block 4 with { 0xAF 0xD6 0x00 0x4 0x16 } . the software returned 1C 90 00

    Then; I want to read block 4 with { 0xAF 0x0A 0x00 0x04 0x16 } . the software returned 90 00 and response 1C…it return 90 00 like true but don’t read and what is 1C. I don’t add it.

    Thanks…

    • Mustafa Moripek

      Hi akdrmrk
      1C means illegal comand code.Please
      write the whole communication so
      I can see where the issue is.
      Mustafa

      • akdrmrk

        Hi dear Mustafa;
        for authenticate;;
        ClearBuffers();
        SendBuff[0] = 0xAF;
        SendBuff[1] = 0×88;
        SendBuff[2] = 0×00;
        SendBuff[3] = 0×00;
        SendBuff[4] = 0×05;
        SendBuff[5] = 0×01;
        SendBuff[6] = 0×00;
        SendBuff[7] = 0×04;
        SendBuff[8] = 0×00;
        SendBuff[9] = 0×60;
        SendLen = 10;
        RecvLen = 3;
        retCode = SendAPDUandDisplay(0);
        if (retCode != ModuleDevice.SCARD_S_SUCCESS)
        {
        return;
        }
        it is returning 90 but is it true because I did not like “http://stackoverflow.com/questions/14319321/how-can-i-do-native-authentication-in-desfire-ev1″….
        for read block;
        string strRead;
        ClearBuffers();
        SendBuff[0] = 0xAF;
        SendBuff[1] = 0xB0;
        SendBuff[2] = 0×00;
        SendBuff[3] = (byte)(4);
        SendBuff[4] = (byte)(16);
        SendLen = 5;
        RecvLen = 16+2; //SendBuff[4] + 2;
        retCode = SendAPDUandDisplay(2);
        if (retCode != ModuleDevice.SCARD_S_SUCCESS)
        {
        return;
        }
        strRead = “”;
        for ( int indx = 0; indx <= RecvLen – 1; indx++)
        {
        strRead += (byte)(RecvBuff[indx]);
        }
        strRead = System.Text.Encoding.UTF8.GetString(RecvBuff);
        tbxUpdate.Text = strRead;
        it is returning 1C 90 00 …
        Thank you so much..

  • akdrmrk

    Hi dear Mustafa;

    for authenticate;;

    ClearBuffers();
    SendBuff[0] = 0xAF;
    SendBuff[1] = 0x88;
    SendBuff[2] = 0x00;
    SendBuff[3] = 0x00;
    SendBuff[4] = 0x05;
    SendBuff[5] = 0x01;
    SendBuff[6] = 0x00;
    SendBuff[7] = 0x04;
    SendBuff[8] = 0x00;
    SendBuff[9] = 0x60;

    SendLen = 10;
    RecvLen = 3;

    retCode = SendAPDUandDisplay(0);

    if (retCode != ModuleDevice.SCARD_S_SUCCESS)
    {

    return;

    }

    it is returning 90 but is it true because I did not like “http://stackoverflow.com/questions/14319321/how-can-i-do-native-authentication-in-desfire-ev1″….

    for read block;

    string strRead;
    ClearBuffers();
    SendBuff[0] = 0xAF;
    SendBuff[1] = 0xB0;
    SendBuff[2] = 0x00;
    SendBuff[3] = (byte)(4);
    SendBuff[4] = (byte)(16);

    SendLen = 5;
    RecvLen = 16+2; //SendBuff[4] + 2;

    retCode = SendAPDUandDisplay(2);

    if (retCode != ModuleDevice.SCARD_S_SUCCESS)
    {

    return;

    }
    strRead = “”;
    for ( int indx = 0; indx <= RecvLen – 1; indx++)
    {

    strRead += (byte)(RecvBuff[indx]);

    }

    strRead = System.Text.Encoding.UTF8.GetString(RecvBuff);
    tbxUpdate.Text = strRead;

    it is returning 1C 90 00 …

    Thank you so much..

    • Mustafa Moripek

      Hi there,
      what are you using for communicating with the
      card.What you send for authentication is not
      right.Apdu command for authentication is:
      90 0a 00 00 01 00 00
      At the beginning of this blog you can see
      the details.
      Mustafa

      • akdrmrk

        now I will use for record person information and credit…before some time , I learned access to mifare 1K classic but desfire ev1 is more complex than classic..

        After using to 90 0a 00 00 01 00 00 for authenticate, I can’t do update or read sector…it is returning 6E 00.

        I think; should be authenticate with using DES. Only sending APDU command (like classic) not enought. I can’t find to my needing information in NXP document.

        I have short time and have to improve myself.
        Can I communicate you on mail adress.
        ( a.kdr-mrk@hotmail.com )

        Thank you again

    • Shehzad

      Hi akdrmrk,

      The DESFIRE EV1 cards follow iso – 7816 format. Hence, they no longer use the term ‘sectors’ with the DESFIRE EV1 cards.
      Everything is grouped as Applications and files.

      I think, either you are using some other card or you are mistaking DESFIRE EV1 cards with MIFARE CLASSIC cards.

      For DESFIRE EV1, a 3-pass authentication is done i.e. 3 steps are involved to complete the authentication. Sending a single command wont help.

      Only after the authentication is complete, you should move ahead with reading or writing.

      -Shehzad

      • akdrmrk

        Hi Shehzad

        can you say list of 3 authentication steps…

        thanks

      • Shehzad

        Hi akdrmrk,

        Before we begin with the authentication, let us first create an application (a folder) in the DESFIRE EV1 card.

        Tell me what you get as a response if you give the following command to the EV1 card. (show the steps that you followed).

        CA 33 33 33 0F 0A (without any spaces)

        Also, tell me what reader you are using and the interface software through which you are sending commands to the card.

      • akdrmrk

        Hi there;

        I sent CA “33 33 33 0F 0A” and it responsed 00 90 00(completed)

        is it create application command?

        reader is ACR128-1U…

        thank you so much..

      • akdrmrk

        after som trying i it responsed DE 90 00

      • Shehzad Ansari

        Hi akdrmrk,

        CA3333330F0A is a create application command. It created an application with ID =333333. The ’00’ that you received before 9000 is the status byte for the command executed. Here it means success.

        Further when you tried this command again, the status byte was ‘DE’, which means DUPLICATE ERROR, as the application with the ID=333333 is already present it the card.

      • akdrmrk

        Hi again Shehzad;

        I created an application with ‘CA3333330F0A’ …Then I sent 90-0A-00-01-00-00 (begin authentication procedure)…

        it responsed me 1D-A4-56-2E-78-43-F6-CB (encrypted rndB)

        Now I should Decrypt and build Rondom B..

        I am sending to picc 1D-A4-56-2E-78-43-F6-CB (encrypted rndB), it returned 67 00..it is wrong way.

        How can I decrypt rndB?

  • Bruno Bertechini

    Hi there,

    Just want to confirm one thing regarding AES (ChangeKey)

    In order to change a blank card (default 0s master key) to a new AES key how should I create the session key ?

    Should I create it using the AES Session Key specs from DESFire EV1?

    Bruno

    • Shehzad

      Hi Bruno,

      In order to change the Appication Master Key (AMK), you should first AES_authenticate with the AMK.

      Once it is done, form the session key as per the DESFIRE EV1 document. (A format is given on how to form the session key using RandA and RandB).

      Then use this session key in the changeKey command and keep the InitVector initialized to zero. Do not use the InitVector obtained from the AES_authentication.

      Hope this would help.

      -Shehzad.

    • Shehzad

      Hi Bruno,

      For changing PICC Master Key, you have to authenticate with the existing PICC MASTER key first.

      So, for example, if this key is a STANDARD TDES KEY, then the session key that is generated will be a 16-byte STANDARD TDES one.

      (So you have to form the session key based on the existing key type of the master key (refer document for this) )

      You have to use this session key in your changeKey command.

      • Bruno

        Thanks Shehzad. But the default key (16bytes all zeroes) results in a DES Session Key with 8 bytes only (Rnda 1st half + RndB 1st half).

        I managed it to work to change the default key to a new AES Key. I can confirm that because my GetKeyVersion command results in 0x77 (AES).

        No I am having a hardtime to authenticate with AES.

        I always get 0xAE when sending the enc(RndA+RndB’) to the PICC.

        Bruno

  • Bruno

    Can someone please clarify the steps for AES Authentication:

    AES Master Key (Confirmed by GetKeyVersion = 0x77):
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F

    1. Send 0xAA
    [90 AA 00 00 01 00 00]

    2. Receive Encrypted(RndB) from PICC (16bytes)
    [7B 94 9E 6F F1 F3 0E 8E 0B AC E7 9C 65 6B C0 31]

    3. Decrypt RndB using MasterKey and IV = new byte[16]
    [AE E0 6A B1 D5 75 89 28 FD 1C 70 C7 D5 DD 46 4B]

    4. LeftShift RndB producing RndB’
    [E0 6A B1 D5 75 89 28 FD 1C 70 C7 D5 DD 46 4B AE]

    5. Generate RndA (16bytes)
    [A2 B0 D4 4F BF 55 C3 AB A3 70 DD 5A 2C C3 EF 5E]

    6. Concat(RndA, RndB’) Using IV = new byte[16]
    [A2 B0 D4 4F BF 55 C3 AB A3 70 DD 5A 2C C3 EF 5E E0 6A B1 D5 75 89 28 FD 1C 70 C7 D5 DD 46 4B AE]

    7. AESEncrypt(RndA + RndB’)
    [C8 4B 07 BE EB 96 24 B9 1E F0 9E 13 AB 61 05 4F 0D 61 76 83 69 06 12 4C 52 DC 2A BA 1F 99 15 E1]

    8. Send 90 AF + AESEncrypt(RndA + RndB’)
    [90 AF 00 00 20 C8 4B 07 BE EB 96 24 B9 1E F0 9E 13 AB 61 05 4F 0D 61 76 83 69 06 12 4C 52 DC 2A BA 1F 99 15 E1 00]

    Is that correct?

    Bruno

    • Mustafa Moripek

      Hi Bruno,
      Are you sure your AES algorithm is
      correct.I tried to verify your data but with
      your key I have got for RndB :
      D9 F8 7D F6 28 4E 01 FF EE 11 83 A7 B7 26 77 5D
      Your authentication steps are correct,I think
      the issue is in your AES decrypting / encrypting
      algorithm.Another important thing is that IV vector
      doesn’t reset after each step.
      Good Luck
      Mustafa

      • Bruno

        Thank you very much for your response Mustafa.

        I think I have 2 possibilities here:

        1. AES algorith is wrong.
        2. Change Key command sent was performed with wrong key 😦

        I have checked few RndB decrypted comparing with other people posts. Seems to be ok. But if you said its wrong I bet its wrong.

        I will try to achieve the “D9 F8 7D F6 28 4E 01 FF EE 11 83 A7 B7 26 77 5D” as you mentioned.

        Thanks Mustafa

        Bruno

        P.S.: I will try a new changekey command and paste here so you can confirm my values are ok.

        Bruno

      • Bruno

        Hi Mustafa, just ran a decrypt using my key under same RndB and got same result as you.
        Probably copy/paste or confusion problem.

        Here is another sequence (can you help me confirm?):

        AES Master Key (Confirmed by GetKeyVersion = 0×77):
        0×00, 0×01, 0×02, 0×03, 0×04, 0×05, 0×06, 0×07, 0×08, 0×09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F

        1. Send 0xAA
        [90 AA 00 00 01 00 00]

        2. Receive Encrypted(RndB) from PICC (16bytes)
        [85 3B 3B EC D3 E4 DF 01 79 B6 A4 49 D7 D4 6D E3]

        3. Decrypt Using AES with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
        [66 65 C7 25 C3 0B DC 1F A7 D0 E5 86 DF 25 CF C3]

        4. Left Shift RndB (RndB’)
        [65 C7 25 C3 0B DC 1F A7 D0 E5 86 DF 25 CF C3 66]

        5. Generate RndA
        [96 10 34 39 DF 16 9E 39 9A A0 24 B9 87 17 AE 2F]

        6. Concatenate RndA + RndB’
        [96 10 34 39 DF 16 9E 39 9A A0 24 B9 87 17 AE 2F 65 C7 25 C3 0B DC 1F A7 D0 E5 86 DF 25 CF C3 66]

        7. Encrypt Using AES with specified Key and (IV = RndB = 66 65 C7 25 C3 0B DC 1F A7 D0 E5 86 DF 25 CF C3)
        (result from decrypting challenge sent from PICC – Is this the correct IV to be used?
        [CE 2A 1F 51 DA 73 EB D4 01 2C 1B D6 E5 41 0B 32 50 5F D6 48 D0 DD CE 62 1F C4 28 27 EA 54 DD 52]

        8. Send APDU
        [90 AF 00 00 20 CE 2A 1F 51 DA 73 EB D4 01 2C 1B D6 E5 41 0B 32 50 5F D6 48 D0 DD CE 62 1F C4 28 27 EA 54 DD 52 00]

        9. Received
        [91 AE]

        Thank you verymuch Mustafa!

      • Bruno

        Hi Mustafa, thank you again for clarifying my path!

        I managed it to work correcting the AES alg for encryption/decryption (with CBC)

        Now I got 91 00 for the AF command. But I am still having trouble with RndA’ Encrypted by the PICC.

        Please See steps 10 and forward:

        AES Master Key (Confirmed by GetKeyVersion = 0×77):
        0×00, 0×01, 0×02, 0×03, 0×04, 0×05, 0×06, 0×07, 0×08, 0×09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F

        1. Send 0xAA
        [90 AA 00 00 01 00 00]

        2. Receive Encrypted(RndB) from PICC (16bytes)
        [F6 AE 8E 2A C8 3F 07 CC AD 71 7F 6B 14 83 F8 FA]

        3. Decrypt Using AES with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
        [80 8A 9D E3 0C 7D 30 C5 70 A1 BB 4B 2D B8 E2 0A]

        4. Left Shift RndB (RndB’)
        [8A 9D E3 0C 7D 30 C5 70 A1 BB 4B 2D B8 E2 0A 80]

        5. Generate RndA
        [A0 AE 67 F8 85 C0 3F E1 D3 C7 F9 6E 91 9D 4E 8F]

        6. Concatenate RndA + RndB’
        [A0 AE 67 F8 85 C0 3F E1 D3 C7 F9 6E 91 9D 4E 8F 8A 9D E3 0C 7D 30 C5 70 A1 BB 4B 2D B8 E2 0A 80]

        7. Encrypt Using AES with specified Key
        [B8 78 A5 55 DA 07 6D 8A A1 92 B8 0F E9 76 6B EC 22 76 CF AB 43 EA AD E2 A9 F3 62 D5 6E 82 A6 02]

        8. Send APDU
        [90 AF 00 00 20 B8 78 A5 55 DA 07 6D 8A A1 92 B8 0F E9 76 6B EC 22 76 CF AB 43 EA AD E2 A9 F3 62 D5 6E 82 A6 02 00]

        9. Received Encrypted RndA’ from PICC
        [E4 75 FC CB CE AF 07 A2 07 EE 1A 88 B1 C6 05 BA]

        10. Decrypted RndA’ from Picc using default iv byte[16] all zeroes
        [22 9F 1D E6 BC D2 80 9C 1F 75 67 50 70 34 D3 54]

        11. Rotate Left Current RndA for comparison
        [AE 67 F8 85 C0 3F E1 D3 C7 F9 6E 91 9D 4E 8F A0]

        12. Compare failed
        [22 9F 1D E6 BC D2 80 9C 1F 75 67 50 70 34 D3 54]
        !=
        [AE 67 F8 85 C0 3F E1 D3 C7 F9 6E 91 9D 4E 8F A0]

        ——

        Can you help me identify the problem? Probably is the decrypt of RndA’

        Thank you very much Mustafa!

      • Shehzad Ansari

        Do not use a zero InitVector. Use the previous InitVector.

        For DESFIRE calculations, InitVector is initialized to zero at the start only. After that always previous InitVector is utilized.

  • akdrmrk

    Hi again;
    I created an application with ‘CA3333330F0A’ …Then I sent 90-0A-00-01-00-00 (begin authentication procedure)…
    it responsed me 1D-A4-56-2E-78-43-F6-CB (encrypted rndB)
    Now I should Decrypt and build Rondom B..
    I am sending to picc 1D-A4-56-2E-78-43-F6-CB (encrypted rndB), it returned 67 00..it is wrong way.
    How can I decrypt rndB?

    • Shehzad Ansari

      Hi akdrmrk,

      I will upload the necessary files and will provide you the download link. The link would contain all the files that you will need to work with DESFIRE EV1.
      I’ll upload the files shortly.

      Shehzad.

  • Mustafa Moripek

    Hi Bruno,
    You are using wrong IV when encrypting
    RndA.You should use the encrypted RndB
    (as it comes from PICC) not the decryption
    of it.
    Mustafa

    • Bruno

      Thanks again Mustafa! I was using a “empty” iv to encrypt RndA. Just corrected it.

      What about the decryption of RndA’ ? Which iv should I use?

      Encrypted(RndB’) (last 16 bytes sent in apdu) ?

      Bruno

      • Mustafa Moripek

        Hi Bruno,
        Yes IV is enk(RndB’).Pay attention
        with decryption.You have to decrypt first
        and then exor with IV.
        Mustafa

  • Bruno

    Thanks Mustafa.

    Im not doing exor at all…Im just using AESDecrypt. Very strange because I got it working now even without XOR. Maybe the C# implementation of RijndaelManaged class does it for me?

    Im just using correct IVs and passing them to the C# RijndaelManaged class to do the job.

    I will post a complete authentication using AES so you can confirm my SessionKey.

    Thanks and Regards

    Bruno

    • Bruno

      Hi Mustafa, one more time I need to say thank you ! You are may hero! 😉

      Got AES authentication and I would like to share here:

      AES Master Key (Confirmed by GetKeyVersion = 0×77):
      0×00, 0×01, 0×02, 0×03, 0×04, 0×05, 0×06, 0×07, 0×08, 0×09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F

      1. Send 0xAA
      [90 AA 00 00 01 00 00]

      2. Receive Encrypted(RndB) from PICC (16bytes)
      [EC 6D 80 9F 56 CD B9 7F D0 37 9E 65 74 5E F3 8C]

      3. Decrypt Using AES with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
      [CE FE CC 91 61 1D 31 2A B7 5E E8 22 0A 6E 43 A4]

      4. Rotate Left (Left Shift) RndB producing RndB’
      [FE CC 91 61 1D 31 2A B7 5E E8 22 0A 6E 43 A4 CE]

      5. Generate RndA
      [18 99 CB 5D 4A E1 A9 78 5F 1C 9D 07 3A 8F 26 1B]

      6. Encrypted RndA using IV = #step2 (Encrypted RndB received from PICC)
      [31 3B 90 9A 91 48 D6 58 6C 4C 74 37 4A A3 34 C6]

      7. Encrypt RndB’ using IV = #step6 (Encrypted RndA)
      [92 8D F3 C8 37 C2 3C 49 E1 48 1A C5 D1 A5 A3 4F]

      8. Send APDU (Data = RndA+RndB’)
      [90 AF 00 00 20 31 3B 90 9A 91 48 D6 58 6C 4C 74 37 4A A3 34 C6 92 8D F3 C8 37 C2 3C 49 E1 48 1A C5 D1 A5 A3 4F 00]

      9. Received Encrypted RndA’ from PICC
      [0B C1 96 17 8A 86 8E 00 4E 5E 77 6F 06 FE 2E 35]

      10. Decrypted RndA’ from PICC using IV = #step7 (Encrypted Left Shifted RndB’)
      [99 CB 5D 4A E1 A9 78 5F 1C 9D 07 3A 8F 26 1B 18]

      11. Rotate Left Current RndA for comparison
      [99 CB 5D 4A E1 A9 78 5F 1C 9D 07 3A 8F 26 1B 18]

      12. Compare Both = OK
      [99 CB 5D 4A E1 A9 78 5F 1C 9D 07 3A 8F 26 1B 18] // Received
      !=
      [99 CB 5D 4A E1 A9 78 5F 1C 9D 07 3A 8F 26 1B 18] // Current Rotated RndA

      13. Generate Session Key
      [18 99 CB 5D CE FE CC 91 3A 8F 26 1B 0A 6E 43 A4]

      ——

      Mustafa is this SessionKey correct ? (RndA byte 0..3 + RndB byte 0..3 + RndA byte 12..15 + RndB byte 12..15) – from NXP docs.

      Thank you very much Mustafa!

      By the way: Im using C# with P/Invoke. If anyone would like the code, please send me a message! WordPress is terrible for posting source code.

      Bruno

  • Mustafa Moripek

    Hi Bruno,
    Yes the session key is like you have mentioned.
    Mustafa

    • Bruno

      Thank you very much!

      From now on, I need to calculate CRC32 and append to encrypted data, and padd it with zeroes to achieve 16bytes frames before send to PICC right ?

      Do you have any sample of CRC32 data?

      for example, can you show me the result of CRC32 for :

      First: 18 99 CB 5D CE FE CC 91 3A 8F 26 1B 0A 6E 43 A4
      Second: 0×00, 0×01, 0×02, 0×03, 0×04, 0×05, 0×06, 0×07, 0×08, 0×09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F

      Thank you very much!

      Bruno

  • Mustafa Moripek

    Hi again,
    I will be out of office tomorrow.I can calculate crc32
    on wednesday.Meanwhile you can try to implement
    the code on the following website :
    http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/libkern/crc32.c
    Mustafa

    • Bruno

      Thanks Mustafa…

      The CRC32 implementaion I was using inC# was doing a “not operator” at the end of crc. (return ~crc instead of return crc)

      After changing that I could reproduce CRC32 data as you mentioned in one of your posts.

      In case someone is looking for a CRC32 implementation for DESFire EV1 AES here it is :

      public class CRC32
      {
      private static uint[] table;

      private static uint ComputeChecksum(byte[] bytes)
      {
      uint poly = 0xedb88320;
      table = new uint[256];
      uint temp = 0;
      for (uint i = 0; i 0; –j)
      {
      if ((temp & 1) == 1)
      {
      temp = (uint)((temp >> 1) ^ poly);
      }
      else
      {
      temp >>= 1;
      }
      }
      table[i] = temp;
      }

      uint crc = 0xffffffff;
      for (int i = 0; i > 8) ^ table[index]);
      crc = (uint)(table[index] ^ (crc >> 8));
      }
      return ~crc;
      }

      public static byte[] ComputeCRC(byte[] bytes)
      {
      uint crcInverted = ComputeChecksum(bytes);
      uint crcNotInverted = ~crcInverted;

      byte[] originalCRC32 = BitConverter.GetBytes(crcNotInverted);

      // Retorna o Reverse pois a implementação do DESFire requer “not inverted”
      return originalCRC32.Reverse().ToArray();
      }

      }

  • akdrmrk

    I created an application with ‘CA 33 33 33 0F 0A’ …Then I sent 90-0A-00-01-00-00 (begin authentication procedure)…

    it responsed me 1D-A4-56-2E-78-43-F6-CB (encrypted rndB)

    Now I should Decrypt and build Rondom B..

    I am sending to picc 1D-A4-56-2E-78-43-F6-CB (encrypted rndB), it returned 67 00 so it is wrong way.

    How can I decrypt rndB and generated rndA?

    CAN SOMEBODY HELP ME PLEASEE???

    • Bruno

      Hi akdrmrk,

      I assume you have created an application with DES/2K3DES keys (since you are using 0x0A for authentication.

      Is that correct?

      Which language are you using? So we can provide some souce code samples?

      Basically the steps are as follow:

      1. Send Authenticate to PICC (as you did)
      [90-0A-00-01-00-00]

      2. PICC respond with Encrypted RndB’ (using the same key you have selected) in your case, key Number 01
      [1D-A4-56-2E-78-43-F6-CB]

      3. Now you shold decrypt RndB using DES (cant help you here because you didnt provided the App key)

      4. After decrypt, you need to Left Shift RndB (Rotate First Byte to the End) producing RndB’

      5. Generate RndA (random byte[8])

      6. XOR RndA and IV (using iv = all zeroes)

      7. Encrypt RndA: Run a “DES Decrypt alg” using IV = new byte[8] (all 0x00)

      8. XOR result of step #7 with RndB’

      9. Encrypt result of step #8 using “DES Decrypt alg” using IV = new byte[8] (all 0x00)

      10. Concat result of step #7 and #9 (EncryptedRndA + EncryptedRndB’)

      11. Create the APDU to send more data
      [90 AF 00 00 [Len] [result of step #10] 00

      Please provide us more information so we can reproduce your data and check if it is correct.

      Regards

      Bruno

      • akdrmrk

        Hi Bruno;

        ..(for 3rd stage) .How I creat App Key…..can you send me its commands…

        your answer is excellent description…Thank you so much

        Respects

        akdrmrk

      • akdrmrk

        Hi again;

        I am using c# language…if you send me source code,it can be very usefull…

        Thanks again

        akdrmrk

      • Kerry

        Hello Bruno and Mustafa,

        1. Send Authenticate to PICC
        [0x90, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00]

        2. PICC respond with Encrypted RndB’
        [FA 06 91 7B 86 5A F3 4C]

        3. Now decrypt RndB using DES (uses default key all 0’s)

        4. After decrypt, Left Shift RndB (Rotate First Byte to the End) producing RndB’

        5. Generate RndA (random byte[8])

        6. XOR RndA and IV (using iv = all zeroes, since Initial vector is 0’s so got same result after doing XOR operation as RndA)

        7. Decrypt RndA using “DES Decrypt algorithm” using key as All 0’s.

        8. XOR result of step #7 with RndB’

        9. Decrypt result of step #8 using “DES Decrypt algorithm” using key as all 0’s.

        10. Concat result of step #7 and #9 (DecryptedRndA + DecryptedRndB’) and send it to PICC.

        Is my understanding are correct or need to modify anything.
        I have doubts on steps 7 and 9 whether i have to do decrypt or encrypt using which key.

        Kerry

  • mibollma

    Thank u guys… the discussion over here was very helpful to unterstand DESFire authentication and key modification.
    To anyone still struggeling e.g. with encryption i recommend this presentation from the parent company of NXP: http://read.pudn.com/downloads134/ebook/572228/M309_Mifare&Security_V1.pdf

  • akdrmrk

    Hi guys,

    I send 90-0A-00-00-01-00-00
    it respond me encrypted rondomB, I should decrypt it but with which key?. I did not represent a key..

    can u explain please?

    • Shehzad

      Hi there,

      All the Application keys (APK), Application Master Keys (AMK) and even the Card Master Key (CMK) are initialized to zeros (0x00) by default.

      So, keep your SecretKey buffer as 0x00 and your InitVector buffer also as 0x00 and then proceed with the decryption.

      -Shehzad.

  • Toni Juola

    How to communicate with DESfire EV1 with AES encryption? Does anyone have the java code? Im using Android device and don’t have a clue what to do after selecting the application and sending the 0xAA command. It just returns some AF+(16bit). How to proceed from there?

    • Bruno

      Hi Tony, From another message I can see you got your auth working and already have the session key.

      The session key will be used to encrypt/decrypt data sent/received from card.

      For better help you, please tell us what do you need to perform at the card (change key, create application, create file, etc) and we will be glad to help you.

      Regards

      Bruno

      • Toni Juola

        I need to only read the Orig. Card ID. I think the command is 0x51 but it returns 00+random32bits. I think I need to encrypt it with the session key, but even then it returns just random 32 bits.

        Here is the code:

        byte[] sessionKey = new byte[16];

        sessionKey[0] = RandA[0];
        sessionKey[1] = RandA[1];
        sessionKey[2] = RandA[2];
        sessionKey[3] = RandA[3];

        sessionKey[4] = decryptedRndB[0];
        sessionKey[5] = decryptedRndB[1];
        sessionKey[6] = decryptedRndB[2];
        sessionKey[7] = decryptedRndB[3];

        sessionKey[8] = RandA[12];
        sessionKey[9] = RandA[13];
        sessionKey[10] = RandA[14];
        sessionKey[11] = RandA[15];

        sessionKey[12] = decryptedRndB[12];
        sessionKey[13] = decryptedRndB[13];
        sessionKey[14] = decryptedRndB[14];
        sessionKey[15] = decryptedRndB[15];

        byte[] ReadData = IsoDep.get(tag).transceive(READ_DATA_COMMAND); //0x51

        byte[] ReadDataParsed = new byte[16];

        System.arraycopy(ReadData, 1, ReadDataParsed, 0, 16);
        //to remove status bits

        byte[] RealUID = decrypt(sessionKey, ReadDataParsed, iv);
        //iv all zeros

        //returns random32bits
        Log.e(“RealUID”, ByteArrayToHexString(RealUID));

        And yes, cards have randomUID on.

      • Toni Juola

        “I think I need to encrypt it with the session key, but even then it returns just random 32 bits.” I meant decrypt

  • DaGui

    Hello,

    I am doing desfire programming in java. I can already do everything under single DES cryptography(with default key all 0x00).

    But now I should use real 3DES cryptography, that is, the key is random now. And I face the authentication problem now.

    Actually, the reason is that I don’t quite understand the 3DES flow diagram when the card send data and the pcd send data. The document says there are some differences as the card always use encrypt mode.

    With 3DES, we should doing 3 times DECRYPT_MODE DES(xor before des) when sending data to PICC and doing 3 times DECRYPT_MODE DES(xor after des) when receiving data from PICC?
    Oh I am confused!

    If I receive encrypted rndB from the card like this

    b4 52 53 a7 2c 7e eb b2
    The key is

    f1 ff ff f3 ff ff ff f4 f1 ff ff f3 ff ff ff f4.
    And what is the real rndB?

    If the rndA is

    d2 02 a0 f5 5a fa be cf.
    What rndArndB should I send to the card?

    Thanks very much!

    • Bruno

      Hi Dagui,

      The only thing from your message I didnt understand is “But now I should use real 3DES cryptography, that is, the key is random now”

      What do you mean by that? Have you chaged the Master from DES to 3DES already using ChangeKeyCommand?

      Now you are using Authenticate 0x1A ?

      Bruno

  • Iman Biglari

    Hi ridrix.
    I’ve been trying to implement a Delphi library to communicate with MIFARE DESFire EV1 cards using this post as my guide. I’m almost certainly sure I’ve implemented CBC Send Mode and CBC Receive Mode correctly, but my card keeps responding with 91AE to my AF DES(RndA+RndB’) command. The weird thing about my card is, when I request Key version for master key of PICC, I get 88h. Is this the expected response for a new card, and I should keep investigating my authentication code, or my card’s PICC master key has somehow been changed?
    I’d be more than happy to paste my code here, but it would clutter the blog.

    • Mustafa Moripek

      Hi Iman,
      88h is not key version,it is the first byte of the UID.
      Write down the whole communication with the PICC
      so I can see what the issue is.
      Mustafa

      • Iman Biglari

        Hi
        Thanks for the quick reply. Here’s the log:

        –>90 6A 00 00 00 // List Applications
        <–01 02 03
        90 5A 00 00 03 00 00 00 00 // Select PICC
        90 1A 00 00 01 00 00 // ISO Authenticate with master key (00000000h)
        90 AF 00 00 00 // Retreive RndB
        <–A4 4C 2B D1 EB 6F 64 0C
        90 AF 00 00 10 0D 9F 27 9B A5 D8 72 60 25 DD 7A 19 63 0F 26 2D 00 // Send DES(RndA + RndB’)
        <–91AE (AUTHENTICATION_FAILURE)

        By the way, RndA equals 1

  • MIFARE DESFire EV1 Authentication Issue | Stackforum.com

    […] DESFire EV1 card with the default key (00000000h) for the last week to no avail. I have followed this blog‘s instructions to the letter. I implemented Send mode CBC and Receive mode CBC like […]

  • Mustafa Moripek

    Hi Iman,
    why are you using authent command 1A?
    Are you sure your key is 3K3DES version.
    Mustafa

    • Iman Biglari

      I was simply following NXP’s guidelines. Here’s the log with Authenticate command:

      –>90 0A 00 00 01 00 00
      <–91AF
      90 AF 00 00 10 49 1E 89 0D E9 AC E9 32 EE 58 EC C4 38 58 B6 2C 00
      <–91AE

      // note that RndA = 0x0011223344556677 and Key = 0x0000000000000000

  • Mustafa Moripek

    Your decrypting algoritm seems to be O.K.
    Encrypting 49 1E 89 0D E9 AC E9 32 gives
    00 01 02 03 04 05 06 07.If you write down
    the whole log I can check your CBC also.
    Mustafa

    • Iman Biglari

      Hi Mustafa.
      Here’s the log data with RndA = 00 01 02 03 04 05 06 07

      PICC: 90 6A 00 00 00
      PCD : 01 02 03 (9100)
      PICC: 90 5A 00 00 03 00 00 00 00
      PCD : (9100)
      PICC: 90 64 00 00 01 00 00
      PCD : 88 (9100)
      PICC: 90 45 00 00 00
      PCD : 0F 01 (9100)
      PICC: 90 0A 00 00 01 00 00
      PCD : (91AF)
      PICC: 90 AF 00 00 00
      PCD : E0 D9 7A 82 05 EC 53 86 (9100)
      PICC: 90 AF 00 00 10 49 1E 89 0D E9 AC E9 32 49 2A D0 1F 44 EC 82 46 00
      PCD : (91AE)

      • Mustafa Moripek

        Hi Iman,
        I have checked your data and I have got same
        results.
        Now there are some possible reasons for the
        AE.Your key may be wrong or type of key is wrong.
        To get the type of key you should send Get Key
        Settings command (45) to the PICC.You will get
        3 bytes (Status,Key Settings,Max No.of Keys) as
        response.The combination of the two MSB’s
        (bit7 and bit6) of Max No.of Keys gives you
        the type of the key type.If it is 00 you should
        authenticate with 0A,if 01 you should
        authenticate with 1A and if it is 10 you should
        authenticate with AA.
        Good luck
        Mustafa

    • Iman Biglari

      Hi again. Please excuse my mistake in misplacing PICC and PCD in the log I posted

  • Iman Biglari

    Hi Mustafa.
    I finally got my hands on a bunch of new DESfire cards and successfully authenticated with them. Now I’m trying to change the default master key, and I’m getting integrity error. Here’s the communication trace:

    // extract UID
    PC : 90 60 00 00 00
    Card: 04 01 01 01 00 18 05 (91AF)
    PC : 90 AF 00 00 00
    Card: 04 01 01 01 00 18 05 04 01 01 01 04 18 05 (91AF)
    PC : 90 AF 00 00 00
    Card: 04 01 01 01 00 18 05 04 01 01 01 04 18 05 04 0E 65 B2 F8 2B 80 BA 34 57 55 30 17 12 (9100)

    // get application IDs
    PC : 90 6A 00 00 00
    Card: (9100)

    // select master application
    PC : 90 5A 00 00 03 00 00 00 00
    Card: (9100)

    // get key version for key # 0x00
    PC : 90 64 00 00 01 00 00
    Card: 00 (9100)

    //authenticate with default master key… RndA = 00 01 02 03 04 05 06 07
    PC : 90 0A 00 00 01 00 00
    Card: BA B0 87 58 53 A7 C7 50 (91AF)
    PC : 90 AF 00 00 10 49 1E 89 0D E9 AC E9 32 3D 6A C4 BF 2D 6B 67 F5 00
    Card: B7 D1 DA 7C E0 DD 98 6B (9100)

    // session key is 00 01 02 03 3A 02 36 04

    // change master key to 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11
    PC : 90 C4 00 00 19 00 EE 1B 98 23 6B F1 EA 6E DA 0C 0B 1E 2B FD 3C 73 A3 94 8E 3D 92 CE 46 FD 00
    Card: (911E)

    I’d appreciate it if you would be kind enough to tell me what’s wrong…

    • Mustafa Moripek

      Hi Iman,
      I don’t know how you came to data you have sent to PICC.
      For changing the key you have to proceed as follows:
      You have to calculate crc16 over the new key,append it
      to the new key and after padding withh zeroes to come to
      multiple of eight bytes send it to PICC in CBC send mode.
      For your session key is eight bytes long you have to
      use single DES decrypting.I have made a sample
      calculation with your data so you can check your
      code.

      1- 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 New Key
      2- 32 07 CRC16
      3- 11 11 11 11 11 11 11 11 Block1
      4- 11 11 11 11 11 11 11 11 Block2
      5- 32 07 00 00 00 00 00 00 Block3
      6- 0D 71 75 4C E8 70 75 7C DES decrypted Block1
      7- 1C 60 64 5D F9 61 64 6D DES decrypted Block1 XOR Block2
      8- 26 50 0C 46 70 EF 76 08 DES decrypted Block2
      9- 14 57 0C 46 70 EF 76 08 DES decrypted Block2 XOR Block3
      10- E1 BE F2 DC B6 37 22 BD DES decrypted Block3

  • Mustafa Moripek

    I am using following code:

    unsigned short crc_16(unsigned char *data, unsigned int len)
    {
    unsigned short crc= 0x6363;
    for(i= 0; i < len ; ++i)
    crc= update_crc16(crc, data[i]);
    return crc;
    }
    unsigned short update_crc16(unsigned short crc, unsigned char Char)
    {
    unsigned short t,v, tcrc = 0;
    v = (crc ^ Char) & 0xff;
    for (t = 0; t > 1 ) ^ 0x8408 : tcrc >> 1;
    v >>= 1;
    }
    return ((crc >> 8) ^ tcrc) & 0xffff;
    }
    Mustafa

  • teguhblitzkrieg

    hi Mustafa,
    i’m new in card Development
    i struggling a weeks for change master key but i always get following error 40,
    i use android NFC and is the log :

    SELECT PICC (->5A000000) : 45) : 6400) : 0A00) : AF0000000000000000F88E32E768B73487) : CD72DFC6E6D040A4) : **
    ** ROTATE RNDA.. (->72DFC6E6D040A4CD) : **

    ** SPLIT HALF ROTATED RndA ( 72DFC6E6 ):( D040A4CD ) **

    ** SPLIT HALF ROTATED RndB ( 91EDA1E5 ):( 1564093E ) **

    ** SEASON KEY IS ( 72DFC6E61564093E91EDA1E5D040A4CD:) **

    GET KEY SETTING (->C40A18069A4ABB76661AD14BA63D2AB009A8105AAD9A5D57D680) : <- 40

    thank in advance

    ~ Teguh

  • Mustafa Moripek

    Hi Teguh,
    I need all the conversation log with the PICC.
    For authentication you need to proceed as follows:
    NFC to PICC 0A 00 (Authent command Key No.),
    PICC to NFC AF 8 Bytes Encrypted RndB
    NFC to PICC AF 16 Bytes Decrypted (RndA 4 RndB’)
    PICC to NFC 00 8 Bytes Encrypted (RndA’)
    From your log I cannot see these data.

    For getting key setting you have to send only 45,
    what are the data begginning with C4…
    Error code 40 means no such key.

    Mustafa

  • teguhblitzkrieg

    hi Mustafa, thanks for quick response,
    i’m confuse with my authenticate method, when i follow the instruction from http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf i get following error 0xCA (command abort)
    here is my authenticate flow :

    -> 0A 00
    RndB
    * generate RndA 01 02 03 0f 0d 0c 0b 0a *
    * concat RndA + RndB (01 02 03 0f 0d 0c 0b 0a + 4D 70 D0 8E 62 CB A1 FA) *
    * decrypt concat RndA+RndB (3E D8 9C B8 DD 23 C4 D1 A7 75 1D 8D EF E0 A3 B4) *

    -> 3E D8 9C B8 DD 23 C4 D1 A7 75 1D 8D EF E0 A3 B4
    <- CA

    ~ Teguh

  • teguhblitzkrieg

    hi Mustafa, thanks for quick response,
    i’m confuse with my authenticate method, when i follow the instruction from http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf i get following error 0xCA (command abort)

    here is my authenticate flow :
    -> 0A 00
    3E D8 9C B8 DD 23 C4 D1 A7 75 1D 8D EF E0 A3 B4
    <- CA

    ~ Teguh

  • teguhblitzkrieg

    hi Mustafa, thanks for quick response,
    i’m confuse with my authenticate method, when i follow the instruction from http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf i get following error 0xCA (command abort)

    here is my authenticate flow :
    -> 0A 00
    3E D8 9C B8 DD 23 C4 D1 A7 75 1D 8D EF E0 A3 B4
    <- CA
    ~ Teguh

  • teguhblitzkrieg

    hi Mustafa,
    here is my authenticate flow :
    -> 0A 00
    3E D8 9C B8 DD 23 C4 D1 A7 75 1D 8D EF E0 A3 B4
    <- CA
    ~ Teguh

  • Mustafa Moripek

    Hi Teguh,
    you get the error code CA,when you send the PICC
    the next frame before the previous command
    is executed and the response is sent.Do send all
    the challenges to the PICC step by step in the
    order I have mentioned above and wait
    for the response each time.
    Mustafa

  • Iman Biglari

    Hi Mustafa
    I’m trying to create an application with ISO files names on my DESfire, but I’m getting 9E error (parameter error) when I set the Key Settings 2 bit 5 to 1. If I use 0x0E as KeySettings 2, the application is created successfully, but if I use 0x16 or 0x1E, I get 9E. Do you have any idea?

    • Mustafa Moripek

      Hi Iman,
      I think you mean bit 4 when you write bit 5,because
      normally you start with bit 0.Bit 4 is RFU and should
      always be zero.
      Mustafa

      • Iman Biglari

        Thanks for your quick reply. My application has 4 keys besides Application Master Key. And I need 2 byte ISO 7816-4 File Identifiers. So, my Key Settings 2 should be 00010101b. That would be 15h. So, the APDU I’m sending to the card is “90CA000012504E410F15454E504E4120652D507572736500”

  • Mustafa Moripek

    Key Setting2 is composed as follows:
    Bit3..0 : Number of keys
    Bit 4 : RFU,has to be set 0
    Bit 5 : Indicates the use of ISO file identifier 0 means
    no identifier,1 means 2bytes file identifier
    Bit 6-7 : Crypto mode
    00 authentication cmd 0A
    01 authentication cmd 1A
    10 authentication cmd AA
    According those rules your Key Settings2 should be:
    00100101b (0X25)
    Mustafa

    • Iman Biglari

      Thanks a lot 🙂
      Can you help me with another issue? Now i want to create a standard file with this APDU: “90CD00000900434400000808000000” but I’m repeatedly getting PARAMETER ERROR. My Access Bits is 1000h (key #1 to read and application master key to modify), and my file size is 64 bytes. Am I calculating something wrong?

      • Mustafa Moripek

        Your APDU command should be:
        90CD00000900434400001040000000
        Desfire internally allocates memory place in
        multiple of 32 bytes,therefore if you send
        08 as LSB meaning eight bytes it may
        cause the parameter error response.
        Mustafa

  • Titin Kurniati

    Hi Mustofa i want change key for master key but i’m getting error 91 1E
    there is my code:

    decryptRndB == 2A552B4102F8132F
    sessionKey == 27071C272A552B4127071C2727071C27
    decryp24keydata == 8BEDDC3C069475ED166E3B5FB33FA958C99F3DBFB0A1530F

    and i’m using following crc source code: and result crc16 = 77f5

    private static byte[] Data= new byte[] {
    (byte)0x00,(byte)0x01,(byte)0x02,(byte)0x03,
    (byte)0x04,(byte)0x05,(byte)0x06,(byte)0x07,
    (byte)0x08,(byte)0x09,(byte)0x0a,(byte)0x0b,
    (byte)0x0c,(byte)0x0d,(byte)0x0e,(byte)0x0f,}

    public static byte[] iso14443a_crc(byte[] Data) // DESFireSAM crc16 do not invert the result
    {
    int bt;
    int wCrc = 0x6363;
    int j = 0;
    int t8 = 0;
    int t9 = 0;
    int tA = 0;
    int Len = Data.length;
    final int maskB = 0x0000000000000000FF;
    final int maskW = 0x00000000000000FFFF;

    do
    {
    bt = Data[j++] & maskB;
    bt = (bt^(wCrc & 0x00FF)) & maskB;
    bt = (bt^(bt<<4)) & maskB;

    t8 = (bt << 8) & maskW;
    t9 = (bt<>4) & maskW;
    wCrc = (wCrc >> 8)^(t8^t9^tA) & maskW;
    }
    while (j >8) & maskB);
    return bb;
    }

    and then send commnd apdu change key :
    90c4000019008BEDDC3C069475ED166E3B5FB33FA958C99F3DBFB0A1530F00

    and result 91 1E (Integrity error) I think my crc wrong,
    can you help me???
    thank you

    • Mustafa Moripek

      Hi Titin,
      your crc16 is correct.I think your session key
      is not correct.If you are trying to change the
      default key all zeroes than the first
      half of your session key be equal to the
      second half.
      Mustafa

      • Titin Kurniati

        hi mustafa thanks for your response,

        whats wrong with my session key ? i use OmniKey CardMan 5321
        and here is my complete log :

        Using given card reader: OMNIKEY CardMan (076B:5321) 5321 00 01
        Using T=1 protocol
        Reading commands from STDIN
        905a00000300000000
        > 90 5a 00 00 03 00 00 00 00
        90 5a 00 00 03 00 00 00 00
        90 0a 00 00 01 00 00
        90 af 00 00 10 09 08 07 06 05 04 03 02 5F B3 C3 42 97 25 99 3C 00
        90 c4 00 00 19 00 C1 E1 41 41 C8 4A B7 2F 6B FF 30 71 63 57 4A A5 F9 E0 95 4A 15 01 83 30 00
        < 91 1E : Error not defined by ISO 7816

        my seasson key is 75879AA7A9244D1875879AA7A9244D18

        any idea ?

  • teguhblitzkrieg

    hi again mustafa,
    im still no success with authentication process
    now i getting result 0xAE (authentication error)

    http://pastebin.com/jC93FtJB

    here is my log :

    TO PICC : 0A 00
    TO PCD : AF28D938B2581F0A1B

    POP FST BYTE : 28D938B2581F0A1B
    DROP TO END RNDB : D938B2581F0A1B28
    XOR RNDA W RNDB : 15845FD7D732D220
    DECRYPT RNDB : 84F6C0DC2868EE4A
    CONCAT RNDA W RNDB : CCBCED8FC838C90884F6C0DC2868EE4A
    DECRYPT CONCAT RNDA+RNDB : 137088072E5E4CB7D938B2581F0A1B28

    TO PICC : AF137088072E5E4CB7D938B2581F0A1B28
    TO PCD : AE

    and is my pseudo code :

    key = 0x00;
    RndA = CC 0B ED 8F C8 38 C9 08;
    encRndB = start_authentication (key);
    encRndB = pop_first_byte (encRndB);

    RndB = shift_first_byte_to_end (RndB);
    RndB = xor_rndb_w_rnda (RndA, RndB);
    RndB = decrypt (key, RndB);

    concatAB = concat_byte (RndA, RndB);
    concatAB = concat_byte (0xAF, concatAB);

    answer = send_to_picc (concatAB);

    sorry for my newbie questions

    ~ Teguh

  • Stefan

    Hi,
    does anybody, maybe Mustafa, know a Java SDK/Library for Mifare Desfire Communication?
    Greets,

    Stefan

  • Mustafa Moripek

    Hi Teguh,
    the way you are proceeding is not correct.
    To your authentication command answers
    the PICC with AF EncNo(RndB) which is
    in your case AF 28D938B2581F0A1B.
    Now you have to decrypt this to get RndB
    and build RndB’.I think your key is all zeroes:
    I have decrypted it so you have a data
    to check your decrypting algorithm.
    RndB is in this case :8C A6 4D E9 C1 B1 23 A7
    RndB’ is A6 4D E9 C1 B1 23 A7 8C.
    You have to decrypt your RndA, build RndB’
    and exor both.Then you have to decrypt it.
    At last you send AF+dec(RndA)+
    dec(dec(RndA) XOR RndB’) to the PICC.

    Mustafa

  • Mustafa Moripek

    Hi Titin,
    In your first comment the session key was wrong.
    In the last comment it was correct but your
    building CBC is wrong.Your three blocks
    you wish to send to PICC are:
    Block1 : 00 01 02 03 04 05 06 07
    Block2 : 08 09 0A 0B 0C 0D 0E 0F
    Block3 : 77 F5 00 00 00 00 00 00
    You have to build CBC as follows :
    Dec(Bl1) :C1 E1 41 41 C8 4A B7 2F
    (Your first Block is correct.But before
    decrypting your second block
    you had to exor it with decrypted Block1)
    Dec(Bl1) XOR Bl2: C9 E8 4B 4A C4 47 B9 20
    Dec(Dec(Bl1) XOR Bl2) :24 E4 2D 88 C0 F8 82 09
    Dec(Bl2) XOR Bl3 : 53 11 2D 88 C0 F8 82 09
    Dec(Dec(Bl2) XOR Bl3) :B2 F1 90 64 BA 73 97 5D
    Your payload should look like:
    90 C4 00 00 19 00 C1 E1 41 41 C8 4A B7 2F
    24 E4 2D 88 C0 F8 82 09 B2 F1 90 64 BA 73 97 5D 00

    Mustafa

    • Titin Kurniati

      thank you for your quick response

      I was trying again and follow you instruction but I’m still getting 91 1E

      this is my log:

      Using given card reader: OMNIKEY CardMan (076B:5321) 5321 00 01
      Using T=1 protocol
      Reading commands from STDIN
      905a00000300000000
      > 90 5a 00 00 03 00 00 00 00
      90 0a 00 00 01 00 00
      90 af 00 00 10 09 08 07 06 05 04 03 02 8E 6E 15 BF F0 67 5C AA 00
      90 c4 00 00 19 00 C1 E1 41 41 C8 4A B7 2F 24 E4 2D 88 C0 F8 82 09 B2 F1 90 64 BA 73 97 5D 00
      < 91 1E

      thank you

      • Mustafa Moripek

        Hi Titin ,
        I am out of office now and I will be back on
        monday and can check you data then.
        For checking I need the log of all conversation
        between reader and PICC.
        Examining your data I can say that you are
        making something wrong,because it is impossible
        that you are getting same results.Each time
        you authenticate you get another sessionkey.
        With new session key your decrypted data
        should be different from previous data.
        Please write all the communication as
        I have written plus your session key,
        so I can verify the data and can find where
        the issue is.
        Mustafa

      • xurniati

        Thank for your help:

        This is a log of All conversation change key between reader and PICC :

        Using given card reader: OMNIKEY CardMan (076B:5321) 5321 00 01
        Using T=1 protocol
        Reading commands from STDIN
        905a00000300000000
        > 90 5a 00 00 03 00 00 00 00
        90 64 00 00 01 00 00
        90 0a 00 00 01 00 00
        90 af 00 00 10 09 08 07 06 05 04 03 02 3A 01 56 28 0D CB 1F E3 00
        this is RndA’

        decrypt RndA’ using key = A775879AA7F7AFA3
        RndA = 75879AA7F7AFA3A7

        decrypt RndB = 47CB190CA2A899DB

        session key = RndA1st half + RndB1st half + RndA1st half + RndB1st half
        = 75879AA747CB190C75879AA747CB190C

        private static byte[] block1 = new byte[]{
        (byte)0x00,(byte)0x01,(byte)0x02,(byte)0x03,
        (byte)0x04,(byte)0x05,(byte)0x06,(byte)0x07
        };

        private static byte[] block2 = {
        (byte)0x00,(byte)0x01,(byte)0x02,(byte)0x03,
        (byte)0x04,(byte)0x05,(byte)0x06,(byte)0x07
        };

        private static byte[] block3 = {
        (byte)0xcd,(byte)0x1c,(byte)0x00,0x00,0x00,0x00,0x00,0x00
        };

        decrypt block1 using session key = 7A5F4AD473E4457A

        xor block2 with (decrypt block 1 using session key) = 7A5E48D777E1437D

        decrypt (xor block2 with (decrypt block 1 using session key) ) = 831348FA13F11F95

        xor block2 with (decrypt (xor block2 with (decrypt block 1 using session key) ) ) = 4E0F48FA13F11F95

        decrypt (xor block2 with (decrypt (xor block2 with (decrypt block 1 using session key) ) )) = EE13F2E0DC7ECC33

        payload = 7A5F4AD473E4457A831348FA13F11F95EE13F2E0DC7ECC33

        and then send command APDU :

        90c4000019007A5F4AD473E4457A831348FA13F11F95EE13F2E0DC7ECC3300
        > 90 c4 00 00 19 00 7A 5F 4A D4 73 E4 45 7A 83 13 48 FA 13 F1 1F 95 EE 13 F2 E0 DC 7E CC 33 00
        < 91 1E

  • Mustafa Moripek

    Hi Xurniati
    I have checked your data.Your crc16,your
    decrypting algorithm and your building
    cbc are all correct.The issue is your
    building the session key.I think your
    Rnd A is 09 08 07 06 05 04 03 02.
    That means the first half of your session
    key should be 09 08 07 06 but you
    have used the first half of the decrypted
    RndA .I couldn’t verify your RndB therfore
    I can’t say what the second half should be.
    If you correct the algorithm for building the
    session key you will be able to change the key.
    Mustafa

    • xurniati

      Hi Mustafa,

      I was trying again and not success and still getting 91 1E

      how to build correct session key?

      I’m so frustasting with that

      • Mustafa Moripek

        Hi Xurniati,
        if you can authenticate succesfully then you have
        all the data to build the sessionkey.First half of
        RndA (in your case 09 08 07 06 ) + first half
        of RndB (the DES decrypted data of the
        response of PICC to your authenticate command).
        For DES has a 16 byte key you have to
        put the above mentioned data two times to
        build the session key.
        Write down the complete log of authent
        procedure so I can find out
        where the issue is.
        Mustafa

  • teguhblitzkrieg

    hi mustafa,
    thank you so much for your answer , finally my authentication process is success! now i have a session key.

    but now i need to change key, according to http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf
    to change key i should build :
    command + key_no + 24 bytes data. but i confuse how to building 24 bytes data is .
    i see your previous comments says it should be 16 bytes + 2 bytes CRC + 6 bytes padding. i send it but i get following error 1E

    its crypto algorithm for change key should be done in single DES ? and i must be use 8 bytes session key ?
    can you show me in a step by step examples to help me understand?

    Sorry for my inconvenience

    ~ Teguh Ginanjar

    • Mustafa Moripek

      Hi Teguh,
      1E means integrity error.You get this error
      message if either crc16 is wrong or
      the padding bytes are not correct.So you
      have to check your crc16 algorithm.The crc16
      of 00 to oF is 77F5,verify your crc16 code.
      If it is correct then something is wrong with
      DES decryption so the PICC calculates
      another crc16 value.Then you have to check your
      session key or look for other issues .
      Write down the log of complete communication
      so I can verify you data.
      Mustafa

  • teguhblitzkrieg

    hi mustafa,
    i think my CRC16 calculation is right i have to check 00 to 0F and get same result as you (77F5).

    my method to change key is i

    C4 + keyno + 16 bytes decrypted 3DES (16 bytes sessionkey with new key 00 .. 0F) + 77 F5 + 00 00 00 00 00 00

    im confuse here, should i use 8 bytes session key and done it with single DES ?

    • Mustafa Moripek

      Hi Teguh,
      if you authenticate with default key all zeroes
      then your session key is as follows:
      first half RndA + first half RndB + first half
      RndA + first half RndB(totally 16 bytes).
      For the first half of your session key is equal
      to the second half you have to use single DES
      decryption.
      Mustafa

      • teguhblitzkrieg

        hi mustafa,
        i think i was successfully to change key from 00 to 00..FF
        here is my log :

        RANDOM A = 01 02 03 04 05 06 07 08 09

        TO PICC = 0A 00
        FROM PICC = AF 17 BC C8 AE 8F DD 1D 6C
        TO PICC = AF CE AD 37 3D B8 0E AB F8 52 6A 40 A7 08 30 F6 D5
        FROM PICC = FB 79 6C 9A AF BF 71 D3

        so i have session key = 01 02 03 04 08 E0 1E 6F

        then i build command to change key :

        C4 00 6A 4E A8 FA AF E1 7F 23 86 E9 95 00 F3 29 15 B1 DA 7C FD B6 D4 6F 1A BC

        i send it and get result 0x00 it means command success

        now i try to authenticate with new keh 00 .. FF
        but i get following error AE (authenticate Error).

        here is the log :

        TO PICC : 0x0A
        FROM PICC : AF 0D EA AB D2 12 02 7F A6
        TO PICC : AF CE AD 37 3D B8 0E AB F8 66 D5 0E 75 A D 4A 9B EA
        FROM PICC : AE

        What could went wrong ?

  • Mustafa Moripek

    Hi Teguh,
    if you have successfully changed the key then
    you are trying to authenticate with wrong key,
    because the crc16=77f5 is for key data
    00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
    and not for 00 11 22 33 44 55 66 77 88 99 AA BB
    CC DD EE FF.Therefore check the key you
    are authenticating with.
    Mustafa

  • teguhblitzkrieg

    hi mustafa,
    Thank you so much, it just works!

    i have question, can i change my new key back to all zero value ?

    Thank you very much in advance 🙂

    • Mustafa Moripek

      Hi Teguh,
      yes you can change it,but don’t forget
      the first half of your key is no more equal
      to the second half therefore you have to
      build your session key accordingly and use
      3DES for decrypting.
      Mustafa

      • teguhblitzkrieg

        hi mustafa ,
        thank you so much for your help,
        i can change it to all zeros and even i can change to AES, but im failed to change AID key level to AES, is AID key cant change to AES ? thank you so much in advance 🙂

  • Mustafa Moripek

    Hi Teguh,
    yes you can change the AID key.Depending on
    yhe key settings you have to authenticate
    with masterkey or change key key first.
    mustafa

    • teguhblitzkrieg

      hi mustafa,
      for AID level i always get following 0x40 (no such keys) when move 3DES to AES.
      what could went wrong ?

      teguh

      • Mustafa Moripek

        Hi Teguh,
        have you been able to change the key
        from 3DES to AES.
        You get 0X40 when the key number is not correct.
        Write the whole communication log.
        Mustafa

      • teguhblitzkrieg

        hi mustafa,
        thank you for your help.

        here is my complete log :

        // authentic master key with AES ( key is all 0xFF)

        TO PICC : AA 00
        FROM PICC : AF894D993D82919DDBEE6597AAAD093146
        TO PICC : AFB8EB39F3A8E6FC14F8F1B0007D7EAAD987FD1A497E7923188E7724A798316006
        FROM PICC : 00BACAD6607DE2C3841735D6BA1095EA89

        now i have session key from master key AES : 0001020319EF45060001020319EF4506

        // select application ID 0x010203

        // authentic application ID 3DES (key is all 0xFF)
        TO PICC : 0x0A 00
        FROM PICC : AFC4D1B6376C365F76


        now i have session key from authentic AID :
        000102031425E5E7000102031425E5E7

        now i change command from 3DES to AES for AID :

        TO PICC : C480425EE7EF3C624CA9BE95867EF4394100FEDA00ACCEA080F1

        FROM PICC = 0x40

  • Mustafa Moripek

    Hi Teguh,
    now I know where the issue is.The type of
    the key of an application you determine
    when creating the application.The bit
    numbers 6 and 7 of Key Setting No.2
    indicate the crypto mode.
    You can change the crypto type
    of only PICC master key the way you are
    trying to change.You have to delete the
    application and create a new one with
    appropriate Key Settings No.2.
    Mustafa

  • Mustafa Moripek

    Hi Teguh,
    why 0XF1.If you want to use only one key
    within this application the Key Setting No.2
    should be 0X81,because bit 7 and bit 6
    of the Key Setting No.2 defines the
    crypto method.If you want to use AES
    encryption method bit 7 should be 1
    and bit 6 should be 0.
    Mustafa

  • teguhblitzkrieg

    hi mustafa,
    thank you so much, its working now 🙂
    but I’m facing the new problem, i can create the value file but i can’t commit transaction after update value file 😦

    teguh

  • JP

    Hi Mustafa and others,

    I’ve successfully authenticated to a Mifare Desfire EV1 card using AES-128.
    After the authentication, I’ve managed to ask for the UID, but as it apparently comes back encrypted,
    I’ve not managed to decrypt it properly. Hope you can help me.

    Some bytes, like app ID and AES key are shown as xx as they aren’t public. The flow is described below:

    Commands sent:
    Select application:
    –> 5A xx xx xx
    AA 02 (using the key 2)
    AF + rndAB
    51
    <– 00 + 16 random bytes

    Now I've tried to follow this link's example with the advices given, but it hasn't worked yet:
    http://stackoverflow.com/questions/20503060/how-to-decrypt-the-first-message-sent-from-mifare-desfire-ev1?rq=1

    My code for this (java):
    public static byte[] decrypt_UID(byte[] session_key, byte[] UIDEncrypted)
    {
    byte[] UIDDecrypted = null;

    byte[] iv = new byte[]
    {
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
    };

    // param 1 = key, param 2 = enciphered data, param 3 = iv
    byte[] x = encrypt(session_key, iv, iv);

    byte[] rx = bitLeftShift(x);

    if ((rx[15] & 0x01) == 0x01)
    {
    rx[15] = (byte) (rx[15] ^ 0x86);
    }

    byte[] crc_k1 = rx;

    byte[] rrx = bitLeftShift(rx);

    if ((rrx[15] & 0x01) == 0x01)
    {
    rrx[15] = (byte) (rrx[15] ^ 0x86);
    }

    byte[] crc_k2 = rrx;

    byte[] command = new byte[]
    {
    (byte) 0x51, (byte) 0x80, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
    };

    for (int i = 0; i < 16; i++)
    {
    // been trying with both, this crc_k2, and crc_k1
    command[i] = (byte) (command[i] ^ crc_k2[i]);
    }

    byte[] iv2 = new byte[]
    {
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
    };

    iv2 = encrypt(session_key, command, iv);

    // param 1 = key, param 2 = enciphered data, param 3 = iv
    UIDDecrypted = decrypt(session_key, UIDEncrypted, iv2);

    return UIDDecrypted;
    }

    I'm using Cipher like: cipher = Cipher.getInstance("AES/CBC/NoPadding");,
    and both the encrypt() and decrypt() functions are the same as used in the
    auth process

    I think I've tried "all" with this and nothing has worked.
    Some things that bother me:
    – the command variable with 0x80 and 14 0x00 bytes
    – UIDDecrypted is always random bytes, which is already wrong, but it's also 16 bytes long.
    The real UID is supposed to be 7 bytes long, I think. But otherwise the given stackoverflow link seems to perfectly relate to this.
    (here it again: http://stackoverflow.com/questions/20503060/how-to-decrypt-the-first-message-sent-from-mifare-desfire-ev1?rq=1)

    I've been stuck with this for a while, and I'm pretty sure I'm close to getting it done, at least on the right track.

    Any help would be really much appreciated!

    – JP

    • Mustafa Moripek

      Hi JP,
      I don’t have any experience with java for
      I am writing codes in C for microcontrollers.
      I wil give you some information which may
      help you to find the issue.
      First thing is you don’t pass any parameters
      to PICC when sending cmd 0X51.Therefore
      I’m not sure about the variable 0X80 and
      14 zero bytes.
      The PICC answers with 16 bytes : 7 bytes
      UID 4 bytes CRC32 and rest padding.
      If you check your code accordingly
      you will find the issue.
      Mustafa

  • JP

    Hi Mustafa,

    Ok, thank you. I will try it more, and this time mostly using only 0x51 as the command, as it probably shall be just 0x51. And I’ll mostly pay attention to the first 7 bytes.

    One thing: “The PICC answers with 16 bytes : 7 bytes
    UID 4 bytes CRC32 and rest padding.” you said. I’ve been mostly trying to decrypt the answer I got from sending 0x51 (16 bytes after the first byte that’s 0x00), so… Should I actually still send something and receive an answer, or am I trying it the right way now (decrypting the answer got from 0x51)?

    Thanks again,

    – JP

    • Mustafa Moripek

      Hi JP,
      the first byte 0X00 means success and the
      following 16 bytes are the encrypted
      UID… . On error you would have
      an error code instaed of the zero as
      the first byte.You have to decrypt the
      16 bytes after the zero.If you find the issue
      please share the result.
      Mustafa

      • JP

        Hi Mustafa,

        Yeah, so I’ve been on the right track, trying to decrypt the 16 bytes following the first 0x00, which is OK for sure as I’ve learnt before 🙂

        Now I’ll keep on trying to decrypt the 16 bytes and then pay the most of attention to the first 7 bytes after decrypting, as it shall be the real UID.

        Thanks again, and yes, I’ll share what was wrong when I’ve solved it.

        – JP

      • JP

        Ok, I finally found out what was wrong with my codes!

        I was long unsure about the sessionKey, but then got the right one after researching some more. It appears to be:

        – byte[16] of which indexes 0…3 and 8…11 are from the reader’s (mine) generated rndA which are also parts of the sent rndAB within the authentication, and indexes 4…7 and 12…15 are from rndB which is built by decrypting the answer to 0xAA (decrypting the 16 bytes after the AF byte).

        Then I also noticed that I had been sending GetVersion command in between the authentication and the GetUID command, and that probably changed the IV, which is 16×00 just after the authentication, just like in my codes for decrypting the UID.

        So, my function public static byte[] decrypt_UID() shown above seems to work with the sessionKey built how I explained in this post. Like Mustafa said, the first 7 bytes of the decrypted UID are the actual, real UID.

        Thanks for trying to help me before, and I hope this helps someone else now too!

        – JP

  • teguhblitzkrieg

    hi again Mustafa,

    can you help me on this issue,

    i was successfully create a value file with communication setting = 0x03 (Fully encrypted). now i try to send debit command but i always get result 0x1E (Integrated Error).

    here is the log :

    session key from key to debit : 00010203 BA314BC6 04050607 515D9F8D

    to PICC :
    DC 00 8F 15 73 95 69 60 69 A6

    from PICC :
    1E

    here is my C code to debit :

    set_debit_encrypted (int fileno, int amount, byte_t * sessionkey, byte_t * result)
    {
    byte_t cmd[10] = {0};
    byte_t tmp[8] = {0};
    byte_t iv[8] = {0};

    tmp[0] = amount & 0xFF;
    tmp[1] = (amount >> 8 ) & 0xFF;
    tmp[2] = (amount >> 16) & 0xFF;
    tmp[3] = (amount >> 24) & 0xFF;

    // 2 bytes CRC 16
    word_t crcval = crc_16 (tmp, 4);
    tmp[4] = crcval & 0xFF;
    tmp[5] = (crcval >> 8) & 0xFF;

    // 2 bytes padding
    tmp[6] = 0x00;
    tmp[7] = 0x00;

    TDESEncryptData (iv, sessionkey, tmp, 16);

    cmd[0] = 0xDC;
    cmd[1] = fileno;
    memcpy (cmd+2, tmp, 8);

    TRANCIEVE (cmd, 10, res);

    }

    thank you

    regards
    Teguh

  • Mustafa Moripek

    Hi Teguh,
    I think the issue is that you have used
    TDES encryption.You had to use TDE
    decryption instead.Because PCD always
    decrypts the data before sending it to
    PICC.
    Mustafa

  • teguhblitzkrieg

    hi mustafa,

    i was changed to 3DES Decrypt mode before sending to PICC but i get 0xBE (boundary Error) what could went wrong ?

    thank you
    Regards

    Teguh

  • Kriss Pujats

    Hei. I am new to desfire ev1 coding.
    This forum has been a gold to me.
    Managed to authenticate, get the right session key, calculate crc16 and change any key.
    The problem is (what i cannot find in this forum or anywhere on internet), I am unable to authenticate with my new key. (recieveing AE)
    for example after changing to this key:
    00000000000000030000000000000003
    i get the right keyversion which is ‘1’ (00000001)
    for this key:
    03000000000000030300000000000003
    i get keyversion ’81’ (10000001)
    this implies that the key has been changed to the right value

    but i am still unable to authenticate
    I am running out of ideas
    for authenticate command i use bruno’s comment on March 5th, 2011 at 04:11
    for changekey command i use Mustafa’s comment on March 7th, 2011 at 16:56
    I also noticed that i cannot change the password if at least 1 of the bytes is >= ’80’ i recieve 1E error
    (for crc16 i use init=0x6363,poly-0x8408)

    any help would be highly appreciated.

  • Kriss Pujats

    sorry…
    i just found this post by Mustafa
    December 24th, 2012 at 13:28

    it worked wonderfully

    Mustafa… you just saved a startup.
    Thanks.

  • Mahendra Singh

    Hii,

    I am new mifare programming, I am using acs acr 122 u device.
    I want to create application and files on mifare card.
    Please Provide me required info for that.

    Thanks

  • Mahendra Singh

    I am using mifare desfire card

  • GW

    Hi,

    Hope someone can help. One of my Desfire Cards has started returning a value 0x01 in response to any commands I send, for example in my Select PICC Application command below –

    My command sequence is (using wrapped commands)

    SEND -> 90-5A-00-00-03-00-00-00-00 // Select PICC
    Response -> 01

    I would normally expect Response to be 91 00

    I have read that a 0x01 can be returned if the PICC requires more time (a WTX, waiting time extension) but I’m not sure if this is the reason. Also I don’t know what to respond to this request.

    Thanks
    GW

    • GW

      Bit more information, the error appeared to start after I sent a formatPICC command (0xFC). Unfortunately I missed the status response sent the first time I sent the command. Any further sends of the command just generate the 0x01 response.

      When sending the formatPICC command does this delete the Master Application 0x00?? I didn’t think it would. Has anyone ever had any problems after sending formatPICC command.

      Thanks
      GW

  • Chiase

    Hi Bruno Bertechini /Mustafa,

    I’m working on AES authentication. I tested some aes algorithm but is successful. So, could you send me the aes algorithm (in C)? email: chiase83@yahoo.com.vn

  • Chiase

    Hi Mustafa,
    I have a AES application. I want to change the key 01 AES from default value (0x00 … 00) to 0x0f 0e 0d 0c … 01 00. After selecting the AID, I authenticate the AID with master key (key 0):
    Reader: 0xaa 00
    DF: af 6b 08 d6 7b 82 07 d0 87 90 12 a1 fb cd d6 c1 f8
    =>rnd_B: 0f da ee a0 45 b2 fe 03 98 1a 00 d8 d0 3f f2 02
    Choise rand_A is: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
    I get a session_key: 00 01 02 03 0f da ee a0 0c 0d 0e 0f d0 3f f2 02
    Change key 01 AES:
    New key: 0f0e0d0c0b0a09080706050403020100
    CRC32(C4(cmd) + 01(KeyNo) + (New key) + 77(new key version)) = e8 e6 83 0b
    Encrypt AES block data of (Cmd + KeyNo + (New key) + (new key version) + (CRC32)+ (padding 9 bytes 00)) with session_key =
    First AES (C4 01 0f 0e 0d 0c 0b 0a 09 08 07 06 05 04 03 02) with IV = 16 byte 00
    => 8d 9c 75 9c 65 b3 7f 6b e4 2a eb ec 7b bc 96 68
    And Second AES (01 00 77 e8 e6 83 0b 00 00 00 00 00 00 00 00 00) with IV (First AES)= C4 01 0f 0e 0d 0c 0b 0a 09 08 07 06 05 04 03 02 (CBC mode)
    => 46 f2 44 2a bc cf 6a e3 c6 cf 55 af 1e 79 57 25
    Finally, I send:
    C4 + 01 + 8d 9c 75 9c 65 b3 7f 6b e4 2a eb ec 7b bc 96 68 + 46 f2 44 2a bc cf 6a e3 c6 cf 55 af 1e 79 57 25
    The card DF responses 0x1E.
    Please show me where is wrong?!

  • Mustafa Moripek

    Hi Chiase,
    you have authenticated with key number 0 to
    change key number 1.You have to bitwise xor
    the current key with the new one add the new key
    version and build crc32 over command + key number
    + xored data + key version and additionally a crc32
    of the new key is appended.After padding you
    AES decrypt the data and send it in cbc mode to the
    PICC.
    Mustafa

  • Chiase

    Hi Mustafa,

    Thanks your reply! I try it and feedback result!

  • Chiase

    Hi Mustafa,

    I can’t change the key AES as your guide. I wonder what is “bitwise xor
    the current key with the new one add the new key version”. Could you explain it clearly? It means:
    1. CRC32 (Cmd + KeyNo + [new_key ^ old_key] + new_keyversion + CRC32(new_key)) or
    2. CRC32 (Cmd + KeyNo + [new_key ^ old_key] + [new_keyversion^old_keyversion] + CRC(new_key)) or?
    3.???
    Thanks,
    Chiase

    P.s: GetKeySetting of the application is 0f 8e (authenticate with key number 0 when changing any key)

    • Mustafa Moripek

      Hi Chiase,
      The right procedure is as follows:
      CRC32(Cmd+KeyNo+[new_key ^ old_key]
      +new_keyversion)+CRC32(new_key)+padding
      Key Setting 8E means you have to
      authenticate with key No.8 (not 0).
      Mustafa

      • Chiase

        Hi Mustafa,

        Key setting of the application that I want to change key is 0x0F 0x8E. Because I created the application is AES authentication with 14 key (it means second byte is 8E). Right?

  • GW

    Hi,

    I hope someone can help me with my ChangKeySettings command for the Master Application

    I’m authenticated with the card using AES

    Process I’m trying to go through to change the Key settings to 0x09

    From what I could tell, with CRC16 only the data (09) is used but for CRC32 the command and data is used (54 09)

    CRC32(54 09) = 19 2d cd f4
    Pad data before encryption = 09 19 2d cd f4 00 00 00 00 00 00 00 00 00 00 00

    AES Encrypt using Session Key and IV from last encryption operation (CMAC)

    Send 54 (cmd Code) + Encrypted Data

    The card always responds back with a 1E command but I can’t see where I’m going wrong?

    Thanks
    GW

    • GW

      Turned out my CRC32 was wrong and needed reversed. Strange as I’d checked it against other CRC32’s in this blog that appeared to be correct…

  • Chiase

    I have changed a AES key successfully. It’s right what Mustafa guides. Note byte order of CRC32. Thanks Mustafa!

  • GW

    Hi,

    Can someone please confirm / correct how the IV works while using AES.

    I understand during authentication I start with an IV of 0x00 (16bytes) that the result of each encryption / decryption operation is used as the IV for the next encryption / decryption operation.

    After authentication the IV is reset to 0x00 (16bytes)

    My first command I send to the card I calculate the CMAC which then provides me with an IV, when the card responds I use the IV calculated from the Send process as the IV for calculating the received CMAC. Again the result of the CMAC calculation will be used as IV for the next CMAC calculation. I know this is correct as I can send / receive multiple requests and the CMAC always verifies.

    When I’m doing an operation such as ChangeKey / ChangeKeySettings that requires the data to be encrypted, do I use a blank IV of 0x00(16 bytes) or do I use the IV that I calculated from my last CMAC operation. I also assume that the result of the encryption (last block encrypted) becomes the new IV for future CMAC calculations etc

    Thanks GW

  • Chiase

    Hi Mustafa,

    I try to authenticate card using 3TDEA algorithm. How’s it different from 2TDEA? What’s 3TDEA authentication procedure?

    Thanks!

  • Chiase

    Hi all,

    My problem is rand_A’ encryption from card wrong when authentication 3TDEA. I think IV (initial vector) for encryption rand_A’ is not exactly (I use IV all zeros). How do I choose IV?

    Thanks!

    • Mustafa Moripek

      Hi Chiase,
      sorry I was busy therefore I couldn’t answer your
      earlier comment.To make it clear TDEA means triple
      DES encryption algoritm.There is no 2TDEA
      or 3TDEA but 2KTDES or 3KTDES.2KTDES has
      a key which is 16 Bytes long and 3KTDES has
      a key which is 24 bytes long.You start always
      with IV all zeroes.Please write clearly what you want
      to do.If possible write the whole log.
      Mustafa

  • Chiase

    Hi Mustafa,
    Thank your reply!
    I created a 3K3DES featured application. Below is all data during 3K3DES authentication.

    Reader sends: 1a 00
    Card responses: 56 d7 e3 44 47 6f c2 33 97 fd 95 18 a0 d1 47 c1

    Decrypt the above data using encrypt-decrypt-encrypt DES algorithm with IV = all zeros and default key (all zeros).
    =>Random B = d4 98 36 0b 6c bf 28 48 09 68 79 62 88 03 df fa
    Random A is chosen 00 01 … 0f
    Rotate random B and concentrate to random A:
    00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 98 36 0b 6c bf 28 48 09 68 79 62 88 03 df fa d4
    Encrypt the data using encrypt-decrypt-encrypt DES algorithm with IV = all zeros and default key (all zeros), I obtain:
    49 1e 89 0d e9 ac e9 32 0a a0 df 24 e9 fe 9c ec e3 3b de a3 ca 59 0f 41 73 b6 52 4a 3e b2 68 24

    Reader sends: 49 1e 89 0d e9 ac e9 32 0a a0 df 24 e9 fe 9c ec e3 3b de a3 ca 59 0f 41 73 b6 52 4a 3e b2 68 24
    Card responses: 23 3f b4 dc c4 8a af 3b 03 26 64 2d b7 8c 14

    I decrypt the response as above decrypt, I have got: 8f 21 49 ee ea f3 ae 2c 09 0a 0b 0c 0d 0e 0f 97.
    Why is first 8 bytes wrong?
    (I still use IV = all zeros and default key (all zeros) to decrypt the data).
    What is session key in the case?

  • Mustafa Moripek

    Hi Chiase,
    I am not in the office,so I cannot check your data.
    There are some essential errors in your proceeding.
    First thing:If you want to use 3K3DES then you have
    use standard mode of encrypting and decrypting not
    the native mode.In native mode you decrypt the data
    when you receive it or you send it.In standard mode
    you decrypt the data when you receive it and
    encrypt the data when you send it.Second thing:
    Your TDES algoritm is not correct.
    3DES Decryption: Dec (K1) Enc(K2) Dec (K3)
    3DES Encryption: Enc (K1) Dec (K2) Enc (K3)
    For your key is all zeroes the first 8 bytes are
    equal to last eight bytes when you encrypt
    or decrypt.
    Mustafa

  • Chiase

    Hi Mustafa,

    Thank for your reply.

    I re-write 3K3DES en/decrypt CBC mode algorithm as your recommendation. However, I still the above error (decrypt first 8 bytes wrong).
    I re-send you my data:

    Reader send: 1a 00
    Card response: 03 16 8a 0e a3 2d 32 0c 0a a2 bb 12 ae af 9e 4f

    Random B is “0d 82 d4 eb 05 38 74 63 36 7d 87 bf fc 21 23 cc”
    Random A is chosen 00 01 … 0f

    Rotate random B and concentrate to random A:
    “00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 82 d4 eb 05 38 74 63 36 7d 87 bf fc 21 23 cc 0d”

    Encrypt the data, I obtain:
    “49 1e 89 0d e9 ac e9 32 0a a0 df 24 e9 fe 9c ec ef f4 ad df 59 c6 41 5a 52 d0 0c 56 29 2d 72 5f”

    Reader sends: 49 1e 89 0d e9 ac e9 32 0a a0 df 24 e9 fe 9c ec ef f4 ad df 59 c6 41 5a 52 d0 0c 56 29 2d 72 5f
    Card response: c7 6c 07 6d 22 e6 d9 a7 df f7 e6 bf 73 c4 c7 cb

    I decrypt the data and have get: f1 69 1d fc 83 b5 3a 57 09 0a 0b 0c 0d 0e 0f 0a

    Could you please take a few time to look my data ?
    Thanks,
    Chiase

  • Chiase

    P.s: what’s a session key after authentication?

  • Mustafa Moripek

    Hi Chiase,
    there is not an error “decrypt first 8 bytes wrong”.
    The session key is built as follows:
    RndA byte0..3+RndB byte0..3+RndA byte6..9+
    RndB byte6..9+RndA byte12..15+RndB byte12..15
    Mustafa

  • Chiase

    Hi Mustafa,

    It means random A’ = “f1 69 1d fc 83 b5 3a 57 09 0a 0b 0c 0d 0e 0f 0a” to be right?
    Because I choose random A to be 00 01 02 … 0f.

    Thank you!
    Chiase

  • Mustafa Moripek

    Hi Chiase,
    If you choose 00 01 02 ..0f as RndA then you
    use this RndA for building the session key.If the
    RndA which is sent by the PICC doesn’t match
    with your chosen RndA then the authentication
    is failed.
    Mustafa

  • Chiase

    Hi Mustafa,

    I see you. But if the authentication is failed, the card will not response the encrypted Rnd_A. Because I send encrypted (Rnd_A || Rnd_B’). I only receive second 8 bytes of Rnd_A to be right (it is 09 0a 0b 0c 0d 0e 0f). It’s strange!

    Thanks,
    Chiase

    • wdtech

      Hi Chiase,
      I have the same problem as yours. While I don’t have the NXP document, the bad Rnd_A received is probably due to the wrong initial IV to decrypt the Rnd_A.

      Anybody get a clue to solve it?

      Tim

  • narges

    hi
    could anyone explain me the file size format? why is it 3 bytes?

  • akdrmrk

    Hi everybody

    I need ISO-7816-4 ATR command.

    Can anybody help me ?

  • Leonhard

    Hello!
    I’d like to use “INTERNAL AUTHENTICATE” on a DESfire EV1 card but I wonder what the required steps are before this command works.
    I mean, do I have to create an application first? Do I need to select that application before?
    Please help 🙂

    • Steinar

      You should automatically be in application 000000 when connected to the card so you should be able to authenticate with key 0 without any additional steps. I think you might have to do that before even being able to create an application.

  • xbego

    Help !

    PCD : 90 0a 00 00 01 00 00
    PICC : 51 76 ae e7 00 d0 7a 59 91 af
    Random Key : 22115544
    PCD : 90 af 00 00 10 dd 11 e8 f0 74 10 60 43 ef f5 19 7f f6 9d 37 64 00
    PICC : 91 ae

    Help Please

    Thnx all

    • Mustafa Moripek

      What is your authentication key?
      Mustafa

      • xbego

        Thnx for your response Mustafa,

        I’m using APDU, i don’t know where i have to put the auth key, i see an example above like this :

        –> 90 0a 00 00 01 00 00
        90 af 00 00 10 b0 cc bc ed 8f c8 38 c9 08 dc e2 4d 86 ca ec 3c 00
        <– 76 73 d9 49 71 3f f2 d1 91 00

        Regards,

  • Mustafa Moripek

    Hi Xbego,
    you don’t put the authentication key anywhere.
    You use it for encrypting and decrypting.The
    communication between card and reader is
    made in encrypted way.Therefor you have to
    know the authentication of the card.Otherwise
    you cannot communicate with the card,and
    you get the answer AE (authentication error).
    Mustafa

    • xbego

      Hi Mustafa,

      oo ok, i use 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 for decrypt data, please help.

      Regards,

      • Mustafa Moripek

        Hi Xbego,
        I need your RndA (random number).In your
        previous comment you have written
        Random Key : 22115544.If this is your
        random number RndA then it is wrong,
        because it should be 8 bytes long.
        For testing your DES decrypting algorithm
        I have decrypted PICC response (51 76 ae
        e7 00 d0 7a 59) and have got as
        RndB:27 32 E4 F1 8F 82 8D 57
        If you send me a new log and your RndA
        I can verify your data and find where
        the issue is.
        Mustafa

      • xbego

        Hi Mustafa,

        here’s my new log, hope you can verify

        PCD : 90 0a 00 00 01 00 00

        PICC : 51 7c 87 10 de 0c 04 db 91 af

        DES Decrypt HEX Data (RndB) : 3a 4d 6b 09 4b ac a8 4a

        Random Key RndA : 39 37 30 36 35 31 39 30

        RndA + RndBShift : 39 37 30 36 35 31 39 30 4d 6b 09 4b ac
        a8 4a 3a

        Decrypt RndA + RndBShift : e4 0f 31 68 09 da c6 eb 06 86 8f 49 e2 73 e6 7c

        Request 2 Command : 90 af 00 00 10 e4 0f 31 68 09 da c6 eb 06 86 8f 49 e2 73 e6 7c 00

        Response 2 Hex : 91 ae

        Best Regards,

  • Mustafa Moripek

    Hi Xbego,
    The first part of your payload
    ( e4 0f 31 68 09 da c6 eb 06 86 8f 49 e2 73 e6 7c)
    is correct,that means your DES decrypting
    algorithm is correct.But I couldn’t realize
    how you have got the second eight bytes.
    The correct way of proceeding is to use
    CBC send mode.To decrypt the second eight
    byte you have to exor the second eight bytes
    (06 86 8f 49 e2 73 e6 7c) with the current
    IV (e4 0f 31 68 09 da c6 eb) and then DES decrypt
    them.The result should be the second eight bytes
    of your payload.
    Mustafa

  • xbego

    Hi Mustafa,

    now i’m trying to change key and get response 1e, here’s the log :

    Start Authentication ….
    Random Key : 14601252
    RndA : 3134363031323532
    Response Hex : 934a0bd645c703b491af
    Response Hex Data : 934a0bd645c703b4
    RndB : 665172b9
    First Half RndB : 665172b9
    First Half RndA : 31343630
    Authentication VALID with Key No : 0
    Change Key …. with new key 00..0F
    Change Key No : 5
    tmp value : 0000000000000000
    Session Key 8 Bytes : 31343630665172b9
    CRC 16 : 77f577f500000000
    block 1 : 0001020304050607
    block 2 : 08090a0b0c0d0e0f
    r1 = block1 xor tmp
    r1 : 0001020304050607
    r2 = DES(r1) with key : Session Key 8 bytes
    r2 : 26affde094b72f18
    r3 = block2 xor r2
    r3 : 2ea6f7eb98ba2117
    r4 = DES(r3) with key : Session Key 8 bytes
    r4 : 470e23a2d8e638e9
    r5 = crc xor Session Key 8 bytes
    r5 : 46c141c5665172b9
    r6 = DES(r5) with key : Session Key 8 bytes
    r6 : 0641f99f275d4d2a
    data : 0526affde094b72f18470e23a2d8e638e90641f99f275d4d2a
    Request Change Key : 90c40000190526affde094b72f18470e23a2d8e638e90641f99f275d4d2a00
    Response Change Key : 911e

    Help Please …. Thnx

    Best Regards,

  • Chiase

    Hi Mustafa,

    How is data decryption procedure when reading data from AES file?
    After authentication with key 0, I read 8 byte of AES file (communication mode is encipher). I received data is (eb 1a 9b f3 34 e2 4d 21 99 2e fa ce e9 6e 91 cd). My session key is 00 01 02 03 67 1b 4f 1e 0c 0d 0e 0f fd 68 75 e0. The expectation data is 8 bytes zero.
    However, I decrypted received data with the session key and Initial Vector (all zeros), I did not get all zeros.
    Please help me?!

    Thanks!

    • Mustafa Moripek

      Hi Chiase,
      in fully enciphered communication mode
      you have to use CMAC’ing.You have to
      build CMAC on cmd+file No.+ offset + length.
      And as current IV you have to use the last
      IV of authentication.You don’t send this to the PICC.
      You have to calculate this for updating the IV.
      Mustafa

    • mileaux

      Hi Chiase,

      the IV after an authentication has to be zero!

      For read data you have to calculate the CMAC over ‘cmd+fileNo+offset+length+padding’. AES CMAC needs padding to a multiple of 16 Bytes with 0x80, 0x00, …

      Now the part that took me the most time to figure out:

      In the CMAC calculation you have to use AES encryption to generate Subkeys and in a loop that is depending on your messagelength.

      In both cases you have to use either ECB mode (ECB doesn’t need IV) or you use an empty Vector and reset it every time after encryption in CBC. You don’t need to touch the IV by your own.

      Only in the last encryption of the CMAC calculation you give the IV as input. If your Algorithm is different, try the algorithm described in SP800-38B and programmed by Junhyuk Song and Jicheol Lee.

      http://www.ietf.org/rfc/rfc4493.txt

      It is written in C so you may adjust it to your language.

      Kind regards

  • Chiase

    Hi Mustafa, Mileaux
    Thanks for your replies! I’ll try the guides and feedback as soon as possible!
    Best regards,
    Chiase

  • Chiase

    Hi Mustafa, Mileaux,

    Now, I can calculate CMAC correctly. I use CMAC as IV for decrypting received data from DESFire EV1. However, I’m facing a problem. If I read less 12 byte (DESFIRE responses 1 block, 16 bytes), decrypted data includes zero bytes and 4 bytes CRC32. If I read more 12 byte (DESFIRE responses 2 blocks, 32 bytes), when decrypting the data, all is zeros, there are not CRC32 bytes. I use CBC AES mode with IV is from CMAC.
    Could you tell me why?

    Regarding writing data enciphered communication AES mode, after successful authentication, the IV is reset to zero or CMAC of (cmd+file No+Offset+length+data+padding) or anything else?

    Best regards,
    Chiase

  • Chiase

    Hi Mustafa, Mileaux,

    I’m sorry. I’ve mistaken about reading data. Now, I can read data from DESFire exactly.
    I have only the question about writing data enciphered communication AES mode.

    Thanks,
    Chiase

    • mileaux

      Hi Chiase,

      for write data I do the following steps:

      1. CRC32 Calculation over

      ->’cmd+fileNo+offset+length+data’

      2. Append CRC32 to the data only without command, fileNo, offset and length.

      -> ‘data+CRC32’

      3. Padd the ‘data+CRC32’ with 0x00 (NOT 0x80, 0x00…) to a multiple of 16 Bytes, if needed.

      -> ‘data+CRC32+Zeropadding’

      4. Encrypt ‘data+CRC32+Zeropadding’ with AES

      -> crypted( ‘data+CRC32+Zeropadding’ )

      5. Send to the PICC

      ->’cmd+fileNo+offset+length + crypted(data+CRC32+Zeropadding)’

      Keep in mind that you can only transfer 60 Bytes in one send. So for the first send you have the 8 Bytes from the command, fileNo, offset and length + the first 52 Bytes from crypted(data+CRC32+Zeropadding).

      After the first send you have 1 Byte for command 0xAF and 59 Bytes for the rest of crypted(data+CRC32+Zeropadding).

      PS: If you have doubts about IV management, try to read the same data multiple times in a row. If this works and your write data doesn’t, the error might be at some other point.

      Kind regards

  • Chiase

    Hi Mileaux,

    I can write data exactly. Thank you very much!
    Regarding IV management, After successful authentication, I calculate CMAC and use it to XOR with decrypted data from a file (read file), I obtain correct data. However, I continue reading data from the file and use the CMAC do XOR with decrypted data, I don’t get same data. I think it is due to CMAC be wrong. How do I update CMAC?

    Best regards,
    Chiase

    • mileaux

      Hi Chiase,

      you don’t to ‘update’ (xor data) your CMAC. You generate it over the answer from the card and with that generation the IV is updated. So the IV is set for the next en- and decryption.

      Keep in mind that the calculation of received CMAC has to be done like this:

      CMAC received calculation:
      cmac(‘parameter1+…+parameterN+status’)

      CMAC send calculation:
      cmac(‘status+parameter1+…+parameterN’)

      Kind regards

  • Chiase

    Hi Mileaux,

    I try the your guides and feedback ASAP!

    Thank you,
    Chiase

  • Chiase

    Hi Mileaux,
    I implement as following:
    1. Authenticate AES mode and get session key.
    2. IV_1 = CMAC (cmd+File No.+Offset file+data length); cmd : read data
    3. Read encrypted data from card (called en_data_1, 16 bytes)
    4. Data_1 = CBC_decrypt_AES(en_data_1, key, IV); key = session key; IV = IV_1.
    5. Continue reading encrypted data from card (en_data_2, 16 byte)
    6. Data_2 = CBC_decrypt_AES(en_data_2, key, IV_2); key = session key and Data_2 must be equal Data_1.
    In the case, what is IV_2?
    Is it en_data_1? Or is it CMAC(en_data_2||Status)? Or anything else?
    Thanks Mileaux
    Chiase

    • mileaux

      Hi Chiase,

      IV != CMAC(cmd+File No.+Offset file+data length);

      This is wrong. The initial Vector is set by the encryption during the CMAC calculation. You should not change it by yourself.

      I guess what you think is that the IV = CMAC, but that’s not true. It’s more like CMAC = IV. And that’s not the whole truth. IV normally has 16 Bytes and CMAC only 8 Bytes. Ater the shiftig operations for the MAC you have to encrypt it to get CMAC. And after that encryption your CMAC is already calculated, because it’s a part of the IV. Namely the first 8 Bytes.

      message = (cmd+File No.+Offset file+data length)

      CMAC:

      1 Subkey generation with Session Key
      2 MAC generation by shifting Subkeys with message
      3 AES_Encryption( MAC ) – This sets your IV
      4 CMAC -> Copy the first 8 Bytes from the IV to the CMAC

      Now the IV ist set for the next en/decryption.

      Just decrypt en_data_1 and give the same IV (because it will be changed) for the decryption of en_data_2.

      Kind regards

      • Abraham Putra P

        Hello mileaux,

        I can authenticate and write fully enchiper using AES key, but could you explain more detail about how to calculate CMAC?
        Like you said shifting operation of MAC, which shift and how many is it? And after that encryption using what key and what’s the IV? thank you.

  • Chiase

    Hi Mileaux,

    Thank for your reply! I understand what you say. “CMAC is first 8 Bytes of IV during the CMAC calculation.”

    However, as sending two reading data commands continuous (file No, offset, length is same), I receive two different data packages from card. So, I can’t apply the IV_1 to decrypt second data package (as last comments, it is en_data_2). Because it decrypts other result.

    Below is all data that I implemented:
    1. Session key: 0x00, 0x01, 0x02, 0x03, 0x16, 0x96, 0xe3, 0x11, 0x0c, 0x0d, 0x0e, 0x0f, 0x4d, 0xfe, 0x0d, 0xef
    2. Message (cmd+File No.+Offset file+data length): 0xbd, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00
    3. IV: 0x72, 0x53, 0x95, 0x61, 0x06, 0x83, 0x92, 0x11, 0xda, 0xe2, 0x2a, 0xfd, 0xc2, 0x09, 0x64, 0x5f
    4. CMAC (8 byte): 0x72, 0x53, 0x95, 0x61, 0x06, 0x83, 0x92, 0x11
    5. PCD sends message to card.
    6. Data from card: 0x60, 0xae, 0x97, 0xfa, 0xa2, 0xbd, 0xd3, 0x6d, 0xf9, 0x91, 0xad, 0xb0, 0xe4, 0x77, 0x8e, 0x5b (called en_data_1)
    7. Decryte data CBC AES mode with session and IV above: 0x11, 0x11, 0x11, 0x11, 0x00, 0x00, 0x00, 0x00, 0x92, 0xca, 0x7f, 0x1b, 0x00, 0x00, 0x00, 0x00
    8. PCD continues sending message.
    9. Data from card: 0x1a, 0xb0, 0xcf, 0xbb, 0x47, 0x70, 0x55, 0xf3, 0xe6, 0x5d, 0x92, 0x6d, 0x62, 0x2d, 0x73, 0x46 (called en_data_2)

    En_data_1 is different to en_data_2. So, I can’t use IV for decriphering en_data_2.
    Could you check my data?
    Best regards,
    Chiase

    • mileaux

      Hi Chiase,

      I thought you send two independent Read Data commands. Sorry for my misunderstanding.

      So you have en_data_1 (Part 1) and en_data_2 (Part 2) which belong together right?

      In that case I wait until the PICC stops sending data and concatenate en_data_1, en_data_2,…, en_data_n and then decrypt with the IV after CMAC calculation.

      But it has to work if you use the updated IV after en_data_1 decryption, not the same! After every en/decryption the IV is changed! That’s namely the sense of the CBC mode.

      Cheers

  • Chiase

    Hi Mileaux,

    Thank your reply!
    Yes. I want to use many Read data commands after authentication successful.
    I try the your guide by using en_data_1 as IV for decrypting en_data_2 (because it is CBC mode) or re-calculating IV using en_data_1 to be initial vector during CMAC calculation (default it is all zeros). But I’m not successful!
    So, the application in the future, I think I will forbid using many Read data commands on the file or must re-authenticate before reading data for resetting IV calculation!

    I also have a question about Read Data Command. I wonder the 4 bytes following data is CRC32 of data or Data||status? Because I calculate CRC32 of the data (0x11, 0x11, 0x11, 0x11, 0x00, 0x00, 0x00, 0x00) to be 0x92, 0x22, 0x44, 0xfd while result that card response is 0x92, 0xca, 0x7f, 0x1b.

    Best regards,
    Chiase

    • mileaux

      Hi Chiase,

      I think you might missunderstood the concept of the CBC mode and the initial vector. I was also at this point and had the same thoughts about re-authenticate to read the card. But this will create more problems at other points.

      So I’ll try to explain more detailed.

      You don’t use the en_data_1 as IV for en_data_2!!! You should never write something into it!!!

      After authenticate you have an IV filled with zeros.

      Step 1)

      Read data from card:

      IV[16] = [0x00,…, 0x00]

      en_data_1[16] = [ 0x60, 0xae, 0x97, 0xfa, 0xa2, 0xbd, 0xd3, 0x6d, 0xf9, 0x91, 0xad, 0xb0, 0xe4, 0x77, 0x8e, 0x5b ]

      Step 2)

      Decrypt data 1:

      de_data_1[16] = [ 0x11, 0x11, 0x11, 0x11, 0x00, 0x00, 0x00, 0x00, 0x92, 0xca, 0x7f, 0x1b, 0x00, 0x00, 0x00, 0x00 ]

      IV is changed by AES_DECRYPTION_CBC, not by your own! Don’t write en_data_1 into it.

      Step 3)

      Read more data:

      en_data_2[16] = [ 0x1a, 0xb0, 0xcf, 0xbb, 0x47, 0x70, 0x55, 0xf3, 0xe6, 0x5d, 0x92, 0x6d, 0x62, 0x2d, 0x73, 0x46 ]

      Stept 4)

      Decrypt data 2:

      The IV is set from the last AES action. In this case from decryption of en_data_1. Just use it!

      You should be able to do as much actions with AES en- and decryption as you want and get the right data. Otherwise you’ll get problems later on.

      CRC32:

      For send crc32 ist calculated over ‘cmd+cmdBytes+de_data’

      For receive crc32 calculated over ‘data+status’

  • Chiase

    Hi Mileaux,

    Thank for your reply!
    I’m clear what you say.
    In the CBC mode decryption, last encrypted data is XORed with current decrypted data. Right?
    In the my case, en_data_1 is only 16 bytes. So , I use it as IV for decrypting en_data_2 (because of CBC mode, last encrypted data of AES_DECRYPTION_CBC is en_data_1. Right?)
    I have showed all my data. So, could you re-calculation the them? What value is the IV for decryption of en_data_2? I know I bother you so much! But I calculated many way, the result is not as my expect!

    P.s: Mustafa, what do you think?
    Best regards,
    Chiase

    • mileaux

      Hi Chiase,

      This is what i get:

      Message = BD 04 00 00 00 08 00 00

      Session Key = 00 01 02 03 16 96 E3 11 0C 0D 0E 0F 4D FE 0D EF

      IV before CMAC = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

      CMAC Calculation…

      IV after CMAC = 72 53 95 61 06 83 92 11 DA E2 2A FD C2 09 64 5F

      CMAC = 72 53 95 61 06 83 92 11

      Encrypted data 1 = 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B

      Decrypted data 1 = 11 11 11 11 00 00 00 00 92 CA 7F 1B 00 00 00 00

      Encrypted data 2 = 1A B0 CF BB 47 70 55 F3 E6 5D 92 6D 62 2D 73 46

      Decrypted data 2 = 56 A7 A5 CA 08 EE 4B 4E 30 31 62 FF 06 F4 B3 53

      What do you send at this point

      >>8. PCD continues sending message.<< ?

      Another Read Data or 0xAF? The problem might be at this point.

      Kind regards

  • Chiase

    Hi Mileaux,

    I send another Read Data command. It’s message (BD 04 00 00 00 08 00 00), old message.
    The card responses en_data_2, 00(status) 1A B0 CF BB 47 70 55 F3 E6 5D 92 6D 62 2D 73 46. It’s all my problem!

    Thanks and best regards,
    Chiase

    • mileaux

      Hi,

      the solution is simple. You have to calculate CMAC again after the second Read Data. If you’re authenticated, then you have to calculate CMAC for almost every command if you want to verify the transmission.

      Message = BD 04 00 00 00 08 00 00

      Session Key = 00 01 02 03 16 96 E3 11 0C 0D 0E 0F 4D FE 0D EF

      IV after Authenticate = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

      CMAC Calculation…

      IV after CMAC = 72 53 95 61 06 83 92 11 DA E2 2A FD C2 09 64 5F

      CMAC = 72 53 95 61 06 83 92 11

      Encrypted data 1 = 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B

      Decrypted data 1 = 11 11 11 11 00 00 00 00 92 CA 7F 1B 00 00 00 00

      IV after Decription = 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B

      CMAC Calculation…

      IV after CMAC = 27 18 23 21 AA 53 98 23 5B 6A B0 54 E2 83 3D 08

      CMAC = 27 18 23 21 AA 53 98 23

      Encrypted data 2 = 1A B0 CF BB 47 70 55 F3 E6 5D 92 6D 62 2D 73 46

      Decrypted data 2 = 11 11 11 11 00 00 00 00 92 CA 7F 1B 00 00 00 00

      This is my output with the second CMAC Calculation.

      Kind regards

  • Chiase

    Hi Mileaux,

    How do you calculate second CMAC (or IV: 27 18 23 21 AA 53 98 23 5B 6A B0 54 E2 83 3D 08)?
    I know that CMAC calculation includes key, message. In the case, the key is session key. What is the message? BD 04 00 00 00 08 00 00?
    If it’s right, CMAC is 72 53 95 61 06 83 92 11 DA E2 2A FD C2 09 64 5F (old).

    Best regards,
    Chiase

    • mileaux

      Hi,

      you have to use the IV from the decription for your cmac calculation.

      IV = 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B

      Message = BD 04 00 00 00 08 00 00

      If you get this, you’re fine!

      IV after CMAC NEW = 27 18 23 21 AA 53 98 23 5B 6A B0 54 E2 83 3D 08

      CMAC = 27 18 23 21 AA 53 98 23

      If you get this, you’re CMAC calculation is false…

      IV after CMAC OLD = 72 53 95 61 06 83 92 11 DA E2 2A FD C2 09 64 5F

      CMAC = 72 53 95 61 06 83 92 11

      If your new cmac is the same as your old, then you need to change your cmac calculation algorith… You have to use CBC encryptionin the last step of cmac calculation, because of the IV.

      Regards

  • Chiase

    Hi Mileaux,

    I’ll try to calculate CMAC with IV 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B (called Z during subkey generation. Right?).

    Thanks,
    Chiase

    • mileaux

      Hi,

      Subkeys are calculated with IV = 00, 00, …, 00

      In the loop ‘for( i=0; i<n-1; i++ )' also use IV = 00, 00, …, 00

      After this loop, there should be another encryption. There you use

      IV = 60 AE 97 FA A2 BD D3 6D F9 91 AD B0 E4 77 8E 5B

      Cheers

  • Chiase

    Hi Mileaux,

    Exactly! You’re great!
    I’m successful! It’s so complex! Before, I try to use the IV for IV during subkey generation. I did not notice there are also IV during MAC generation.

    Thank you very much!
    Chiase

  • Chiase

    Hi Mileaux,

    I have a AES application. After authenticating with PICC master key, response from card includes parameters and a CMAC (8 byte) (i.e, response of getFileIDs command is 00(status), 04 (File ID), 03, 06, 05, (CMAC 8 bytes) f9, 8e, 1d, 8d, 97, 0a, b5, 75 ). After the getFileIDs command, I read data of the file and decrypt it. As the last problem, I can’t obtain right data. (if I read data after authenticating successful, I decrypt the data exactly.)
    I assume the problem is wrong IV. In the case, after information commands (such as getFileIDs, getFilesetting, getKeysetting, getApplicationIDs, v….), how is IV calculated?

    Best regards,
    Chiase

  • Chiase

    Hi Mileaux,

    I solved the problem. I have to calculate CMAC for the command, use it to calculate CMAC of response from card. Finally, CMAC of response is used to calculate CMAC for next commands. I think now I can manage CMAC (or IV).

    Thanks,
    Chiase

  • Tim

    Hello all,

    i am currently trying to write data in full encyphered mode after an AES Authentication. This always returns on me with 0x1E (Integrity Error).

    Does anyone know, what i am doing wrong on the write?
    I have appended a log with all crucial data. Key is all 00.

    RndA: 8e494d13292dac444fde87551824a13f
    ekRndB: 7cdbc311d73e0fab174d668096408499
    RndB: 6c6dbb6048107019a0d51cc64a521e75
    RndA_RndBDash: 8e494d13292dac444fde87551824a13f6dbb6048107019a0d51cc64a521e756c
    dkNo_RndA_RndBDash: 5174fb31066b278c8f9de645437429928305ecbd2c019502d871ce82c20117e4
    SessionKey: 8e494d136c6dbb601824a13f4a521e75
    ekNo_RndADash: 66f6520c85adf7d0331524d94e8c8827
    RndADash: 494d13292dac444fde87551824a13f8e
    RndADashExpected: 494d13292dac444fde87551824a13f8e
    L: 036961420125c81fddac9f2afa536501
    K1: 06d2c284024b903fbb593e55f4a6ca02
    K2: 0da585080497207f76b27cabe94d9404
    Starting IV: 00000000000000000000000000000000

    -> Auth done

    IV to encrypt: 00000000000000000000000000000000
    Data to send in plain text: 3d03000000080000
    Data to send enciphered: ff00ff00ff00ff00
    -> crc over all data
    Data to send enciphered with CRC appended: ff00ff00ff00ff00856e06cf
    padded Data to send enciphered: ff00ff00ff00ff00856e06cf00000000
    Enciphered data to send: c7c2b83ff1dcdf6cd643db02f13edc07
    Composed command: 3d03000000080000c7c2b83ff1dcdf6cd643db02f13edc07

    I have no problem to do a fully encrypted read, so i am pretty sure the Auth, Keys, CRC-32 and the decyphering works right.
    The read command is issued directly after the auth.

    Thank you in advance,
    Tim

    • mileaux

      Hi Tim,

      you have to calculate your crc over (cmd + header + plain data) and then append it to the message. After this you do the encryption of (plain data + crc + zeropadding).

      message = cmd + header + plain data

      crc32 ( plain data )

      message = cmd + header + plain data + crc32

      encryption ( plain data + crc32 + zeropadding )

      message = cmd + header + encryption

      Sorry for taking so long, but i was very busy in the last days.

      Kind regards

      • Tim

        Hello mileaux,

        i am sorry myself to have taken so long to react. I was busy with a wedding and the honeymoon afterwards 😉

        Thank you that you confirmed my understandings on the parts which to encrypt and what fields to append. I will check my code another time and look if i have not something stupid in there left.

        Thank you very much,
        Tim

      • Tim

        Thank you.

        After checking everything once more i found the problem laying after generating the right command.

        The wrapping of the native command into an APDU inserted a zero byte every time the size of a request changed due to CMAC or encryption.

        So encrypted commands do work now at my side.

  • destar

    hy mileaux,

    i’m trying to send command APDU write std data file, first command has 65 bytes length and no response, then i try to send command with length 60 bytes and returns success. any advice ? please help

    • mileaux

      Hi destar,

      can you post the messages you send like Tim did? (message, data, data+padding, encrypted data, …)

      There are many possible errors and without input i can’t figure out where the mistake in your code or program is.

      Kind regards

  • destar

    hi mileaux,

    this is the log :

    Data to Write : 306652324a464f7741536f4a53644b4b553562613731623932386662343834373665653065383138376537653035633431353965
    Request Write Data file no 1 Length : 65
    Request Command Write Data file no 1 : 903d00003b01000000340000306652324a464f7741536f4a53644b4b55356261373162393238666234383437366565306538313837653765303563343135396500

    i get no response for above request, but if i decrease the command length to 60 i get successfully response.

    Best Regards,

    • mileaux

      Hi destar,

      your data to write is 52 Bytes long. So why do you put the length to 65 or 60?

      Command for write data:

      0x3d + fileNo + LSB_Offset_MSB + LSB_length_MSB + data

      You send:

      0x90 + 0x3d + 0x00003b + 0x010000 + 0x00340000 + plain data

      You should send:

      0x3d + 0x01 + 0x000000 + 0x340000 + data

      If your data is 65 Bytes long, you send

      0x3d + 0x01 + 0x000000 + 0x410000 + data

      And the card should respond with

      0xAF

      And then you send

      0xAF + rest of data

      Kind regards

  • Mobile devices and NFC in public transit (part II) | Random Oracle

    […] word on the problem. Going one level deeper, DESFire protocol can operate in 2 different ways: “native” mode or “standards” mode. In standard mode the protocol messages are actually compatible with ISO7816. Cards support this, […]

  • mileaux

    Hi all,
    I have a problem changing the PICC Master Key from DES/2K3DES to AES.
    In one of the Application Notes NXP says, that ich have to send:
    Command + Key No + ENCRYPTED( KEY + KEYVERSION + CRC32( Command + Key No + Key + KeyVersion ) + Padding )
    That’s my log:
    CMD
    C4
    CMD + KEYNO
    C4 80
    CMD + KEYNO + KEY
    C4 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    00 00
    CMD + KEYNO + KEY + KEYVERSION
    C4 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    00 00 00
    CMD + KEYNO + KEY + KEYVERSION + CRC32
    C4 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    00 00 00 8B E9 ED B5
    CMD + KEYNO + KEY + KEYVERSION + CRC32 + PADDING
    C4 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    00 00 00 8B E9 ED B5 00 00 00
    CMD + KEYNO + ENC( KEYNO + KEY + KEY VERSION )
    C4 80 7B 82 0E BC 5F 4F F0 DC 7A 34 D4 AF 8F F1
    82 9F 6B CD EF 52 71 CB FB 7E
    ####
    The Authentication:
    Auth Key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    CMD + KEYNO
    -> 0A 00
    ENC PICC CHALLANGE
    AF E6 30 5E 7F EF A9 03 6A DD E7 E4 97 0A 47 89 A3
    END PCD CHALLANGE
    <- 00 19 D6 1D 32 14 9A 62 0E
    Session Key Generated
    23 47 C1 55 E2 34 D6 F7 7F 80 70 7A 0B 54 24 CA
    ####
    When I try this, I always get 1E from the card, which meas Integrity Error. Can someone find my mistake?

    Kind regards

  • Mustafa Moripek

    Hi Mileaux,
    I think the issue is your session key.You are
    authenticating with default key all zeroes.
    You have to use single DES and the first half
    of your session key should be equal to
    second half.(RndA(0-3 bytes)+RndB(0-3)+
    RndA(0-3 bytes)+RndB(0-3))
    In your case :
    23 47 C1 55 E2 34 D6 F7 23 47 C1 55 E2 34 D6 F7

    Mustafa

    • mileaux

      Hi Mustafa,

      yes you’re right. I identified the problem a few hours ago. But that was not the only a mistake from me.

      For changing PICC Master Key from DES to AES, you also have to authenticate with 0x1A and not 0x00.

      Kind regards

  • Chiase

    Hi Mileaux,

    I changed the PICC Master Key from DES/2K3DES to AES successfully. After successful authentication with PICC Master key DES, I send the data:
    Command + Key No|0x80 + ENCRYPTED(New KEY + CRC16( New Key) + Padding ) (like same key DES change case).

    I only have a problem. How does PICC Master Key AES change?

    Best reagrds,
    Chiase

  • Ali

    Hi 2 All
    I can do change key setting when the first 8 bytes of key are equal to the second half.But My question is that : ” How can I do change key setting when the first 8 bytes of key are defferent from the second half.

    • Mustafa Moripek

      Hi Ali,
      changing the key settings is independend from
      type of the key.If the configuration changeable bit
      of the current keysettings is set you can change
      the keysettings after successfully authentication
      with the master key.
      Mustafa

      • Ali

        Hi mustafa
        thanks for reply
        My question was about encryption
        because as I saied when the first 8 byte of key are equales to second half I should use single des dycryption but when they are diferrent I try single des and 3des but in both mode I received 91 1e.How can I fixed it?

  • Chiase

    Hi all,

    How to change PICC Master Key AES?

    Best reagrds,
    Chiase

  • Ali

    Hi mustafa
    thanks for reply
    My question was about encryption
    because as I saied when the first 8 byte of key are equales to second half I should use single des dycryption but when they are diferrent I try single des and 3des but in both mode I received 91 1e.How can I fixed it?

  • Ali

    Hi is anybody here?

  • Theophile

    Hello,

    I’ve read several time most of the comments of this blog, but I still have a problem for changing PICC default master key. I have checked with NXP example, and I am almost sure that CRC16 computation and session key computation is correct.

    So, I’m trying to change the PICC master key, after select PICC app with command 5A 00 00 00. I authenticate using TDES native mode and key 00 (0A 00).
    I successfully authenticate, and get a correct encrypted randA value from the PICC.
    The problem is, when I try to change key using command C4 00, I get an integrity error (0x1E).
    I have some doubt about the manner of using IV in the Decryption process.
    Should it be reset to zero after each command (for TDES native mode), or should we keep its value after authentication for encryption of change key command ? And do we use different IV for sending and receiving (I know the xor operation is not performed at the same time).

    I repeat, when I use NXP example values, I get the same messages. Maybe the problem comes from the manner of using the session key, because NXP example use a 16 byte one, and I use a 8 bytes one as I authenticated with default key (0x00 8-times)

    Any help will be really enjoyed, I have already several days on this problem, I will get mad !

    Theophile

    • Theophile

      Problem solved: I was using wrong data instead of randB to compute the session key, that’s why it worked when I put data from the NXP’s examples but not with real messages from reader.

  • mileaux

    Hey All,

    I’m facing problems when I try to read the file settings from a value while authenticated in AES.

    My exact problem is that my CMAC calculation goes wrong. For every other command the CMAC calculation is fine.

    Did anyone faced this problem?

    The command is:

    GetFileSettings( fileNo )

    CMD F5

    Kind regards

  • darylhurst

    Hi,

    I’ve successfully changed the PICC master key from all zeroes to 00112233445566778899AABBCCDDEEFF, this is therefore now a standard rather TDES key rather than a native TDES key.

    Now I can authenticate successfully using TDES standard mode with INS 1A but I can’t change the key again without getting a 1E error.

    I’ve got the NXP documentation under NDA however this doesn’t explain clearly how to do ChangeKey using standard TDES, it explains it for native TDES and AES.

    Does anyone know what the differences are for changing a standard TDES key to another standard TDES key?

    Kind Regards,

    Daryl.

    • mileaux

      Hi Daryl,

      if you have access to the NDA documents, ask NXP to hand you out the Application Notes. There you can find examples for key changes in every mode.

      Kind regards

      • darylhurst

        Hi,

        Thanks for the response, I have the document I think you’re refer to (AN094531 DESFire – Features & Hints).

        Pages 68 & 69 shows ChangeKey in Native TDES mode (authentication code 0x0A), pages 70 & 71 shows ChangeKey in AES mode (authentication code 0xAA), there is no example of ChangeKey for Standard TDES mode (authentication code 0x1A).

        Kind Regards,

        Daryl.

      • mileaux

        Hey,

        I have the AN094534 and on page 69 and 70 I can see the apdu structure for the TDES Native, TDES Standard 16-Byte, 3KTDES and AES.

        Did you check your CRC calculation? Sometimes there is a problem with the endianess and your CRC will be backwards. Also you could check the exclusive or of the keys and the padding if needed.

        Kind regards

      • darylhurst

        Hi,

        I may have outdated documentation, my documents are dated 02 Oct 2008 so they’re pretty old.

        But just be absolutely clear you can see examples of TDES Native, TDES Standard and 3KTDES and AES all specifically in relation to the ChangeKey command? My document doesn’t show TDES Standard or 3KTDES, it does talk about these elsewhere in the document but just doesn’t have examples for ChangeKey and therefore leaves it up to the reader to try and guess the implementation!

        My CRC calculations are correct as I’m using them elsewhere without issue and have successfully used them to change the master key using Native TDES authentication. The other odd thing I notice is that after authenticating using Native TDES and then changing the card master key e.g. from all 00000000000000000000000000000000 to FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF I can then only re-authenticate with the new key using TDES standard authentication, trying to use Native TDES just throws the usual 1E error. Is it that once a key has been changed using Native TDES it automatically swaps to Standard TDES for security reasons, if so is this feature documented?

        I’ve emailed NXP for updated documentation, that may answer all my questions – I hope!

        Kind Regards,

        Daryl.

  • mileaux

    Hi,

    i have the full examples for change key command in native TDES, change key from standard TDES to AES and change key in AES mode. In addition, there is also a chart with the structure of the change key apdu for every mode. With this chart and one of the examples I managed to change the keys successfuly.

    Do you get 1E when you try to authenticate? Normally you should get AE when the authentification fails. 1E is the error for CMAC, CRC and logic failure. Logic failure are those things like “OldKey XOR NewKey” and annexion of CRCs with padding. I had a lot of trouble on the beginning at this point due to the fact, that there are two cases for changing keys.

    “Is it that once a key has been changed using Native TDES it automatically swaps to Standard TDES for security reasons”
    – I’m not sure. I switched my cryption to AES. However in my AN I can see it in chapter 9.1.1.1 changing card master key, that the change of card master goes to 16 and 24 Byte keys ind TDES and 128 Bit keys AES. So you could be right with your guess.

    Sorry for taking so long. Had a day off yesterday 😉

    Kind regards

    • darylhurst

      Hi Mileaux,

      I’ve resigned myself to wait on NXP for updated documentation, I think there are gaps in the details I currently have.
      For the time being I’m managing to progress my current work albeit with gaps in my understanding which is annoying as I hate not fully understanding the whole workings of DESFire.

      Thanks for your feedback so far, you’ve been most helpful. Do you have any other pointers for resources/help on DESFire, I’ve found the NXP site difficult to find real information and I only came across this site by accident when Googling.

      Kind Regard,

      Daryl.

  • wdtech

    Hi all,

    I would be appreciated if any one could let me know how to change the key version (parity bit of the DES key).

    I have successfully issued the “ChangeKey” APDU command with the following structure:

    90 C4 00 00 19 00 + 3DES (packed cryptogram)
    packed cryptogram = 16 byte New Key + 2 byte CRC16 + 6 byte padding

    The question is that where (or how) should I put the key version data in the packed cryptogram?

    Thanks and regards,
    Jim

  • Franz

    Hi,

    i try to change the masterkey from AES to AES, but i dosn’t work. Please see my protokoll:

    Authentication AES successful.
    AuthenticationInformation{key=00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF,rndA=C0 AC 92 3F 19 71 76 A2 FD 7E 37 47 35 08 3B AE,rndBE=91 EA 63 DF 76 9D E5 AB D7 D9 89 B2 AA 89 9B B4,rndB=7F 60 2D 3A F2 7E DA 96 39 CC 08 65 5B D0 AD B7}
    Changing AESkey to AESkey.
    keynumber: 0
    key: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
    keyversion: 0
    newkey: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    newkeycrc32_1p: C4 00 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 00
    newkeycrc32_1: 67 32 5C 83
    newkeycrc32_2: 13 44 B4 AA
    newkeyCommand: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 67 32 5C 83 13 44 B4 AA 00 00 00 00 00 00 00
    sessionkey: C0 AC 92 3F 7F 60 2D 3A 35 08 3B AE 5B D0 AD B7
    block1: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    block2: 00 67 32 5C 83 13 44 B4 AA 00 00 00 00 00 00 00
    block1Decrypt: 96 4E 6F 4E B0 FE 9F 89 CD B5 0A B5 D9 21 02 60
    block2XOR: 96 29 5D 12 33 ED DB 3D 67 B5 0A B5 D9 21 02 60
    block2Decrypt: 00 BC 9E 36 A4 F2 FB E7 13 EB D5 87 74 C0 70 6B
    COMMAND SEND: 90 C4 00 00 20 96 4E 6F 4E B0 FE 9F 89 CD B5 0A B5 D9 21 02 60 00 BC 9E 36 A4 F2 FB E7 13 EB D5 87 74 C0 70 6B 00
    COMMAND RETURN: 91 7E

    I try’d a lot, but no success. Please help.

    Thanks and regards,
    Franz

    • teguhblitzkrieg

      hi franz , 7E means length error. for change from aes key you should build with following commad C4+keyno+aes_enc(keynum+crc32+padding) wich aes_enc is 32 bytes length not 24.

      but Unfortunately , I’m still facing the problem, i always get 0x1E (integrity error)

  • Franz

    Hi,
    i played around with key diversifications as described in AN10922.
    It’s working but i don’t know where to get the System Identifier??

    Thanks
    Franz

  • senthilkumar2185

    i am having blank smart how to create AID and read and write file.please reply for me i have mifare desfire card

  • Anish Jhaveri

    Hi,

    Can anyone help me with the process of AES CMAC Calculation? Also if you have a source in .Net to help, it would be great. Thanks.

  • Sergio

    Hi!
    I’m just newbie to communicate with DESfire, and I hope somebody can help me with authentication.
    I read all comments, debug my code a lot but cannot find mistake. I’ll put my actions here, please have a look and help me:

    0) I work through Android SDK’s IsoTag class.
    1) I make connect and send auth request: isoTag.transceive(new byte[]{(byte)0x0A,(byte)0x00});
    2) Tag responses me:
    randB = 0xB0, 0xD1, 0x55, 0xFD, 0xE8, 0x62, 0x8B, 0x5C (1st byte AF already filtered)
    3) Decrypt randB in normal mode:
    decryptedRandB = 0x85, 0xAB, 0xC6, 0x55, 0x2F, 0x1E, 0x41, 0xF2
    4) Generate randA (const value now):
    randA = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
    5) Make second Array with 0-7bytes from randA and 8-15bytes shifted B:
    arrayTwo = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xAB, 0xC6, 0x55, 0x2F, 0x1E, 0x41, 0xF2, 0x85
    6) DECRYPT it in SEND MODE (XOR before DES):
    decryptedArrayTwo = 0x49, 0x1E, 0x89, 0x0D, 0xE9, 0xAC, 0xE9, 0x32, 0x89, 0xC6, 0xEE, 0x96, 0x60, 0xDD, 0x06, 0x9C
    7) Send it and get response:
    answer = 0xAE

    May be error in my cipher class, cause I wrote it by myself. Check it, please.

    My key is all ’00’
    in 6) 1st InitialVector is all ’00’, 2nd InitialVector (for B’ block) is E(randA)
    part of code for it:
    block = doXORBytes(block, iv);
    byte[] res = cipherBlock(block, subKeys, “decrypt”);
    iv = res;
    baos.write(res);

    Thanks a lot!

    PS: Sorry for my bad English.

    • Mustafa Moripek

      Hi Sergio,
      I have checked your data they seem to be O.K
      May be the issue is in the tags you are using.
      Mustafa

      • Sergio

        Thank you so much, Mustafa!
        I think little more time, and have two assumpions:
        1) My tag chip is DESfire ev1, may be it has another algorithm?
        2) Can producter change tags master key? Cause I didn’t do it for sure. My tag is Samsung Tectiles, I bought it to study work with DESFire, but their native app works with it like a simple tag (through NDEF). It seems to be so, but I can’t understand reasons.
        Please, express your opinion.
        Thanks a lot!

  • Mustafa Moripek

    Hi Sergio
    Desfire EV1 has the same DES algorithm.
    Sure,the producer can change the key,
    but in this case they should deliver the key.
    Otherwise you can never authenticate.
    Try to get an NXP Desfire tag.
    Mustafa

    • Sergio

      Hi Mustafa
      Really Samsung changed the key, but don’t tell me cause ‘Our production made for special tasks that dont need it’. Then I don’t understand why they use DESfire, seems their engineers made wrong choise.
      I’ll try to get clear tag.
      Thanks a lot, you save hours of my time!
      Sergio

  • teguhblitzkrieg

    hi mustafa, i need your help.

    i have changed PICC master key (AID = 00 00 00 ) from des to aes
    with command :
    C4 + 80 + TDESDec (theKey + crc16 + padding)

    but i cant change back from AES into des and i always get result 0x1E,

    here is the command :

    C4 + 00 + aes_enc (theKey + crc32 + padding)

    thank you and best regards

    • Mustafa Moripek

      Hi Teguh,
      here is the correct command:
      C4+00(Key No.)+NewKey+Keyversion(00)+CRC32+padding
      CRC32 of:cmd+Key No.+New Key+Key Version
      AES encryption of: New Key+Key Version + CRC32+padding
      Mustafa

  • ahmad edi saputra

    hi, would somebody tell me about DES?

  • Developer

    Hi Mustafa,
    Thanks for this blog, It provides a lot of information. Can you please provide how to change AES key in Desfire card, I am facing lot of problems.

    Thanks

  • Mustafa Moripek

    Hi Developer,
    what kind of problems you are facing of.Can you
    speciy them.Do you want to change from DES to AES
    or do you want to change only the key and not
    the crypto algorythm?
    Mustafa

    • Developer

      Hi Mustafa,
      Sorry for the delay, I went for vacation. I haven’t check post. Please try to help me I have tried a lot of options.
      Here I am trying to change AES key to AES key only, please find the steps below
      1. Generating Session key
      rndA(part1) +rndB(part1) +rndA(part2) +rndB(part2)
      2. generating CRC32 over : Cmd(C4) + Key No. +New Key +
      New Key Version
      Here can you please explain what is new key version?
      here I build that
      c4(cmd) + 00(Key no) + 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff +00(New key version)
      CRC32 Output is :83 5C 32 67
      3. Encrypt with AES (key is session key) data is (total 32 bytes data) :00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff + 00(new key version) + CRC32 output + padding
      4. Final data I am sending : c4(cmd)+ key number + AES output

      Is is giving output as : 91 1e

      I am waiting for your reply.

      Thanks
      kumar

  • John Kerry

    Hello Everyone,

    I am using Mifare Desfire EV1(MF31CD21) type 4 tag. I have to implement authentication mechanism using Mifare Desfire tag. Is above explain commands is same for this tag also. Can anybody tell list of commands and steps to follow for authentication.

    Kerry

  • Developer

    Hi Mustafa,
    Sorry for the delay, I went for vacation. I haven’t check post. Please try to help me I have tried a lot of options.
    Here I am trying to change AES key to AES key only, please find the steps below
    1. Generating Session key
    rndA(part1) +rndB(part1) +rndA(part2) +rndB(part2)
    2. generating CRC32 over : Cmd(C4) + Key No. +New Key +
    New Key Version
    Here can you please explain what is new key version?
    here I build that
    c4(cmd) + 00(Key no) + 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff +00(New key version)
    CRC32 Output is :83 5C 32 67
    3. Encrypt with AES (key is session key) data is (total 32 bytes data) :00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff + 00(new key version) + CRC32 output + padding
    4. Final data I am sending : c4(cmd)+ key number + AES output

    Is is giving output as : 91 1e

    • Mustafa Moripek

      Hi Developer,
      Error code 1E means integrity error which you get
      when CRC is not correct.I have checked your CRC32 and
      it is OK.That means your AES encryption is not correct
      so the card gets not the right CRC32.
      Write whole log (communication with the card) so
      I can check your AES algorithm too.
      Mustafa

      • Developer

        Hi Mustafa,
        Thanks for your replay, I will mention all commands that I sent to card

        I have completed Authentication using AES key, Please find the below steps
        Please make me correct if i am doing wrong

        1. Send 0xAA
        [90 AA 00 00 01 00 00]

        2. Receive Encrypted(RndB) from PICC (16bytes)
        [2F 13 63 36 31 B6 CB 5A 4E F6 C8 B1 7C 80 BF 35]

        3. Decrypt Using AES( key 0 key value is 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
        [B8 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE]

        4. Rotate Left (Left Shift) RndB producing RndB’
        [62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8]

        5. Generate RndA
        [00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF]

        6. Encrypt(RndA+RndB’) by means encrypt(00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8)
        [C8 A3 31 FF 8E DD 3D B1 75 E1 54 5D BE FB 76 0B 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8]

        7. Send APDU (Data = RndA+RndB’)
        [90 AF 00 00 20 C8 A3 31 FF 8E DD 3D B1 75 E1 54 5D BE FB 76 0B 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8 00]

        8. Session key
        [00 11 22 33 B8 62 25 D1 CC DD EE FF 26 4C AD BE]

        9. Here old key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 and new key =00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff

        10. Generating CRC32 over : Cmd(C4) + Key No. +New Key +New Key Version
        here I build that
        c4(cmd) + 00(Key no) + 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff +00(New key version)

        CRC32 Output is :83 5C 32 67

        11. Encrypt with AES (key is session key) and IV (00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) is data is (total 32 bytes data) :00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff + 00(new key version) + CRC32 output + padding
        [5A FF C0 C1 8F BC 61 E0 01 13 43 21 C5 78 18 32 F5 E3 73 04 9F 8E 22 E5 8F 49 42 69 D5 37 D6 AC]

        12. Sending final command is
        [90 C4 00 00 21 00 5A FF C0 C1 8F BC 61 E0 01 13 43 21 C5 78 18 32 F5 E3 73 04 9F 8E 22 E5 8F 49 42 69 D5 37 D6 AC 00]
        [91 1e]

        here I am having doubt about what is new key version is doing wrong

        Thanks & Regards
        kumar

  • kerry

    Dear Mustafa,

    I have gone through Mifare Desfire Specs and libfreefare source code, there is three type of crypto to do authentication( AES, DES/3DES and 3K3DES.

    Do you have any documents related to implementation of Mifare Desfire authentication process or Set off commands for authentication

    Thanks & Regards,
    kerry

    • Mustafa Moripek

      Hi Kerry,
      There are two documents (ds225832,AN0945)
      which you can get from NXP after signing a
      nondisclosure agreement.Please contact NXP
      to get the documents.
      Mustafa

      • Kerry

        Dear Mustafa,

        Thanks for the reply. I am newbie in Mifare Desfire tag. Could you please guide me to implement authentication mechanism usind Mifare Desfire EV1 tag.

        Thnaks
        Kerry

  • Mustafa Moripek

    High Kerry,
    here the scheme for authentication procedure:

    R:Request (Reader -> Card)
    A:Answer (Card -> Reader)

    R : 0X0A (Command) 0X00 (Key Number)
    A : Either Error Code or 0XAF plus 8 Byte
    (encrypted Random B)
    R : 0XAF plus 16 Bytes ( decrypted Random A +
    Random B’)
    To build B’ you have to decrypt the 8 bytes
    coming from the card and to shift one
    byte to left.The first byte becomes last byte.
    A : Either Error Code or 0X00 (success)
    plus 8 bytes (encrypted Random A’)
    Now you build The session key as follows:
    First half of Random A + First half of Random

    Mustafa

    • Kerry

      Hello Mustafa,
      Thanks for the reply.
      Before start the authentication process we have to select the application. To select the application shall i send “0x00, 0xA4, 0x04, 0x00, 0x07 , 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01, 0x00” this command?.
      After select the application we have to send authentication command with key number.
      Is this correct process?

      Kerry

  • Mustafa Moripek

    Hi Kerry,
    the application select command 0X5A plus three byte
    Application ID.After sending this and getting the answer
    0X00 (success) you start with authentication procedure.
    Mustafa

    • Kerry

      Dear Mustafa,

      1) R: 90 5A 00 00 03 00 00 00 00 (Select application 0x000000)…
      A: 91 00
      2) 90 0a 00 00 01 00 00
      Is above command is correct to start authentication?

      I have one doubt, in above authentication command data is 1 byte.
      i.e Key = 0x00.

      Kerry

    • Kerry

      Hello Mustafa,

      1) R: 90 5A 00 00 03 00 00 00 00 (Select application 0x000000)…
      A: 91 00
      In above command i am sending AID=00 00 00 i.e. Master but when i am trying to select Application 1 using
      R: 90 5A 00 00 03 00 00 01 00 command getting below response
      A: 91 A0

      Kerry

  • Mustafa Moripek

    Hi Kerry,
    you have received error code 0XA0 because
    you haven’t created any application.And that
    error code means application not found.
    You do better if you get the datasheet and
    application manual I have mentioned previously.
    Mustafa

    • Kerry

      Hello Mustafa,

      1) R: 90 5A 00 00 03 00 00 00 00 (Select application 0x000000)…
      A: 91 00
      2) R: 0x90, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00
      A: E4 05 38 55 F8 D9 0D 3A 91 AF
      The above eight bytes indicates RndB which i received from PICC.

      Now i have to do deciphering operation on the received RndB to retrieves RndB. and obviously the key should be same for the prevvious enciphering by the PICC.

      I have some doubts,
      1) Since i have used Master Key so key should be 00 00 00 00 00 00 00 00 ???
      2) for deciphering what i should use DES or 3DES??

      Kerry

    • John Kerry

      Hello Mustafa,

      1. Send Authenticate to PICC
      [0x90, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00]

      2. PICC respond with Encrypted RndB’
      [FA 06 91 7B 86 5A F3 4C]

      3. Now decrypt RndB using DES (uses default key all 0’s)

      4. After decrypt, Left Shift RndB (Rotate First Byte to the End) producing RndB’

      5. Generate RndA (random byte[8])

      6. XOR RndA and IV (using iv = all zeroes, since Initial vector is 0’s so got same result after doing XOR operation as RndA)

      7. Decrypt RndA using “DES Decrypt algorithm” using key as All 0’s.

      8. XOR result of step #7 with RndB’

      9. Decrypt result of step #8 using “DES Decrypt algorithm” using key as all 0’s.

      10. Concat result of step #7 and #9 (DecryptedRndA + DecryptedRndB’) and send it to PICC.

      Is my understanding are correct or need to modify anything.
      I have doubts on steps 7 and 9 whether i have to do decrypt or encrypt using which key. Could you please explain steps 7 and 9.

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        your steps are correct.If the cards key is not
        changed then you use the default key which
        is all zeroes.You have to DES decrypt because
        PCD always decrypt and PICC always encrypt.
        Mustafa

    • Kerry

      Hello Mustafa,

      Thanks for the support.

      I have some question
      1) How i can check the Card key has changed or not?
      2) how i can get the Card Key value?
      3) How i can change the Master Key value?

      I have followed the same steps as mentioned above but when i send (RndA + RndB’) (Command (0xAF)) , i am getting 0x91 0xAE, which means AUTHENTICATION_ERROR.
      What i am doing wrong?

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        you can not check the Card key.
        If the card is a virgin card the key is all zeroes.
        Otherwise if you don’t know the key you cannot
        authenticate.
        Mustafa

    • Kerry

      Hello Mustafa,

      Thanks for the reply.

      Can i Change Master card key ? So i will use that card key only for my authentication process.

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        You can change the master card key if you know it.
        For changing any key you have first to autneticate either
        with master key or with change key key.
        Mustafa

    • Kerry

      Hello Mustafa,

      If i use new card then Master Key would be 0’s. Could you please tell me the process of changing Master key or any other Application Key if i know the key

      Kerry

    • Kerry

      Hello Mustafa,

      I have used new Mifare desfire tag but still getting AE error.

      i am following below steps:
      1) A – > 90 5A 00 00 03 00 00 00 00
      R 0x90, 0x0A, 0x00, 0x00, 0x01, 0x00, 0x00
      R <- 03 98 A2 E2 6A F2 F6 18 91 AF (RndB)

      3) Decrypt RndB using DES algorithm using Master key as All 0's

      4) Rotate RndB left (RndB')

      5) XOR RndA and IV (using iv = all zeroes)

      6) Decrypt results of step 5 using Master key as All 0's

      7) XOR result of step 6 with RndB'

      8) Decrypt result of step 7 using Master key as All 0's

      9) concatenate result of step 6 and step 8

      10) send it to PICC (0x90, 0xAF, 0x00, 0x00, 0x10, 16 bytes value, 0x00)

      Getting 0xAE value.

      i have one doubts every time i send Authentication command getting New RndB value, is it normal behavior.

      Please help me to solve this issue

      Kerry

    • Kerry

      Dear Mustafa,

      Thank you so much for your support and I really appreciate .
      Now its working 🙂 and I am able to get Session Key using Master key as All 0’s.

      Now i want to change the Master Key. Could you please tell me the steps to be followed to change the master key and do authentication using that key.

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        I am pleased to hear that you could authenticate
        successfully.
        To change the key you have to proceed as follows:
        C4 (cmd) + Key No.+ NewKey + CRC16 of NewKey +
        Padding to 24 bytes.
        Bytes starting from NewKey till the and of padding
        is desciphered in send mode using 3DES session key.

    • John Kerry

      Hello Mustafa,

      I am little bit confused, I have completed mutual authentication (Both RndA and RndB were compared on its own source and were verified). Now I have to change the Master Key.

      what would be the Session key?
      1) RndA(1st half) + RndB(1st half) or
      RndA 1st half + RndB 1st half + RndA 2nd half + RndB 2nd half

      I have used Master key as eight bytes(i.e All 0’s), So New Key should be Eight bytes only?

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        if the first half(8 bytes) is equal to second half
        (8 bytes) then the session key is RndA (1. half)+
        RndB (2. half).
        If they are different the session key is
        RndA 1st half + RndB 1st half + RndA 2nd half +
        RndB 2nd half.In your case the key is all
        zeroes which means the fisrt half is equal to
        second half your session key is RndA (1. half)+
        RndB (2. half).
        Mustafa

    • John Kerry

      Hello Mustafa

      Thanks for the reply.
      So Now i can send Change Key command as below:
      C4 (cmd) + Key No.(00) + NewKey (11 22 33 44 55 66 77 88) + CRC16 of NewKey (xx xx ) + (00 00 00 00 00 00)
      Padding to 24 bytes.

      My doubts is new key should be 8 bytes or 16 bytes?
      In Change Key Command Key version is required ?

      Kerry

    • Kerry

      Hello Mustafa,

      Example: New Key = 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
      So My Block Data would be like below:
      1. Block 00 01 02 03 04 05 06 07
      2. Block 08 09 0A 0B 0C 0D 0E 0F
      3. Block 77 F5 00 00 00 00 00 00

      Step 1: BLOCK1 XOR IV (All 0’s)
      Step 2 : Result of Step 1 Decrypt using Session Key ( 1st half of RndA + ( 1st Half of RndB)
      Step 3 : Result of Step 2 XOR with Block 2 data
      Step 4 : Result of Step 3 Decrypt using Session Key
      Step 5: Result of Step 4 XOR with Block 3 data
      Step 6: Result of Step 5 decrypt using session key
      Final Command :
      C4 + Key No.(00) + Step 2 + Step 4 + Step 6 + 00

      Is my understanding are correct?
      Key version is required or not in Final Command?

      Kerry

    • John Kerry

      Dear Mustafa,

      Thank you so much for your support.
      I am able to Change the Master Key and authentication using that key. 🙂

      Kerry

    • Kerry

      Hello Mustafa,

      Thank so much for your support. I am successfully able to authenticate Mifare desfire tag and able to change key too.

      Now I am trying to implement this mechanism on android phone as card emulation mode. So that android phone will be acts as type 4 tag and can do same authentication process as Mifare desfire tag is doing.

      I have one apps which acts as type 4 tag and my reader is able to detect android phone and even able to read and write with that apps using APDU commands.

      My problem is normal Mifare desfire tag I write some key which cannot read it back. But I cannot used same mechanism in android apps bcoz other can read the key.

      Is there any mechanism in Android apps so that if I write key other cannot read it.

      Could you please help me.

      Kerry

      • Mustafa Moripek

        Hi Kerry,
        Sorry I have no experience with Android phones
        therefore I can not help you.If you find the solution
        publish it so the others are informed too.
        Good luck.
        Mustafa

  • Developer

    Hi Mustafa,
    Thanks for your replay, I will mention all commands that I sent to card

    I have completed Authentication using AES key, Please find the below steps
    Please make me correct if i am doing wrong

    I am waiting for your reply, please help me here

    1. Send 0xAA
    [90 AA 00 00 01 00 00]

    2. Receive Encrypted(RndB) from PICC (16bytes)
    [2F 13 63 36 31 B6 CB 5A 4E F6 C8 B1 7C 80 BF 35]

    3. Decrypt Using AES( key 0 key value is 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
    [B8 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE]

    4. Rotate Left (Left Shift) RndB producing RndB’
    [62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8]

    5. Generate RndA
    [00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF]

    6. Encrypt(RndA+RndB’) by means encrypt(00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8)
    [C8 A3 31 FF 8E DD 3D B1 75 E1 54 5D BE FB 76 0B 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8]

    7. Send APDU (Data = RndA+RndB’)
    [90 AF 00 00 20 C8 A3 31 FF 8E DD 3D B1 75 E1 54 5D BE FB 76 0B 62 25 D1 8E DE 9C 19 E0 F8 04 9B 26 4C AD BE B8 00]

    8. Session key
    [00 11 22 33 B8 62 25 D1 CC DD EE FF 26 4C AD BE]

    9. Here old key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 and new key =00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff

    10. Generating CRC32 over : Cmd(C4) + Key No. +New Key +New Key Version
    here I build that
    c4(cmd) + 00(Key no) + 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff +00(New key version)

    CRC32 Output is :83 5C 32 67

    11. Encrypt with AES (key is session key) and IV (00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00) is data is (total 32 bytes data) :00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff + 00(new key version) + CRC32 output + padding
    [5A FF C0 C1 8F BC 61 E0 01 13 43 21 C5 78 18 32 F5 E3 73 04 9F 8E 22 E5 8F 49 42 69 D5 37 D6 AC]

    12. Sending final command is
    [90 C4 00 00 21 00 5A FF C0 C1 8F BC 61 E0 01 13 43 21 C5 78 18 32 F5 E3 73 04 9F 8E 22 E5 8F 49 42 69 D5 37 D6 AC 00]
    [91 1e]

    here I am having doubt about what is new key version is doing wrong

    Thanks & Regards
    kumar

    • Mustafa Moripek

      Hi Kumar,
      are you sure that you have authenticated successfully.
      What answer did you receive to your request APDU.
      Your APDU is not correct.When sending more than
      16 bytes to the card you have to use CBC send mode.
      That means:
      Your start IV now is the enc(RndB) what you have received
      from the card.You XOR this with RndA (2F 02 41 05 75 E3
      AD 2D C6 6F 62 0A B0 5D 51 CA) and encipher it
      (EE BE D6 E1 66 35 5F DA D4 7C 27 BC 53 23 13 86).
      This is your result IV and you XOR it with your RndB’
      ( 8C 9B 07 6F B8 A9 46 3A 2C 78 BC 9A 1F 8E AD 3E)
      and encipher it (1D 67 31 22 B7 D3 4C A9 D7 BE 3A 02 11
      7F EB 22).
      Your APDU should look like :
      90 AF 00 00 EE BE D6 E1 66 35 5F DA D4 7C 27 BC 53
      23 13 86 1D 67 31 22 B7 D3 4C A9 D7 BE 3A 02 11 7F
      EB 22 00
      Therfor it is impossible that you have received success
      answer.
      Mustafa

      • kumar

        Hi Mustafa,
        Thanks for your help.
        Now I am able to change master key successfully, it is not a problem. Then i struck in one place for format card. Can you please help here I am doing this since long time.
        Can you please help out here

        Thanks & Regards
        kumar

  • Mustafa Moripek

    Hi Kumar,
    if you specify the problem I can try
    to help.The command for format PICC
    is 0XFC.No parameters are passed with
    this command.If this command is not
    disabled with SetConfiguration command
    then you can format the PICC.
    Mustafa

  • kumar

    Hi Mustafa,
    Thanks for your replay,
    I had authentication via below steps,

    1. Send 0xAA
    [90 AA 00 00 01 00 00]

    2. Receive Encrypted(RndB) from PICC (16bytes)
    [46 ED F9 20 9C 65 C7 F7 F4 36 C0 D1 1B 08 65 F0]

    3. Decrypt Using AES with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
    [1B BB 10 45 40 85 1C 0D 48 89 36 01 CB 8A 84 1F]

    4. Rotate Left (Left Shift) RndB producing RndB’
    [BB 10 45 40 85 1C 0D 48 89 36 01 CB 8A 84 1F 1B]

    5. Generate RndA
    [BE 4C 2F 53 60 CF 6B F8 BE 52 6D 2B 0C 38 B7 20]

    6. Encrypted RndA using IV = #step2 (Encrypted RndB received from PICC)
    [DF 96 54 C2 29 24 C8 D6 A4 36 81 2D 8C B7 0C 01]

    7. Encrypt RndB’ using IV = #step6 (Encrypted RndA)
    [57 23 72 6B 62 73 2F E7 ED AB 92 C4 DF AA C0 3A]

    8. Send APDU (Data = RndA+RndB’)
    [90 AF 00 00 20 DF 96 54 C2 29 24 C8 D6 A4 36 81 2D 8C B7 0C 01 57 23 72 6B 62 73 2F E7 ED AB 92 C4 DF AA C0 3A 00]

    9. Received Encrypted RndA’ from PICC
    [27 4B 9A E8 8A BA 3E BD 40 52 F2 0A A0 1A BE 70]

    10. Decrypted RndA’ from PICC using IV = #step7 (Encrypted Left Shifted RndB’)
    [4C 2F 53 60 CF 6B F8 BE 52 6D 2B 0C 38 B7 20 BE]

    11. Rotate Left Current RndA for comparison
    [4C 2F 53 60 CF 6B F8 BE 52 6D 2B 0C 38 B7 20 BE]

    12. Compare Both = OK
    [4C 2F 53 60 CF 6B F8 BE 52 6D 2B 0C 38 B7 20 BE] // Received
    !=
    [4C 2F 53 60 CF 6B F8 BE 52 6D 2B 0C 38 B7 20 BE] // Current Rotated RndA

    13. Generate Session Key
    [BE 4C 2F 53 1B BB 10 45 0C 38 B7 20 CB 8A 84 1F]

    It is giving “9100” for authentication.

    Then i tryed for format card using this command 90 FC 00 00 00
    it is giving “91AE”

    Can you please help out here.

    Advanced thanks for your help

    Thanks & regards
    kumar

  • Mustafa Moripek

    Hi Kumar,
    after successfully authentication the
    format command should also success.
    The only thing I can say is that in the
    APDU command the LE is missing.
    Try to send format command as follows:
    90 FC 00 00 00 00 (one double zero more)
    Mustafa

  • kumar

    Hi Mustafa,
    Thanks for your great help.
    I even tryed with “90 FC 00 00 00 00” command, but still i am getting “91AE” error only.
    can you please help me out here.

    Thanks & Regards
    kumar

  • Mustafa Moripek

    Hi Kumar,
    error code AE means that the current authentication
    does not allow the requested command.The format
    command always requires a preceding
    authentication with the PICC master key.Therefore
    be sure you are using the PICC master key.If you
    first select an application than select AID 00 so
    you are on PICC level.If you select an application
    and authenticate with key number 00 you are
    not autenticating with PICC master key.
    Mustafa

  • Omid

    Hi ridix,

    I’m working with DESFIRE EV1 and I want to use fully encryption method for reading file. I can authenticate the application successfully by using 3DES and generate CMAC as new IV for decrypting response, but I face with problems. I think its related to calculating CMAC. The following is a sample of my procedure:

    Sessionkey = 01234567F5FAADE189abcdef0243AFB5
    command= BD 00 00 00 00 03 00 00
    Key1= 43ba5d0b5d4af16a
    Key2= 8774BA16BA95E2D4

    generated CMAC= BD55F2C29C85FC3F

    card response = 22 4E D0 92 07 FD 84 92

    I decrypt the card response with session key and CMAC as IV but it is not correct. Could you please help me solve this problem?

    Best Regards,

    Omid

  • Sentinel

    Hi ridix,
    I want to change the card mode DES to AES mode.
    Logged exchange cards and readers:
    1.Send: [03 0A 00]
    2.Received: [03 AF 66 12 F8 D0 91 6E 45 90]
    ENCRYPT RndB = 32 f4 30 06 b3 0d ab 5d
    ROTATE RndB’ = f4 30 06 b3 0d ab 5d 32
    RndA = bd 4d 00 00 0a 21 00 00
    3.Send: [02 AF 9D B9 C9 5A D2 8E 4A F2 CA 48 9E CE 3B F4 2F1B]
    4.Received:[02 00 CB 8A D2 B5 56 4D E3 E6]
    RndA’ =4d 00 00 0a 21 00 00 bd

    Session Key
    RndA(4)+RndB(4) =bd 4d 00 00 32 f4 30 06

    5.Send:[03 C4 80 39 3D 34 DB 64 49 E8 B4 D1 EF 20 BC D8 1B 71 CF 52 EF E3 B4 80 7E 2C 52]
    6.Received:[03 00] – OK

    ENCRYPT {39 3D 34 DB 64 49 E8 B4 D1 EF 20 BC D8 1B 71 CF 52 EF E3 B4 80 7E 2C 52} =

    00 00 00 00 00 00 00 00
    00 00 00 00 00 00 00 00
    42 63 24 00 00 00 00 00 <- 42 63 24 ?

    the first two lines – a new key for AES. which means bytes 42 63 24 ?

  • Kumar

    Hi Mustafa,
    Thanks for helping.
    If I write data to card using one reader, then if I try to write data using another reader in same card and same file and application, it is giving “919d” exception

    • Mustafa Moripek

      Hi Kumar,
      9D means current configuration or status does
      not allow the requested command.Be sure that
      both readers are configurated in the same way.
      Mustafa

  • Georges

    Hi all,

    I’m trying to switch from DES to AES but I don’t known how I can do it. I tried to authenticate me with AES auth command with all 0 key, but I have the error “AE”. Also, I tried to change key with a 16 b key but that requires a 3DES authentication and not working with AES command (0xAA)

    Please help

  • Mustafa Moripek

    Hi Georges,
    you have to authenticate in DES mode with command 0A.
    After successful authentication you can switch to AES using
    the changekey comand.On this site you can find information
    about how to make it.
    Mustafa

    • Georges

      Hi Mustafa, and thanks for your response.

      If I understand, it should be used a CRC32 instead CRC16 and CMAC instead of MAC ?
      In this case, what is the difference between MAC and CMAC ?

      Thanks

    • Georges

      Hi Mustafa,

      My change key from DES to AES work fine (C4 + 80 …) but I have another problem when i tried to authenticate me. I received the good response (AF + 16 bytes RndB), and i do all operations (I believe…) and I finally received a 0xAE error.

      My steps :

      1) Decipher RndB

      2) Calculate RndB’ with this algo (in C#) :

      var rndbprim = new byte[16];

      rndbprim[15] = randomB[0];
      for (int i = 0; i < 15; i++)
      {
      rndbprim[i] = randomB[i + 1];
      }

      3) Generate RndA (16 bytes)

      4) Create a byte array associating RndA + RndB'

      5) Decipher this association. (because desfire card can only cipher)

      (My key is actually all 0)

      Thanks

      • Georges

        Also, the changekey command from DES to AES key works only for the PICC master key. What is the procedure for others keys ?

  • Mustafa Moripek

    Hi Georges,
    I didn’t understand what the issue is.Have you been able
    to change the authent algorithm from DES to AES.
    If not write the communication log between PCD and PICC.
    You can change the key number you select from DES to AES.
    If you select key number 00 you change PICC authent mode.
    Mustafa

    • Georges

      Hi Mustafa,

      Here is my log in all authentication steps (with all 0’s key) :

      1) Response from PICC after 0xAA command :
      FF37D1D91F1A6AEFCFD0BC90205C75EA91AF

      2) Calculated RndB :
      3582337D8A829BB2D045DCCAF0C2025F

      3) Generated RndA :
      8F6FE2463F77E9E3822D77DF94BE3C08

      4) Calculated RndB’ :
      82337D8A829BB2D045DCCAF0C2025F35

      5) RndA + RndB’ :
      8F6FE2463F77E9E3822D77DF94BE3C0882337D8A829BB2D045DCCAF0C2025F35

      6) Ciphered datas sended to the PICC :
      2E194428334AA784387F6D1CD5FEF3587C6588F02C675AD12928BCEF47964A66

      7) PICC returned :
      91AE

      Thanks again for your help!

      • Georges

        My problem is solved. It was because in DES (or only with last versions as MF3ICD40), desfire card could only encrypt datas. Consequently, the PCD using only the decryption method. It seems that with new cards (MF3ICD41), PICC uses decryption and encryption method. Thereby, the PCD has to use decryption metyhod to decrypt received datas from PCD and encryption method to send datas to the PCD.

        Georges

  • Mustafa Moripek

    Hi Georges,
    the statement that PCD always decrypt is valid
    only for native DES algorithm.For AES mode you
    use both,encipher and decipher.
    Mustafa

  • Kumaraswamy

    Hi Mustafa,
    I saw this forms completely, it is really great and I am working on change key, Change key is working when application created with ef(keysetting1) and 83(keysetting2). here what ever the key to be change I am authenticating with same key and changing. Please find the procedure…

    CRC32 over : Cmd(C4) + Key No. +New Key + New Key Version
    AES over : New Key + New Key Version + CRC32 + Padding
    Payload : Cmd (C4) + Key No. + AES cipher data

    It is not working when I created application with 0f(keysetting1) and 83(keysetting2). here what ever the key to be change I am authenticating with master key and changing but it is giving exception ‘911e’. Please find the procedure…

    CRC32 over : Cmd(C4) + Key No. +New Key + New Key Version
    AES over : New Key + New Key Version + CRC32 + Padding
    Payload : Cmd (C4) + Key No. + AES cipher data

    Advanced thanks for help.

    Thanks & Regards
    Kumaraswamy

  • Georges

    Hi Mustafa,

    I have another problem. I explain it : with the MF3ICD40 desfire card, i could write data in a StandardDataFiles without any problem. But with a MF3ICD41, this return 0x6300.
    I have no idea about this error.

    Thanks for help

    • Georges

      It seems that this is a bug from my reader (ACR122U) because this work fine with another reader.
      But it seems that the WriteData command is different with MF3ICD41. With the MF3ICD40, Write data datas are :

      1 byte : file number
      3 bytes : offset
      3 bytes : length
      0 to 52 bytes : datas to write

      and if an additional frame is required, must be sent a 0xAF command with 0 to 59 bytes (represents datas).

      But with MF3ICD41 card, this return 0x7E length error.

  • Mustafa Moripek

    Hi Georges,
    the write data format are for both the same.
    Be sure that the communication settings are
    set for plain data, otherwise you have to add
    CRC and padding or CMAC to your payload
    to the PICC.This can cause length error.
    Mustafa

  • Georges

    Hi Mustafa,

    It’s very strange. I’m sure that the communication settings are set for plain data. But if I set the max length for the first part of datas to 47 instead of 52 and the others frame length to 54 instead of 59, this works fine.

    Also, can you confirm me that the difference between the two others communication settings is CRC for plain communication secured and CMAC instead of CRC for the fully enciphered mode ?

    Thanks

    • Georges

      Also, is it possible to change custom application (AID != 0x00) DES keys to AES keys without re-create it ?
      I known it is possible to change PICC master key to AES key using 0x80 as key number but this doesn’t work to change custom app keys. (I known it’s possible to set key settings to AES while creating app, and my question is only because i’m curious ;-))

      Thanks a lot

    • Mustafa Moripek

      Hi Georges,
      are you sure you are counting only the data?
      Where does those five bytes come from.
      There are three communication modes:Plain,Plain secured
      by MAC and fully enciphered.When using MACed mode
      you send data in plain mode but you add the MAC.For
      calculating MAC you encipher the data using TDES.And
      the 4 LSB bytes of the last enciphered block is MAC.
      And for fully enciphered mode you calculate CRC16 and
      add CRC plus padding to the data,but they are not
      calculated in 52 or 59 bytes.
      Mustafa

      • Georges

        Hi Mustafa,

        As I explained it, with my MF3ICD40 card, in plain communication, if I send 60 bytes datas, I will have to do it in several times :

        The first frame will contain the 0x3D as command and, as datas, the offset on 3 bytes, the length on 3 bytes and the datas to write with a max length of 52.

        The second frame will contain the 0xAF as additional frame command, and the datas to write with a max length of 59. In my example, the second frame will have the 8 last datas to write.

        But if my datas length is less than the max value, I don’t have to add padding bytes.

        With a MF3ICD41 (or 81) it seems that these max values are respectively 47 and 54 instead of 52 and 59, but I don’t known why.

        Have you see my last message about the ChangeKey command with AES ?

        Thanks for the time you give me. Your help is really appreciated.

  • Georges

    Hi Mustafa,

    I need your help again… and again ! I’m trying ti change key from AES to AES. I don’t known how to do it.
    I known that in DES mode, the datas length is 24. It seems with AES the length is 32 (multiple of 16). I tried to format datas like it :

    – CRC32 of the new AES key appended to the new key
    – Enciphered (this + padding of 12 zeros)

    If I have to use a CMAC, I don’t understand how to do it.

    I’m a beginner with desfire and I have begin successfull by implement these functionalities in DES mode but I don’t have any documentation for AES.

    Thanks for help

    • Mustafa Moripek

      Hi Georges,
      the change key format for AES encryption mode
      is as follows:
      C4 (cmd) + Key No. + New Key + New Key Version +
      CRC 32 (calculated on cmd+KeyNo.+NewKey+New Keyversio) +
      Padding)
      The data beginning with new key should be AES ecnciphered
      with the session key and sent in CBC send mode
      to the PICC(totally 32 bytes).
      Mustafa

      • Georges

        Hi Mustafa,

        I tried to change key with the format you give me and I have a 1E error.
        Here is my log :

        AES Authentication with all 0’s key :

        Received RndB (non-deciphered) :
        10 41 E4 23 05 A7 CB 8F DC 3B FC 77 6A F3 2B DD

        Deciphered RndB :
        3D C7 7D 82 11 E1 27 19 5C 3E 52 A2 43 B5 71 25

        RndB’ :
        C7 7D 82 11 E1 27 19 5C 3E 52 A2 43 B5 71 25 3D

        Generated RndA :
        0C E8 95 C3 EA 1C 2A 49 EF 67 AE 07 22 D5 44 75

        RndA + RndB’ :
        0C E8 95 C3 EA 1C 2A 49 EF 67 AE 07 22 D5 44 75 C7 7D 82 11 E1 27 19 5C 3E 52 A2 43 B5 71 25 3D

        Ciphered datas sended in AF command :
        DD E2 7F B8 2B F3 D1 A0 E7 CD 83 66 5F 83 4B D8 4C 85 58 0D 42 2E E3 F8 06 1B 2D 38 A4 05 14 F6

        Received datas from PICC with auth success code 0x9000 :
        0A AD 0B CA D8 0D 2C DA 8A DB 2E 21 66 29 A2 43
        (not sure that’s good ?)

        Session key :
        0C E8 95 C3 3D C7 7D 82 22 D5 44 75 43 B5 71 25

        Change key to the same key (all 0’s) :

        Datas on which to calculate CRC32 :
        C4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
        (also, for other key, I don’t known how to get key version)

        Calculated CRC :
        0A 0F 86 1B

        Datas to cipher :
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 0F 86 1B 00 00 00 00 00 00 00 00 00 00

        Ciphered datas :
        F1 4C 34 62 60 6B A1 F9 0D F5 07 BE 4E 6A 8D EF 68 C2 A0 54 81 8C 2C 9C 39 A5 74 23 25 1E 25 59

        PICC response : 0x911E

        Thanks

  • Mustafa Moripek

    Hi Georges,
    first of all you should write 80 for Key No.If you use 00 it
    means you change to DES mode.The second issue is
    the CRC32.Check your CRC32 calculation,I have got
    for your data 23 E3 F6 B5 as CRC32.You can use 00
    for new key version if you don’t make key versioning.
    Mustafa

  • Mustafa Moripek

    Hi Georges,
    I have cheked my calculations again.You are
    right,while copy pasting I made a mistake.Your
    CRC-32 calculation is correct.I have checked your
    AES cipher and decipher algoritm,they are correct
    also.The only issue is ,as you have noticed allready,
    the one 00 before CRC should come to after
    CRC.
    But as I mentioned before, if you want to go on
    with AES mode for encryption and decryption,
    you have to write 80 as Key No.
    Mustafa

  • Georges

    Hi Mustafa,

    I have always the same error. I send you my logs again with more details:

    AES key : 00 … 00

    Authentication with the PICC master key (00) :

    Ciphered RndB (received from the PICC) :
    76 A4 40 10 FE A9 DE F6 42 CE CB 0B C7 9F 1C 5C

    Deciphered RndB :
    17 26 6E C6 18 03 EE D1 23 45 FE E6 02 31 E6 FB

    RndB’:
    26 6E C6 18 03 EE D1 23 45 FE E6 02 31 E6 FB 17

    RndA (generated by the PCD):
    82 F6 C3 29 C0 00 50 07 B1 A7 5F 0B D8 37 5B CD

    RndA and RndB’ concatenation :
    82 F6 C3 29 C0 00 50 07 B1 A7 5F 0B D8 37 5B CD 26 6E C6 18 03 EE D1 23 45 FE E6 02 31 E6 FB 17

    Ciphered datas to send:
    C3 95 0F 45 1D 25 84 D8 FB 3A 52 79 E7 D2 36 D3 F5 A6 65 79 7F D6 D2 57 24 03 97 F9 CE 26 BF 1D

    Datas received from PICC with successful code :
    4B 98 54 6C BC 27 99 7E B2 E0 58 AD 3A A8 5D EE

    Session key : 82 F6 C3 29 17 26 6E C6 D8 37 5B CD 02 31 E6 FB

    Authentication OK!

    Change key :

    New AES key = 01 … 01

    CRC calculate over:
    C4 80 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 00

    CRC value:
    BC 71 57 FB

    Datas to ciphered:
    01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 00 BC 71 57 FB 00 00 00 00 00 00 00 00 00 00 00

    Ciphered datas:
    8A 6B 2D 2C 58 33 40 64 BC 8C 95 7C 5A 90 E4 B6 C1 E9 64 E9 22 AF 60 8D E4 20 A1 E6 6C 8C 1E 9C

    Datas to send (without command byte):
    80 8A 6B 2D 2C 58 33 40 64 BC 8C 95 7C 5A 90 E4 B6 C1 E9 64 E9 22 AF 60 8D E4 20 A1 E6 6C 8C 1E 9C

    Complete sent APDU buffer:
    90 C4 00 00 21 80 8A 6B 2D 2C 58 33 40 64 BC 8C 95 7C 5A 90 E4 B6 C1 E9 64 E9 22 AF 60 8D E4 20 A1 E6 6C 8C 1E 9C 00

    PICC always return 0x911E

    Thanks again…

    • Mustafa Moripek

      Hi Georges,
      I think I know the issue now.Your session key is
      wrong.In AES crypto mode you build the session key
      as follows :
      Session Key = RndA byte 0..3 + RndB byte 0..3 +
      RndA byte12..15 + RndB byte 12..15
      Try again and let me know about the result
      Mustafa

      • Mustafa Moripek

        Hi Georges ,
        your session key is O.K. I have looked to wrong
        place.And I don’t know any other issue.If
        I find out I let you know.
        Mustafa

      • Georges

        Hi Mustafa,

        Tanks for your help.
        Others informations:
        Key settings for PICC application:
        0F01

        Card type: MF3ICD41
        I get the same error with MF3ICD21 and MF3ICD81 cards.

        Georges

  • Mustafa Moripek

    Hi Georges,
    you have written key settings for PICC application.
    I have a question.Are you trying to change the same
    key you are authenticating with.If you are
    authenticating with master key and want to change
    another key than the change key format is different.
    Mustafa

    • Georges

      Hi Mustafa,

      As you can see in the authentication part, I do authentication with the key 00, so the master key (note the 0x000000 application is selected). And after that I try directly to authenticate me with the 0x80 key which indicates I use AES mode.

  • Georges

    Hi Mustafa,

    I have a question about AES authentication. I noticed that if I send a command like GetAppAIDs just after a successfull authentication, I received app AIDs and a (random ?) 8 bytes value. Do you know what are these bytes ?

    Also, my ChangeKey problem isn’t solved yet…

    • Mustafa Moripek

      Hi Georges,
      this is not a random number,it is CMAC.
      Regarding to ChangeKey problem I have a question.
      After authentication do you select an application
      and then try to change the key?
      Mustafa

      • Georges

        Hi Mustafa,

        No, I try to change the PICC master key, so I try the ChangeKey command just after authenticate command.

        Thanks

  • Kumaraswamy

    Hi Mustafa,
    I saw this forms completely, it is really great and I am working on change key, Change key is working when application created with ef(keysetting1) and 83(keysetting2). here what ever the key to be change I am authenticating with same key and changing. Please find the procedure…
    CRC32 over : Cmd(C4) + Key No. +New Key + New Key Version
    AES over : New Key + New Key Version + CRC32 + Padding
    Payload : Cmd (C4) + Key No. + AES cipher data
    It is not working when I created application with 0f(keysetting1) and 83(keysetting2). here what ever the key to be change I am authenticating with master key and changing but it is giving exception ‘911e’. Please find the procedure…
    CRC32 over : Cmd(C4) + Key No. +New Key + New Key Version
    AES over : New Key + New Key Version + CRC32 + Padding
    Payload : Cmd (C4) + Key No. + AES cipher data
    Advanced thanks for help.
    Thanks & Regards
    Kumaraswamy

  • Mustafa Moripek

    Hi Kumaraswamy,
    E means you have to authenticate with the same
    key you want to change,0 means you have to
    authenticate with application masterkey.And for
    changing a key after authenticating with a diffrent key
    the change key format is as follows:
    C4 (cmd) + Key No. + (Old Key XOR New Key) +
    New Key Version + CRC32 over(cmd+KeyNo+OldKey
    XOR New Key +New Key Version) + CRC32 over New Key
    + Padding
    Mustafa

  • Kumaraswamy

    Hi Mustafa,
    Thanks for your replay.
    Here if we forget oldkey, then is it possible to change key only with new key.

    Advanced thanks for help.
    Thanks & Regards
    Kumaraswamy

  • Farshid

    Hi,
    I have problem with sending native wrapped commands to DESFire EV1 card using Java smartcardio package. When I wrap a native command that doesnot contain any data part (like “Get Version” which is 6 bytes in wrapped mode) in an APDU object, the parse method in CommandAPDU object throws an exception:

    at javax.smartcardio.CommandAPDU.parse(CommandAPDU.java:323) java.lang.IllegalArgumentException: Invalid APDU: length=6, b1=0

    a related problem has been posted in link below but there isn’t any right to the point answer.

    http://stackoverflow.com/questions/11685959/javax-smartcardio-how-to-send-native-commands-to-desfire-card

    That’s too odd when I send a native wrapped command which contains data part like “Select PICC Application” there is’t any problem and the response is correct.
    I would greatly appreciate it if you can help me on this.

  • Georges

    Hi Mustapha,

    My previous issue is solved. It was an crypto error (bad IV).

    Also, what is the command to change file settings using AES. I can do it with DES but it doesn’t work with AES.

    Thanks

    • Mustafa Moripek

      Hi Georges,
      If the communication settings is plain,the change file settings
      command is : 5F + File No. + Com Set + Access Rights (totally
      5 Bytes).
      Otherwise :5F + File No + New enciphered settings (AES enciphered) (totally 18 Bytes)
      Before changing you have to authenticate with change access
      right key.
      Mustafa

      • Georges

        Hi Mustafa,

        Thanks for reply.
        It seems that it’s work now.

        I have a last question (I hope this is the last ;-)) :
        It’s about IV management. In my understanding, when I am authenticated, after all other commands, I have to update IV from CMAC returned by the PICC with the success status. But I don’t understand how to do it.

        Thanks

  • Georges

    Hi Mustafa,

    I tried to convert the algorithm describes here to C# : https://tools.ietf.org/html/rfc4493#appendix-A

    Now my IV is good and updated for each encryption operation, but my calculated CMAC is wrong if the default IV is not all 00.

    • Georges

      Hi,

      I solved my issue using another algorithm. It seems the issue is in the generate_subkey method. If you try the given code with the example which have a M length of 40, it doesn’t work.

      Thanks for your support Mustafa.

  • Georges

    Hi Mustafa,

    I have a question which I believe is simple. I know how to switch the PICC master key from DES to AES but I don’t know how to do the opposite (from AES to DES).

    Thanks a lot!

    • Mustafa Moripek

      Hi Georges,
      The change key command for DES is as follows:
      C4 + Key No.+ New Key + CRC16 of the New Key + Padding.
      The 7. and 6. bits of the Key Number should be 0.
      Mustafa

      • Georges

        Hi Mustafa,

        Thanks for reply but I don’t understand. I’m authenticated with AES, so I have to encrypt datas with AES algorithm ? And in this case I have a 7E or 1E error.

        Thanks

  • Mustafa Moripek

    Hi Geoges,
    sure you have to authenticate and encrypt with AES .
    Write the whole log so I can see it.
    Mustafa

    • Georges

      Hi Mustafa,

      Thanks for your support.
      Here is my log:

      AES key : 00 … 00

      Authentication with the PICC master key (00) :

      Ciphered RndB (received from the PICC) :
      03 2D BF 35 D3 F2 E0 2E 06 54 2B 71 31 69 4F D8

      Deciphered RndB :
      6B A4 28 79 EC 04 7A 88 CF 51 95 62 45 DF 31 A6

      RndB’:
      A4 28 79 EC 04 7A 88 CF 51 95 62 45 DF 31 A6 6B

      RndA (generated by the PCD):
      74 B2 5E EC AC 78 DE DB 35 3C EC A7 AD 44 4C 20

      RndA and RndB’ concatenation :
      74 B2 5E EC AC 78 DE DB 35 3C EC A7 AD 44 4C 20 A4 28 79 EC 04 7A 88 CF 51 95 62 45 DF 31 A6 6B

      Ciphered datas to send:
      51 F0 D6 0C 7F CB 67 80 39 D8 0D 51 65 69 2C 3A CF C6 9E 7A C8 AF 3C 00 40 1C 7C 08 30 1B 68 52

      Datas received from PICC with successful code :
      EA 33 A5 BE F7 52 26 4F 08 36 1F BF AF 27 CA 46

      Session key : 74 B2 5E EC 6B A4 28 79 AD 44 4C 20 45 DF 31 A6

      Authentication OK!

      Change Key to DES :

      New DES key : all 00 (length of 16 with two equals parts of 8 length)

      CRC on new key :
      37 49

      Datas to ciphered :
      00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 37 49 00 00 00 00 00 00

      Ciphered datas :
      AC 5C AE 58 EE FC 1A 03 01 25 C1 D0 0F 8D 8C 66 46 14 8A A4 6D 2C 45 1B 19 F1 6F 0F 46 7C AF 38

      Datas to send :
      00 AC 5C AE 58 EE FC 1A 03 01 25 C1 D0 0F 8D 8C 66 46 14 8A A4 6D 2C 45 1B 19 F1 6F 0F 46 7C AF 38

      Complete APDU :
      90 C4 00 AC 5C AE 58 EE FC 1A 03 01 25 C1 D0 0F 8D 8C 66 46 14 8A A4 6D 2C 45 1B 19 F1 6F 0F 46 7C AF 38

      PICC returns 0x1E error

      • Mustafa Moripek

        Hi Georges,
        as you have authenticated in AES mode the change
        key command should be accordingly like as fallows:
        C4+Key No(now it should be 00) + New Key (16 Bytes)+
        New Keyversion(00) + CRC32 + padding
        You should build CRC32 over C4,KeyNo,NewKey,
        NewKeyversion,and you should encipher New Key,
        New keyversion+CRC32+Padding.
        Mustafa

      • Georges

        Hi Mustafa,

        Thanks again for your time according to my issue.

        PICC returns now a 0xAE error. My authentication is OK and I tried to change key to DES key just after authentication, so with IV equals to all 00 and here is my ChangeKey logs :

        SessionKey:
        85 AA A1 FB 63 83 A5 A4 24 84 85 3C 51 BC 1E CA

        New DES key is all 00 too and new key version is 0x01

        Datas to CRC:
        C4 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01

        Calculated CRC:
        9C 3F 81 6C

        Datas to cipher:
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 9C 3F 81 6C 00 00 00 00 00 00 00 00 00 00 00

        Ciphered datas:
        F8 DC 22 CD F1 E0 BA FF 98 2C A9 48 FB FA 25 1B CA A7 4C C9 3E 9C 6D F1 D8 BA C7 85 D8 24 3C 4D

        Complete APDU:
        90 C4 00 F8 DC 22 CD F1 E0 BA FF 98 2C A9 48 FB FA 25 1B CA A7 4C C9 3E 9C 6D F1 D8 BA C7 85 D8 24 3C 4D

        Thanks again…

  • Mustafa Moripek

    Hi Georges,I don’t see any issue.Try with key version 00.
    May be it helps.
    Mustafa

  • Kevin

    Hi all,

    I am trying to Select the PICC Application:

    >> 90 5a 00 00 03 00 00 00 00 (SELECT_APPLICATION)
    << 91 7e (LENGTH_ERROR)

    As you can see i only get a Length error.
    What am i doing wrong?

    Thanks in advance.

  • Farshid

    Hi Mustafa,
    First of all, I would like to thank you for your comments in this blog. I would be very grateful if you could help me on this.
    I have problem with write data command into STD data file just after authentication. I receive 1E (integerity error) in response. I used native wrapped mode for communication. The communication with file is fully enciphered. Here is my log:

    AUTHENTICATE_AES RESPONSE:
    99A2C37F302496EC04C9266317537E5791AF

    ADDITIONAL FRAME:
    FCDE4AA301D0A23FDD0789B2573A4F4F9100

    RANDA:
    01010101010101010101010101010101

    RANDB:
    CBCF486324D58F5AF68523A758E193AF

    SESSION KEY:
    01010101CBCF48630101010158E193AF

    plain data : 1010101010
    file no : 01
    offset : 000000
    to CRC32 : 3D010000000500001010101010
    CRC32 : 7F173118
    data+CRC32 : 10101010107F173118
    padded(data+CRC32):
    10101010107F17311800000000000000
    IV:16 bytes zero
    encryptedData(padded):
    F2B16C8C99171E7097CB4A81386B1357
    writeCommand: 903D00001701000000050000F2B16C8C99171E7097CB4A81386B135700

    response from PCD : 911E

    I’m so confused what is wrong?

  • Mustafa Moripek

    Hi Farshid,
    the write data command looks like as follows:
    3D(cmd) +File No. + Offset + Length + Data(up to 52 bytes).
    You should calculate CRC32 over the above written data.
    Then you add the CRC32 to the data you want to write
    and padd it to multiple of 16 bytes.After encrypting it you
    send the following payload to the PICC:
    3D + File No. + Offset + Length + Encrypted Data
    Mustafa

    • Farshid

      Hi Mustafa,
      Thanks for your quick response. I do exactly as you mentioned and previous posts in blog. I guess CRC32 calculation or last step encryption is wrong! Could you please look closer to my log?

  • Farshid

    Hi Mustafa,
    Thanks for your quick response. I do exactly as you mentioned in your recent comment and previous posts. I guess CRC32 calculation or last step encryption is wrong! Could you please look closer to my log?

  • Mustafa Moripek

    Hi Farshid,
    your CRC32 is O.K.But your AES encrypted data is
    diffrerent from what I get using your session key and
    data.
    I have received:
    82 27 7D 5B C7 35 CA 6F 97 42 03 06 AA E2 D1 5F
    Mustafa

    • Farshid

      Hi Mustafa,
      Thanks for your response.
      As you mentioned, the encrypted data was wrong. That was my fault in copy and pasting into blog. The right result of my AES/CBC/NoPadding encryption method is:

      EC36E44F4835CE7D2E717F62A7AE734D

      The encryption method used in write data and authentication is exactly the same. I also compare my encryption result with the site below and the result was exactly the same.
      http://testprotect.com/appendix/AEScalc

      But I cannot produce your result for encryption! Could you please send me any reference for calculating AES? Is it required to calculate CMAC in write data? or anything else i missed?

  • Mustafa Moripek

    Hi Farshid,
    your data is right.Unfortunately I have mixed up the
    data with the key.In write data and read data operations
    you need to calculate CMAC.You use it for verifying
    the data and for calculating the next IV.
    Mustafa

    • Farshid

      Dear Mustafa,
      I really appreciate your cooperation.
      Because of write command transmission to PCD is done just after authentication, I use 16 byte zero IV for AES encryption in write data. Is it OK? or I should calculate CMAC from anything else and update IV before encryption? if yes, for which data stream I should calculate CMAC?

  • Mustafa Moripek

    Hi Farshid,
    after authentication the session is completed.
    When you start to write to a file a new session
    begins and your start IV is all zeroes.But if you
    go on writing to the file you have to calculate
    CMAC.
    Mustafa

  • Syed Muhammad Mubashir Ahmed

    Dear Mustafa Moripek!!

    I am following the this blog from Ridix for DESFire personalization ,

    And I have converted the below Java Code To Dotnet For The 3DES Inversion Algorithm For The Personaliation Of DESFire,
    http://stackoverflow.com/questions/14117025/des-send-and-receive-modes-for-desfire-authentication
    And 3 DES Algorithm converted to dotnet from java using below code

    DES Algorithm Java Implementation

    The log for Authentication Of DESFire is as follows

    Initial Command To DESFire Is
    900A0000010000

    Result Is
    E552DCADCBE43A9791AF

    RAndB
    491E890DE9ACE932

    RAndB’
    EF2B7FBEC3C66F2F

    RAndB + RAndB’
    491E890DE9ACE932D4CB14681CF252BB

    Result Of Command To DESFire
    (90AF000010491E890DE9ACE932D4CB14681CF252BB00)

    Is
    91AE

  • Mustafa Moripek

    Hi Syed,
    I think your DES decrypting algorithm is
    not working properly.With key all zeroes
    I get 33 F7 53 28 B0 AF 8C 0A for RndB.
    If your key is different let me know it.

  • Wajid P

    Hi mustafa
    Am trying to authenticate and read some data from desfire ev1 card the supplier has given the folowing info
    Read Key 1111111111111111
    1. Select the AID value 0x474731
    2. Use Read Access Key to get authenticating, following 3 parameters are required, the relevant value:
     Key Number 3
     Read Key Read Access Key
     Crypto Type AES
    3. Read the file ID 31 (0x1F, the Access Management file), to get the Read Student Key. Following parameters are required for reading the file ID 31:
     FileType = STANDARD_DATA_FILE
     DataFileSize = 64
     CommunicationMode = FULL_DES_3DES_ENCIPHERING
     ReadAccessKeyNo = 3
     WriteAccessKeyNo = 0
     ReadWriteAccessKeyNo = 0
     ChangeAccessRightKeyNo = 0
    4. Use Read Student Key to read out the File ID 0 ~ 7, to get all student fields information.

    This happens when i try to authenticate

    –>90 AA 00 00 01 03 00
    90 AF 00 00 20 E9 1D C5 46 04 56 5A 95 49 72 CE D5 7B DD A7 40 29 8A 90 89 86 6B 8F B0 3E 9D 72 AB 79 E7 3C 8F 00
    <–91 AE

    Kindly help

  • Harry Aves

    Hello Mustafa,

    I see that you’ve been helping people here about Desfire EV1 problem.
    I also stumbled into a problem with Changing Master Key of Desfire EV1 from default DES ’00..00′ key to AES 128-bit key.
    I’m still getting 0x1E error which is CRC and padding error. I hope you can help me with this.

    Here are the communication step that I did (I use Desfire Native communication):
    1. Authentication with default desfire EV1 key (0x0A)

    –} 0A00
    {– AFB85CA3498592776E
    RndB : A8E029E594F59B69
    –} AFA91D11F94DC26005996C25D223D5A2EB
    {– 00147529039A50613E
    RndA : 450f56d99d1ca3be
    session Key : 450F56D9A8E029E5450F56D9A8E029E5

    2. Change key command (0xC4)
    new AES key : 00000000000000000000000000000000
    crc of new AES key : 3749
    to be decrypted by session key : 000000000000000000000000000000003749000000000000
    output decrypted by session key : aaf394824a3603b2aaf394824a3603b2889f1a58a3f195dc

    –} C480AAF394824A3603B2AAF394824A3603B2889F1A58A3F195DC
    {–1E

    Can you find something that makes the output incorrect ?

  • Mustafa Moripek

    Hi Harry,
    there are several issues which makes the result incorrect.
    First you have built CRC16 and this over the new
    AES key.The correct scheme to change the key to
    AES is as follows:
    You have to build CRC32 of CMD (C4) + Key.No.(80) +
    NewKey(16 Bytes zeroes) + New Key version (00)
    then you have to send the following data in CBC
    mode .
    New key (16 Bytes zeroes) +New Keyversion + CRC32
    + padding.You have to use DES decryption with
    session key.

    Mustafa

  • Harry Aves

    Thank you for the reply Mustafa, I really appreciate it.
    I have tried your suggestion. Here is my communication log :

    1. Authentication with master key (0x0A)
    –} 0A00
    {– AFBA6E8FE05BBB6A2B
    RndB : 2803567A3566D7B3
    –} AF650A87B41582E7A48809460AC35CFB2F
    {– 002978BAA6ACAEFAF4
    RndA : 22ed09f1da39f692
    session Key : 22ED09F12803567A

    2. Change key to AES (0xC4, 0x80)
    new AES key : 00000000000000000000000000000000
    crc of new AES key : 8BE9EDB5
    to be decrypted by session key : 00000000000000000000000000000000008BE9EDB5000000
    output decrypted by session key : e2809112b45aeb54e2809112b45aeb548733bcf8b8d152bc

    –} C480E2809112B45AEB54E2809112B45AEB548733BCF8B8D152BC
    {–1E

    I still have 1E as the result. Is there any step that is incorrect ?

  • Mustafa Moripek

    Hi Harry,
    your CRC32 is correct,also your DES decrypting
    algorithm.The issue is you haven’t used CBC
    (Block cipher chaining).The data you want to
    decrypt is longer then eight bytes so you have
    to chain them as follows:
    Start IV (initial vector) : 00 00 00 00 00 00 00 00
    First eight bytes : 00 00 00 00 00 00 00 00
    Start IV exor first 8 bytes : 00 00 00 00 00 00 00 00
    Result : 00 00 00 00 00 00 00 00
    DES decr of the result : E2 80 91 12 B4 5A EB 54
    New IV : E2 80 91 12 B4 5A EB 54
    Second 8 bytes : 00 00 00 00 00 00 00 00
    New IV exor second 8 bytes : E2 80 91 12 B4 5A EB 54
    DES decr of the result : AD AE 41 03 C7 A4 53 FD
    New IV : AD AE 41 03 C7 A4 53 FD
    Last 8 byets : 00 8B E9 ED B5 00 00 00
    New IV exor last 8 bytes :AD 25 A8 EE 72 A4 53 FD
    DES decr of the result :92 8C 5C C8 31 75 3C A0
    Now your payload is : C4 80 E2 80 91 12 B4 5A EB 54
    AD AE 41 03 C7 A4 53 FD 92 8C 5C C8 31 75 3C A0
    Mustafa

  • Harry Aves

    Thank you for your reply Mustafa, please bear with me because I still have problem with the result.

    here are my comm log :

    1. Authentication (0x0A) :
    –} 0A 00
    {– AF 6B 17 AC 3D 49 92 DC C9
    –} AF 9E 34 96 57 40 3F F0 31 14 CD D6 32 A2 1C 88 FE
    {– 00 FC 93 BD 19 23 E5 B1 27

    new AES key : 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    crc of new AES key : 8B E9 ED B5

    to be decrypted by session key :
    00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 8B E9 ED B5 00 00 00

    output decrypted by session key :
    27 7F CB C0 3B E8 59 AF D4 FE 04 66 45 04 5E E0 8D 34 92 ED 04 24 92 17

    2. Change Key (0xC4)
    –} C480277FCBC03BE859AFD4FE046645045EE08D3492ED04249217
    {–1E

    Can you notice any problem with the process ?

  • Harry Aves

    forgot to mention, I have implemented the cbc des as you wrote on your previous comment and I have same result with you for the same key and input data you’ve tried on the comment.

  • Mustafa Moripek

    Hi Harry,
    sorry I made a mistake.You are authenticating using
    native DES format (0A).The change key scheme should be:
    CRC16 over NewKey,DES decrypting (CBC mode) of : new key,
    CRC16 plus padding.
    Payload:C4 80 decrypted data (totally 26 bytes).
    Sorry again.
    Mustafa

  • Harry Aves

    yay, at last. thank you for all your help mustafa.

  • Farshid

    Dear Mustafa,

    I have tried everything to get my DES ChangeKey command work but till now without any result. I’ll really appriciate if you could help me out.
    Oke hier is my situation:

    I can create DES application en DES file on my DESFire EV1 card with ‘00000000000000000000000000000000’ as default key without any problem. But the last step (ChangeKey) to set the real key results constantly in ‘1E’ (‘INTEGRITY ERROR’). I do have a succesfull Authentication. But the last step (C4 command) goes wrong. I have my doubts whether my SessionKey, CRC16 and/or CBC chaining are correct.
    Here are my logs:
    DefaultKey: ‘00000000000000000000000000000000’
    NewKey: ‘00112233445566778899AABBCCDDEEFF’
    Authentication:
    ->’90 0A 00 00 01 00 00′
    ’90 AF 00 00 10 99 4D 4D C1 57 B9 6C 52 2D 99 51 57 AC 93 69 DB 00′
    ’90 C4 00 00 19 00 B2 C5 93 F7 E6 AC 3C 44 04 69 A8 13 F9 16 0F DB 8B C1 D0 1B F7 1F 37 31 00′
    <-'91 1E '

    So Mustafa, would you please take a close look at my steps and tell me what I'm doing wrong? Thanks a lot for your time.

    • Mustafa Moripek

      Hi Farshid,
      write the whole log:your session key,crc16,the payload
      before encrypting and then after the encrypting.Otherwise
      I can’t see where the issue is.
      Mustafa

      • Farshid

        Dear Mustafa,

        Thank you for your response to my previous question. I got that one solved by comparing my code with an example code. My mistake was in caclulating the session key.

        I’m now working on GetKeySettings command. I can get a successfull authentication, but when I execute the command (45), I get an CA (Command Aborted) error from the card.

        This is what I get back from my authentication:
        63 A4 0D CC F6 D0 65 22 D5 6E 71 05 BC 2C 55 B9 91 AF

        And this is my GetKeySettings command: 90 45 00 0000

        And here is my response: 91 CA

        Would you please help me out of this? I’ve tried everything but no success.

      • Farshid

        Hello Mustafa,

        Ik see now that the card expect an AdditionalFrame command (AF) to send the reminding data. But what should I send to the card with my command? I’m really new in this, so please be as detailed as you can.

        Thanks in advance for your response.

  • Nima

    hi all
    I have problem with change key .
    please help me

    this is my result
    I use Des .

    Read Card Info : ( Desfire Detect ) (UID len : 7 ) ( SEL RES : 20) (UID : 04 6F 45 99 C9 24 80 ) ( RATS : 75 77 81 02 80 BD )

    Card Selected.

    Desfire >> Try To Login With KeyNo : ( 0 )

    InDataExchange PN532 —>> Card : 0A 00

    InDataExchange PN532 <> Read RndB : <>

    Desfire >> Generate RndA : <>

    InDataExchange PN532 —>> Card : AF D7 2B BD 27 A8 62 D5 34 1A CF CE D6 C5 31 7C FF

    InDataExchange PN532 <> Reading RndA’ : <>

    Desfire >> RndA’ After Decrype : <>

    Desfire >> Session Key : <>

    Desfire >> Login Sucsess

    Desfire >> Try To Change Key of KeyNo : ( 0 )

    Desfire >> Old key : <>

    Desfire >> New key : <>

    Desfire >> 24 Bytes ChangeKey Parameter : <>

    Desfire >> 24 Bytes ChangeKey Parameter After Decrype : <>

    InDataExchange PN532 —>> Card : C4 00 96 47 09 F8 05 F1 8E B0 2F B9 E3 4F 89 35 F7 CC 69 55 17 F4 03 0D B7 72

    InDataExchange PN532 <> Error In Changing Key

  • Nima

    oops , why parameter is empty ?
    I send again .

    Read Card Info : ( Desfire Detect ) (UID len : 7 ) ( SEL RES : 20) (UID : 04 6F 45 99 C9 24 80 ) ( RATS : 75 77 81 02 80 BD )

    Card Selected.

    Desfire -> Try To Login With KeyNo : ( 0 )

    InDataExchange PN532 -> Card : 0A 00

    InDataExchange PN532 Read RndB : ( 3E D7 5B 68 CD C0 2D 7B )

    Desfire -> Generate RndA : ( B8 2D A0 05 55 C7 3F B1 )

    InDataExchange PN532 -> Card : AF A4 69 68 D6 77 E1 CC C1 81 D0 2D 71 DE 96 6C 6D

    InDataExchange PN532 Reading RndA’ : ( 21 EC 15 A2 5C D9 D9 2B )

    Desfire -> RndA’ After Decrype : ( 2D A0 05 55 C7 3F B1 B8 )

    Desfire -> Session Key : ( B8 2D A0 05 3E D7 5B 68 next 8 byte if use 3des : 55 C7 3F B1 CD C0 2D 7B )

    Desfire -> Login Sucsess

    Desfire -> Try To Change Key of KeyNo : ( 0 )

    Desfire -> Old key : ( 00 00 00 00 00 00 00 00 )

    Desfire -> New key : ( 31 31 31 31 31 31 31 31 )

    Desfire -> 24 Bytes ChangeKey Parameter : ( 31 31 31 31 31 31 31 31 00 00 00 00 00 00 00 00 15 07 00 00 00 00 00 00 )

    i test next 8 byte to 0x31 . but dosn’t work

    Desfire -> 24 Bytes ChangeKey Parameter After Decrype : ( 7D E8 FA 5E 4E 85 F5 32 72 31 C1 A8 6D 56 15 D0 C1 9B 3F C3 8A A8 38 15 )

    InDataExchange PN532 -> Card : C4 00 7D E8 FA 5E 4E 85 F5 32 72 31 C1 A8 6D 56 15 D0 C1 9B 3F C3 8A A8 38 15

    InDataExchange PN532 Error In Changing Key

    • Nima

      mustafa , please see my result , whats my problem?

      • Mustafa Moripek

        Hi Nima,
        there are several issues I have rcognized.
        First thing the key should be 16 bytes long.That means
        you have to use 16 times 31.Same is valid for the
        session key.You have to use two times :
        Rnda(0-3)+RndB(0-3).When you build CRC16
        you have to build it over 16 times 31.
        When decrypting the 24 byte change key parameter
        you have tu use cbc chaining and single DES.
        For the first half of your key is equal to the
        second half you have to use single DES.
        CBC chaining means:you decrypt first eight byte,
        then you have to xor the result with the second eight
        byte and decrypt it.Atlast you xor that result with
        the third eight byte and decrypt it.
        Mustafa

      • Nima

        Thanks for your answer. I try 16 byte 31 and crc over that. But not work. I use cbc and des by oryx-embedded library.
        That library have cbc. I use it.

    • Nima

      System start

      Read Card Info : ( Desfire Detect ) (UID len : 7 ) ( SEL RES : 20) (UID : 04 6F 45 99 C9 24 80 ) ( RATS : 75 77 81 02 80 BD )

      Card Selected.

      Desfire -> Try To Login With KeyNo : ( 0 )

      Desfire -> Read RndB : ( 33 C4 FB F2 1E 68 59 E7 )

      Desfire -> Generate RndA : ( F8 6C D1 45 AA 1D 90 F5 )

      Desfire -> Reading RndA’ : ( 0E 9F F4 C5 A4 68 53 A6 )

      Desfire -> RndA’ After Decrype : ( 6C D1 45 AA 1D 90 F5 F8 )

      Desfire -> Session Key : ( F8 6C D1 45 33 C4 FB F2 next 8 byte if use 3des : AA 1D 90 F5 1E 68 59 E7 )

      Desfire -> Login Sucsess

      Desfire -> Try To Change Key of KeyNo : ( 0 )

      Desfire -> Old key : ( 00 00 00 00 00 00 00 00 )

      Desfire -> New key : ( 31 31 31 31 31 31 31 31 )

      Desfire -> 24 Bytes ChangeKey Parameter : ( 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 98 3D 00 00 00 00 00 00 )

      Desfire -> 24 Bytes ChangeKey Parameter After Decrype : ( AC D1 86 51 4C E8 13 4D 9D E0 B7 60 7D D9 22 7C 1C 8C AC E8 84 C1 70 A0 )

      Desfire -> Error In Changing Key

  • Mustafa Moripek

    Hi Farshid,
    the GetKeySettings command is only
    one byte long (0X45).From what you wrote
    I can see that you are authenticating in AES mode
    and the authentication is not finished.The answer you
    have got from PICC is enciphered RndB.First you
    have to finish the authentication and then send the
    GetKeySettings command.As answer you will get
    1 byte key settings + 1 byte max. key number
    and optionally MAC.
    Mustafa

  • Mustafa Moripek

    Hi Nima,
    I have checked your data and I think your cbc
    algorithm is not working correctly.The first 8 bytes of
    your change key parameter is O.K.
    If you xor this with 8 times 0X31 you get the second
    8 bytes of your parameter (9D E0 B7 60 7D D9 22 7C).
    You should decrypt it (single DES).Then you should
    xor this decrypted data with 98 3D 00 00 00 00 00 00 ,
    and decrypt it (single DES) so you get the last 8
    bytes of the change key parameter.The last 8
    bytes on your log is completely different.
    Mustafa

    • Nima

      Hi mustafa.
      please visit http://www.oryx-embedded.com .
      I use Des and CBC with that library.
      this is standard library for SSL .
      I think My CBC is true . please solve my problem .

      here my code .
      bool MifareDesfire_ChangeKey(uint8_t key_number,uint8_t *OldKey,uint8_t *NewKey)
      {
      uint16_t answerLen;
      uint8_t answer[32];
      uint8_t commandParam[32] ;

      commandParam[0] = key_number;

      #if (DEBUG_DESFIRE==1)
      printf(“Desfire -> Try To Change Key of KeyNo : ( %d )\n\r”, key_number);
      #endif
      #if (DEBUG_DESFIRE==1)
      printf(“Desfire -> Old key : (“);
      for(uint8_t i=0 ; i New key : (“);
      for(uint8_t i=0 ; i<8 ; i++)
      printf(" %02X",NewKey[i]);
      printf(" )\n\r");
      #endif

      desInit(&myCodeContext,Desfire_SessionKey,8);

      for(uint8_t i=0 ; i<8 ; i++)
      commandParam[i+1] = NewKey[i];

      for(uint8_t i=8 ; i<16 ; i++)
      commandParam[i+1] = NewKey[i-8];

      iso14443a_crc(&commandParam[0+1],16,&commandParam[16+1]);

      for(uint8_t i=18 ; i 24 Bytes ChangeKey Parameter : (“);
      for(uint8_t i=1 ; i 24 Bytes ChangeKey Parameter After Decrype : (“);
      for(uint8_t i=1 ; i Error in Sending Cammands\n\r”);
      #endif
      return false;
      }

      if(answer[0] != 0x00)
      {
      #if (DEBUG_DESFIRE==1)
      printf(“Desfire -> Error In Changing Key\n\r”);
      #endif
      return false;
      }

      return true;

      } .

  • Nima

    oops .I dont know why cant copy paste code here . code is here .

    bool MifareDesfire_ChangeKey(uint8_t key_number,uint8_t *OldKey,uint8_t *NewKey)
    {
    uint16_t answerLen;
    uint8_t answer[32];
    uint8_t commandParam[32] ;
    commandParam[0] = key_number;

    desInit(&myCodeContext,Desfire_SessionKey,8);

    for (uint8_t i=0 ; i<8 ; i++)
    commandParam[i+1] = NewKey[i];
    for (uint8_t i=8 ; i<16 ; i++)
    commandParam[i+1] = NewKey[i-8];

    iso14443a_crc(&commandParam[0+1],16,&commandParam[16+1]);
    for(uint8_t i=18 ; i<24 ; i++)
    commandParam [i+1] = 0;

    cbcDecrypt(DES_CIPHER_ALGO,&myCodeContext,iv,&commandParam[1],&commandParam[1],24);

    if(MifareDesfire_SendCommandAndAnswer(MIFARE_DESFIRE_CMD_CHANGEKEY,commandParam,25,answer,&answerLen)==false)
    {
    return false;
    }
    if(answer[0] != 0x00)
    {
    return false;
    }
    return true;

    }

    • Farshid

      Hello Mustafa,

      Thank you for your response. Now I do the following and get another error:

      Authentication:
      –> 90 AA 00 00 01 02 00
      90 AF 00 00 20 05 1B A4 AB 6F 85 4F 44 25 D7 81 DF C5 27 04 D3 8B C2 DF 62 4E 2E 7D BA 8F 2A 41 0C B4 EF FD C8 00
      90 45 00 00 00
      <– 91 AE

      As you can see I get aan authntication error.

      I have no explanation for the steps I do for they are copied from another routine (calculating session key).

      Would you please tell me what do I do wrong?

      Thank you.
      Farshid

      • Farshid

        Hello Mustafa,
        Some How Part of my post disappeared. I guess there is a limitation of the post. Here I put it step for step:

        Authentication:
        –> 90 AA 00 00 01 02 00
        <– 1B 08 22 56 FC 6D 84 F2 D4 FE 9B 79 5E 22 E4 D9 91 AF

      • Farshid

        Then I set my IV vector to:
        00000000000000000000000000000000

        I decrypt the response of PICC from the authentication and put it in RndB

        I rotate the first byte of RndB and get the following:
        E4`3E 0E 5D 47 63 6B 6E 97 25 72 10 01 13 59 A8

        I set my IV vector to: 01010101010101010101010101010101 and assign that to my RndA = 01010101010101010101010101010101

      • Farshid

        I encrypt hRndA+hRndB and send the result to the PICC
        –>90 AF 00 00 20 05 1B A4 AB 6F 85 4F 44 25 D7 81 DF C5 27 04 D3 8B C2 DF 62 4E 2E 7D BA 8F 2A 41 0C B4 EF FD C8 00
        <– D3 D4 60 56 35 B1 93 31 61 A0 20 17 26 AE B0 58 91 00

        So far so good.

      • Farshid

        Now I send the real command to the PICC
        –>90 45 00 00 00
        <– 91 AE

        As you can see I get aan authntication error.

        I have no explanation for the steps I do for they are copied from another routine (calculating session key).

        Would you please tell me what do I do wrong?

        Thank you.
        Farshid

    • Mustafa Moripek

      Hi Nima,
      I can’t say what is wrong with your code.I will
      write down how your changekey parameter in cbc mode
      should be,so you can test your code step by step
      to fix the isue.
      Your 24 byte parameter :
      31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31
      98 3D 00 00 00 00 00 00
      Des decrypt 31 31 31 31 31 31 31 31 0 =>
      AC D1 86 51 4C E8 13 4D XOR with
      31 31 31 31 31 31 31 31 => 9D E0 B7 60 7D D9 22 7C
      Des decrypt 9D E0 B7 60 7D D9 22 7C =>
      62 2C DB A5 2A 83 66 B7 XOR with
      98 3D 00 00 00 00 00 00 => FA 11 DB A5 2A 83 66 B7
      Des decrypt FA 11 DB A5 2A 83 66 B7=>E4 B8 78 16 42 49 AD FC
      Your des decrypted 24 byte data should be
      AC D1 86 51 4C E8 13 4D 62 2C DB A5 2A 83 66 B7
      E4 B8 78 16 42 49 AD FC

      Mustafa

  • Flowerzo

    Hi All,
    I need speak in private mode because I have a problem of base to work with Mifare DesFire. Can I ask at you?

  • Mustafa Moripek

    Hi Farshid,
    here is the authentication scheme for AES type key:
    You receive from PICC enciphered RndB.This
    is now your new IV.You build RndB’ (as you made correctly)
    You generate RndA and you have to send this data
    to the PICC in cbc mode as follows :
    You XOR RndA with the new IV (the enciphered RndB
    you have received from PICC) you have to enciphere
    this data using AES mode.This enciphered data is
    your new IV.You have to XOR this with RndB’
    and encipher the result and send it to PICC.This
    enciphered Rnd’ is your new IV which you use
    for following operations.
    Mustafa

    • Farshid

      Hello Mustafa,

      Thans again for your response.
      Should I do this instruction after my AF or should I use the result of this for my AF?
      I know it’s too much to ask but would you please give me some example hoe it works. I mean from the authentication to GetKeySettings.You can just use fake data, just to give an impression of the process.
      I really appreciate your effort and time.

  • Mustafa Moripek

    Hi Farshid,
    after you have receive RndB you have to send
    this payload,but you have to start with AF.
    Mustafa

    • Farshid

      Hello Mustafa,

      Do I understand you correct?
      . I do the authentication
      . I do the Additional Frame as I already do
      . I do the CBC with XOR and the rest of stuff you explained
      . I send the result of the previous step together with the main command (0X45) to the PICC

    • Farshid

      Hallo Mustafa,

      I’ve changed my routine and followed your instruction and here is the result:

      Data from Authentication:
      <– D4 9F 99 A7 EB 49 84 56 56 79 5E 37 9D 8F 4A 4E 91 AF
      Rotate first byte and calculate RndB
      RndB = 9F 99 A7 EB 49 84 56 56 79 5E 37 9D 8F 4A 4E D4
      Generated RndA
      RndA = 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
      Set IV to RndB

      • Farshid

        XOR RndA with RndB => 9E 98 A6 EA 48 85 57 57 78 5F 36 9C 8E 4B 4F D5
        Encipher de result of previous XOR => 42 86 04 A5 49 37 4A 3B 71 EE 4E 40 F6 C4 B8 34
        Set IV to this encipher value
        XOR this new IV with RndB => DD 1F A3 4E 00 B3 1C 6D 08 B0 79 DD 79 8E F6 E0
        Encipher de result of previous XOR => 59 BB 6F 03 8B 78 45 5F 38 13 52 65 18 CB D3 ED
        Set IV to this encipher value
        Send this encipher value along with the command to the PICC
        –>90 AF 00 00 20 59 BB 6F 03 8B 78 45 5F 38 13 52 65 18 CB D3 ED 00
        <– 91 7E

  • Nima

    Hi Mustafa . I try it . but Not….
    Read Card Info : ( Desfire Detect ) (UID len : 7 ) ( SEL RES : 20) (UID : 04 6F 45 99 C9 24 80 ) ( RATS : 75 77 81 02 80 BD )

    Card Selected.

    Desfire -> Try To Login With KeyNo : ( 0 )

    InDataExchange PN532 -> Card : 0A 00

    InDataExchange PN532 Read RndB : ( A6 85 35 B0 38 EE B3 72 )

    Desfire -> Generate RndA : ( 83 F7 6A CF 43 A7 1B 8E )

    InDataExchange PN532 -> Card : AF 21 E5 A1 6B 03 EA 99 18 1E E3 24 BC F4 F8 62 B0

    InDataExchange PN532 Reading RndA’ : ( 65 8B 84 BA 67 33 4C 02 )

    Desfire -> RndA’ After Decrype : ( F7 6A CF 43 A7 1B 8E 83 )

    Desfire -> Session Key : ( 83 F7 6A CF A6 85 35 B0 next 8 byte if use 3des : 43 A7 1B 8E 38 EE B3 72 )

    Desfire -> Login Sucsess

    Desfire -> Try To Change Key of KeyNo : ( 0 )

    Desfire -> Old key : ( 00 00 00 00 00 00 00 00 )

    Desfire -> New key : ( 31 31 31 31 31 31 31 31 )

    Desfire -> 24 Bytes ChangeKey Parameter : ( 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 98 3D 00 00 00 00 00 00 )

    Desfire -> 24 Bytes ChangeKey Parameter After Decrype : ( 1A E5 FE 63 6A 92 17 D0 91 54 85 82 B2 18 7C AF 1D E9 8E A0 95 6A 0B 8F )

    InDataExchange PN532 -> Card : C4 00 1A E5 FE 63 6A 92 17 D0 91 54 85 82 B2 18 7C AF 1D E9 8E A0 95 6A 0B 8F

    InDataExchange PN532 Error In Changing Key

  • Nima

    one question Mustafa .
    My session key is true ?

    • Mustafa Moripek

      Hi Nima,
      I have checked your data with the session key
      you have given.Using this session key your 24
      bytes data is correct.If you get error message then
      your session key is wrong.If the data A6 85 35 B0
      38 EE B3 72 is the answer from PICC then it is
      not RndB but encrypted RndB and you have
      to decrypt it to build the session key.
      Mustafa

  • Mustafa Moripek

    Hi Farshid,
    I have problems verifying your data.First you
    have to authenticate with the card and after
    you receive success answer (91 00) you can
    send the next command 45.The authentication
    procedure is as I described before.Now to your
    data.If D4 9F 99 A7 EB 49 84 56 56 79 5E 37 9D
    8F 4A 4E is the answer from PICC then you
    have to decipher it and then rotate to get RndB’.
    I f it is the deciphered data then you cannot use
    İt to build the xored data.You have xor RndA
    with the data you receive from PICC without rotating.
    Rest you make as I described it.When sending
    to PICC you have to send enciphered RndA
    and eciphered Rnd B’.You have sent only
    RndB’ therefore you have received error
    message 7E (lengthe error).You should see it
    from your command.You have written as
    Length 32 bytes but you have sent 16 bytes only.

    Mustafa

    • Farshid

      Thank you very much Mustafa for you response.
      Sorry! You are right I wasn’t really clear about that part. The data I wrote (D4 9F 99 A7 EB 49 84 56 56 79 5E 37 9D 8F 4A 4E) is the one I received from the PICC for my authentication (’90 AA 00 00 01 02 00′) with a 91 AF at the end. I forgot to put that one and the end.
      Do I understand you correct that I have to follow your instruction AFTER a successfull (’90 AA 00 00 01′) to build my command for my (’90 AF 00 00 20′ + output of your instruction)? And after a successfull (90 AF….) I just need to send a single (’90 45 00 00′) command to the PICC te receive my settings?

      • Mustafa Moripek

        Hi Farshid,
        my instructions are part of authentication.You have
        to follow them to get the successful answer.After that
        you can send other commands.
        Mustafa

      • Farshid

        Hello Mustafa,
        Thank you again for you response. But I miss the enciphering of RndA in your instruction. In which step and which IV do I encipher RndA and add it to the RndB? The result that I send to the PICC is still onlt 16 byte long and I understood from you that it should be 32 byte.

  • Nima

    Thanks for your support mustafa. I test it soon and tell you.

  • Nima

    Thanks a lot mustafa . my problem solve after 6 month . I’m so happy . 🙂 🙂 🙂
    very very very thank you.

  • Mustafa Moripek

    Hi Farshid,
    let me write again the authentication from beginning.
    To your authent cmd AA 0 the PICC response with
    16 bytes data.This is encciphered (RndB).You have
    to decrypt it and rotate it to get RndB’.Then you
    have to generate RndA.Then you have to send
    AF + encrypted( RndA + RndB’) to the PICC.The
    The enciphering of RndA+RndB’ you should do
    according my instructions above.
    Mustafa

  • Fiore

    Hi,
    the date that we must to send to PICC is 3DES(rndA) + 3DES(rndB xor 3DES(rndA))..

  • Farshid

    Dear Mustafa,
    I thought this time that I’m following you instruction step by step but obviously I’m doing something wrong: 😦
    Here is my log:
    –>’90 AA 00 00 01′
    ’90 AF 00 00 20’+’72 C1 6F B3 94 CB A1 5B 43 8F A4 81 BD D0 F0 F1 0B 01 A3 98 D7 01 8B 66 03 E1 85 B1 87 EE 61 4D 60 DB C5 66 F8 51 D6 B8 C3 2D 2A 17 59 19 84 A4’+’00’
    <–'91 7E'

    • Farshid

      I don’t what is wrong with this forum but it just cut my post:
      Here a new try:
      PART1:
      –>’90 AA 00 00 01′
      <–'9C 3F ED 40 67 DA 26 E3 F9 BC 9C FA 5D 58 38 10 91 AF'
      1. encRndB = '9C 3F ED 40 67 DA 26 E3 F9 BC 9C FA 5D 58 38 10'
      2. Set IV to encRndB
      3. RndB = Decipher(encRndB) = '78 06 E5 F9 DB B7 13 BF 06 3E FD 9A D2 7F 02 B2'
      3. Set IV to RndB
      4. rotRndB = '06 E5 F9 DB B7 13 BF 06 3E FD 9A D2 7F 02 B2 78'
      5. Generate RndA = '01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01'

      • Farshid

        PART2:
        6. xorRndB_RndA = XOR(encRndB with RndA) = ‘9D 3E EC 41 66 DB 27 E2 F8 BD 9D FB 5C 59 39 11’
        7. encXOR_RndB_RndA = Encipher(RndA + xorRndB_RndA) = ‘E0 7F F5 7E 72 21 8D 67 E2 E6 19 96 BF 61 16 75 20 12 F7 45 1E 0E 26 9C FB 78 44 74 91 E4 3B A4’
        9. Set IV to encXOR_RndB_RndA
        10. FinalXOR = XOR(encXOR_RndB_RndA with hBinRndB) = ‘7C 40 18 3E 15 FB AB 84 1B 5A 85 6C E2 39 2E 65 FF FF FF FF FF FF FF FF FF FF FF FF FF FF DB DB’
        11. Result := Encipher(RndA + FinalXOR) = ’72 C1 6F B3 94 CB A1 5B 43 8F A4 81 BD D0 F0 F1 0B 01 A3 98 D7 01 8B 66 03 E1 85 B1 87 EE 61 4D 60 DB C5 66 F8 51 D6 B8 C3 2D 2A 17 59 19 84 A4′

      • Farshid

        –>’90 AF 00 00 20’+’72 C1 6F B3 94 CB A1 5B 43 8F A4 81 BD D0 F0 F1 0B 01 A3 98 D7 01 8B 66 03 E1 85 B1 87 EE 61 4D 60 DB C5 66 F8 51 D6 B8 C3 2D 2A 17 59 19 84 A4’+’00’
        <–'91 7E'

  • Mustafa Moripek

    Hi Farshid,
    I will try to explain the authentication procedure again
    but first I want to say you that the data you have
    to send to PICC should be 32 bytes long: 16 Bytes
    RndA plus 16 Bytes RndB'(You have sent 48 bytes and
    received length error again).But you have to encrypt
    those 32 bytes of data before sending and now
    I will explain how to make it using your data.The response
    to your authentication command is encrypted already you don’t
    need to encrypt it again.You have to decrypt it to get RndB.
    !.If you decrypt :9C 3F ED 40 67 DA 26 E3
    F9 BC 9C FA 5D 58 38 10 you get
    2. RndB : 36 D5 9C C1 78 C9 E5 0B 61 64 DE 5C 55 28 8B 4C
    if you rotate it you get
    3. RndB’ : D5 9C C1 78 C9 E5 0B 61 64 DE 5C 55 28 8B 4C 36
    4. RndA : 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
    5. RndA XOR enc(RndB) :
    (9C 3F ED 40 67 DA 26 E3 F9 BC 9C FA 5D 58 38 10) XOR
    (01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01) =
    9D 3E EC 41 66 DB 27 E2 F8 BD 9D FB 5C 59 39 11
    6. Now encrypt the result and get : F3 3F 66 D1 F8 1E 89 ED
    8F FE 30 72 BB 2E D9 BE
    7. Your encrypted RndA is : F3 3F 66 D1 F8 1E 89 ED
    8F FE 30 72 BB 2E D9 BE
    at the same time this is your new IV
    8. RndB’ (step 3) XOR new IV (step7) : 26 A3 A7 A9 31 FB 82 8C
    EB 20 6C 27 93 A5 95 88
    9. Encrypt result (step 8) : 51 AB E4 92 FA BE C9 7A
    B6 8E CB F9 01 C9 CF 36
    10. The data you have to send to PICC is : AF + Step6 + Step 9:
    AF F3 3F 66 D1 F8 1E 89 ED 8F FE 30 72 BB 2E D9 BE
    51 AB E4 92 FA BE C9 7A B6 8E CB F9 01 C9 CF 36
    As response you will receive 16 Bytes data from PICC.This
    is encrypted RndA’.For check puposes you decrypt it and
    reverse rotate to get RndA.
    Your authentications is now complete an you build
    the session key as follows:
    RndA(byte 0-3)+RndB(byte 0-3)+RndA(byte12-15)+RndB(byte12-15)

    Mustafa

    • Farshid

      Dear Mustafa,

      You are brilliant!! Thank you ver much for your effort and detailed explanation.

      But one last question before I start implement this: Should I use this session key with my GetKeySetting command like ’90 45 00 00 + SessionKey + 00′ ?

      Than you again, Farshid

      • Mustafa Moripek

        Hi Farshid,
        after building the sessionkey you have to use
        it for each encryption or decryption until
        the session is complete.
        Mustafa

      • Farshid

        Hello Mustafa,

        Thank you for your quick response.
        I see dat I get a different result for my first decryption (step 1) already. If I decrypt: ‘9C 3F ED 40 67 DA 26 E3 F9 BC 9C FA 5D 58 38 10′
        Then I get: E4 39 08 B9 BC 6D 35 5C FF 82 61 60 8F 27 3A A2
        While you get: 36 D5 9C C1 78 C9 E5 0B 61 64 DE 5C 55 28 8B 4C
        What is the default IV you use for your decryption:
        I use ’00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00’?

        Cheers, Farshid

  • Mustafa Moripek

    Hi Farshid,
    Your data is wrong.But my is also.
    I have mixed up data with key so all the
    results are wrong.I give you the correct ones.
    You have to decrypt the response to get RndB.
    1.If you decrypt :9C 3F ED 40 67 DA 26 E3
    F9 BC 9C FA 5D 58 38 10 you get
    2. RndB : 30 6C B0 EA 51 BA D1 13
    F6 FD EB 7C 80 8A E3 C8
    if you rotate it you get :
    3. RndB’ : 6C B0 EA 51 BA D1 13 F6 FD EB 7C 80 8A E3 C8 30
    4. RndA : 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
    5. RndA XOR enc(RndB) :
    (9C 3F ED 40 67 DA 26 E3 F9 BC 9C FA 5D 58 38 10) XOR
    (01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01) =
    9D 3E EC 41 66 DB 27 E2 F8 BD 9D FB 5C 59 39 11
    6. Now encrypt the result and get : CB 02 BE D4 78 B2 58 DD
    12 E6 42 2E A3 1A C5 C2
    7. Your encrypted RndA is : CB 02 BE D4 78 B2 58 DD
    12 E6 42 2E A3 1A C5 C2
    at the same time this is your new IV
    8. RndB’ (step 3) XOR new IV (step7) : A7 B2 54 85 C2 63 4B 2B
    EF 0D 3E AE 29 F9 0D F2
    9. Encrypt result (step 8) : FD 1E 00 FB 64 77 9E C8
    91 00 B7 CA 14 89 61 0D
    10. The data you have to send to PICC is : AF + Step6 + Step 9:
    AF CB 02 BE D4 78 B2 58 DD 12 E6 42 2E A3 1A C5 C2
    FD 1E 00 FB 64 77 9E C8 91 00 B7 CA 14 89 61 0D
    As response you will receive 16 Bytes data from PICC.This
    is encrypted RndA’.For check puposes you decrypt it and
    reverse rotate to get RndA.
    Your authentications is now complete an you build
    the session key as follows:
    RndA(byte 0-3)+RndB(byte 0-3)+RndA(byte12-15)+RndB(byte12-15)
    If you don’t get my results then is your AES decrypting
    and/or encrypting algorithm.
    Mustafa

    • Farshid

      Hello Mustafa,

      I got it! It’s working now. Thank you very much for your help.
      This is what I recieved from the PICC now after I sent the GetKeySettings command:
      ‘0B 01 5A 70 05 FF 0E 3E 22 07 91 00’
      Do you know what the meaning is of every byte? How can I translate this in to the readable settings?

      Cheers, Farshid

  • Roshni

    Hi,
    I am new to this concept of Desfire communication.
    I want to find a command to READ the data in the Mifare Desfire card.
    Using af a2 be cd 03 d8 46 cb 33 i have authenticated it, how ever i can’t find a command to read the data in the card. If someone could please help me I’d be extremely grateful.

  • Mustafa Moripek

    Hi Farshid,
    from the key settings you cannot determin which
    encryption algorithm the PICC is using.If you
    authenticate with command AA you have to use
    AES encryption.If the authent command is 0A then
    you have to use DES or 3DES.If the first half (first
    8 bytes) are equal to the second you use DES
    if not you have to use 3DES.
    The meaning of the response you have received
    from PICC to your GetKeySettings command is :
    First byte (0B) means that the configuration is
    changeable,that the master key is not required for
    creating or deleting any application and the changing
    of the PICC master key is allowed.The second
    byte (01) is the maximum number of the keys.The
    following eight bytes (5A 70 05 FF 0E 3E 22 07 )
    are CMAC.
    These and many other information you can get
    if you contact NXP and ask for datasheets which
    you can get after signing an NDA.
    Mustafa

    • harsha javagal

      Hi Mustafa,

      I am trying to change the master key settings

      data = 9077c50000000000
      combined decrypted data with 54
      getting 1E error. Please help

  • PRAVEENA

    Hi Mustafa,
    I am very new to Mifare desfire programming.I could able to proceed with very few steps upto getversion cmnds.But,if i am trying to authenticate desfire card using 0a 00 its not responding.Even it is not trowing any error also.If i am mentioning 0a 01..then it is responding with “no such key”.Is it required to set any thing on the card side to respond with authenticate command?I am not getting what to do.The card is HID Desfire DBL.It’s 8k card.So,please let me know,how i have to proceed with?Thanks in advance.Below is the data exchange between reader and the card.Reader is the my own developed reader,which uses clrc632 ic.This is working for mifare classic.
    ::
    PCD_TRANSCEIVE..10
    ..in request.. :4403
    PCD_TRANSCEIVE.. 28
    ..in Anti-coll-cl1 snr.. :88 04 95 59 40
    PCD_TRANSCEIVE.. 08
    ..in Select snr.. :24
    PCD_TRANSCEIVE.. 28
    ..in Anti-coll-cl2 snr.. :52 82 3A 80 6A
    PCD_TRANSCEIVE..08
    ..in Select snr2.. :20
    ..UID(7 -byte is.. :04 95 59 52 82 3A 80
    Sending RATS. :
    PCD_TRANSCEIVE.. 30
    …… RATS-SEQ : e0 50
    067577810280
    ..Sending PPS.. :
    PCD_TRANSCEIVE…08
    …… PPS-SEQ : d0 11 00
    D0
    ..Sending Get_version….. :
    PCD_TRANSCEIVE.. 48
    …… get_ver : 02 60
    02AF04010101001A050F
    ..Sending Get_version1111….. :
    PCD_TRANSCEIVE.. 48
    …… get_af1 : 03 af
    03AF04010101041A050F
    ..Sending Get_version2222….. :
    PCD_TRANSCEIVE.. 80
    …… get_af2 : 02 af
    020004955952823A80BA5451D6501105

    ..Sending Get_appid….. :
    PCD_TRANSCEIVE.. 10
    …… get_app-id : 03 6a
    0300

    ..Sending sel_picc:…. :
    PCD_TRANSCEIVE.. 10
    …… get_select picc app : 02 5a 00 00 00
    0200

    ..Sending get fileid’s:…. :
    PCD_TRANSCEIVE..10
    …… get_file id : 03 6f
    039D

    ..Sending key_settings:…. :
    PCD_TRANSCEIVE.. 20
    …… get_key settings : 02 45
    02000F01

    ..Sending key_version:…. :
    PCD_TRANSCEIVE.. 18
    …… get_key version: 03 64 00
    030000

    ..Sending sel_picc second time:…. :
    PCD_TRANSCEIVE.. 1E..10
    …… get_select picc app : 02 5a 00 00 00
    0200

    ..Sending authentication:…. :
    …… get_auth-00: 03 0a 00
    mi_ok …..= 030A00000052823A80BA5451D6501105
    ..Sending end….. :

    Please note that for the last command i have not received any “PCD_TRANSCEIVE”.This debug data is for knowing how many bits received after sending command to card.So,in the last the data representing is the previous data filled in that buffer.The card has not responded at all.
    So,please help me in sorting out this issue.

    –praveena

    • Mustafa Moripek

      Hi Praveena,
      I don’t understand anything from what you have
      written.Please Write the whole log in form challenge
      and response following each other.If you authenticate
      with 0A you get as response AF and 8 bytes RndB.
      If something wrong happens then you get an error message.
      Mustafa

      • harsha javagal

        Hi Mustafa,

        Can we write the DESFire with both IsoDep and NDEF format. I want to store the data in ISodep and store the weblink using NDEF.

  • harsha javagal

    HI Mustafa,

    I am trying to change the PICC key and getting 1E error.

    rndA –> 0000000000000000
    rndB –> response of 0A00

    rndB = decrypt of rndB with key 00000000000000000000000000000000
    rndb is leftshifted, xor with rndA and decrypted

    Session key = first 8 bytes of rndA + first 8 bytes of rndB

    old key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    new key = 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff ff

    old and new key xored and crc calculated and appended to new key

    padding of 00 00 00 00 00 00 is appended to get 24 byte

    block 1 of 8 bytes is xor with iv and decrypted with session key

    block 2 is xor with result 1 and decrypted with session key

    block 3 is xor with result 2 and decrypted with session key

    the results are appended

    the command C4 00(picc) + result gives 1E error

  • harsha javagal

    I have changed the PICC master key to 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31.

    How to authenticate with this key. I tried to use this in decrypting and encrypting on rndA and rndB. it is giving AE error. Please help

  • harsha javagal

    I am trying to change PICC master key settings and geting iE error

  • Nikos

    Hello,
    I am working on a J3D081 card with DESFire emulation. This card has some pre-personalisation steps in order to make the card work before fusing the card. I have bought some test cards so this pre-personalisation step is done by me.

    I have tried fusing a card to work only with DESFire and ignore any other ISO 14443 APDU commands. By doing this, I am able to create a DESFire tag that I can read and write NDEF on this tag.

    For next step, I fused another chip with pre-personalisation steps to work both as ISO 14443 card and DESFire emulation. The distinction happens at command dispatcher level. If the first command is ISO command then JCOP is engaged otherwise if first received command is DESFire (native or wrapped) then DESFire gets to answer.

    So what happens now is that with the J3D081 card which is configured to handle both ISO 14443 and DESFire commands, I am not able to use any of the available Android application for DESFire found on Play Store. Like for example “NFC TagInfo” from “NFC Research Lab”, which says that “PICC level not authenticated” error message.

    Other NFC applications like TagInfo from NXP using the same card say that “PICC Level AID 000000, Key configuration unavailable (Command aborted)”.

    The weird thing is that when I try to authenticate using a custom Android app that I have develop, I complete the authentication process successfully. I have even successfully managed to change key (not for PICC but for NDEF tag app with AID 000001).

    I am using Motorola Nexus 6 (NFC chip by Broadcom) with Android 6.0.1. I tried also Galaxy Nexus device with Android (with NXP chip) which has even worse results. For example with Galaxy Nexus NFC TagInfo app says “Communication interrupted” before even trying to read Mifare memory contents.

    Thanks in advance.

  • harsha javagal

    Hi Mustafa,

    Can you please tell me how to reset the PICC master key to default key?

    • Mustafa Moripek

      Hi Harsha,
      The Desfire default key is all zeroes and the
      crypto algorithm is DES.If you want to use
      this setting you have to use change key
      command.

  • Hulusi Gürel

    Hi every body,
    I got a problem about writing data to a standard file.
    Following selection of the related application and authentication successful I try to write a few data to a file already created:
    I encrypt 12 byte of data + 2 byte CRC + 2 * 0x00 => 16 bytes data with 3DES and send it to PICC. I receive always 0xAF as response. No way to store my data.
    Any hint from you ???

    Tahnks a lot.

  • Exploring the university’s canteen payment card | rothbucket

    […] to another blog, the commands that are used to communicate with the NFC-tag are hexadecimals, passed as bytes, to […]

  • Jaydevsinh

    hi

    I have some doubts about new(fresh) mifare desfire EV1 card,

    (1) what is default PICC level master key and key version?
    (2) Is there any default application is present in new Desfire card, if yes then what is the AID?
    (3) what is the default key setting for PICC level, to execute Getapplication or CreateApplication command requires authentication with PICC level master key or not?
    (4) Is there any difference between procedure for PICC level master key authentication and application level key authentication.

    Thanks & Regards,
    Jaydevsinh

    • Shehzad

      Hi Jaydev,

      This may help you.

      (1) what is default PICC level master key and key version?
      – Default master key is AID=0x00 and the key number for the master key 0x00.

      (2) Is there any default application is present in new Desfire card, if yes then what is the AID?
      – No there aren’t any.

      (3) what is the default key setting for PICC level, to execute Getapplication or CreateApplication command requires authentication with PICC level master key or not?
      – CreateApplication, GetApplicationID, GetDFNames & GetKeySettings are are permitted without master key authentication.

      (4) Is there any difference between procedure for PICC level master key authentication and application level key authentication.
      – No. The procedures differ for the type of key i.e. DES, AES etc.

  • Ramy

    hi thanks for this usefull post,

    i read the mifare defire short datasheet , and they say that the commands are available on the below data sheet
    ###########################
    Data sheet — MF3ICD81 MIFARE DESFire EV1, document number: 13403**1.
    ###########################

    but i didnt find this datasheet anywhere , on nxp site or on the internet

    how can i get the Desfire ev1 2k Commands Datasheet

    Thanks in advance

  • yastahaa

    Excuse me, i have successful for authentication on mifare desfire with 3DES (Single DES). And then i has success full read and write data to application in mifare desfire in plain communication setting. I want change to enciphered commmunication with communication setting is 0x03. I want to enciphered communication using 3DES (Single DES) encryption and decryption. So, i have follow mileaux step but i change algorithm from AES to Single DES and i am using crc16.

    1. CRC16 Calculation over
    ->’cmd+fileNo+offset+length+data’
    2. Append CRC16 to the data only without command, fileNo, offset and length.
    -> ‘data+CRC16’
    3. Padd the ‘data+CRC16’ with 0x00 (NOT 0x80, 0x00…) to a multiple of 16 Bytes, if needed.
    -> ‘data+CRC32+Zeropadding’
    4. Encrypt ‘data+CRC16+Zeropadding’ with Single DES
    -> crypted( ‘data+CRC16+Zeropadding’ )
    5. Send to the PICC
    ->’cmd+fileNo+offset+length + crypted(data+CRC16+Zeropadding)’

    write command :
    ff 00 00 00 1c d4 40 01 3d 00 00 00 00 11 00 00 8a 2b c7 21 23 24 47 73 1c c6 06 db b5 18 cd 90 00

    when i Write data to PICC, i get response from PICC :
    D5 41 00 af 90 00

    when i read data to PICC, i get response from PICC :
    24 byte message length of data,

    d5 41 00 00 b1 5a 37 2e ff e6 a0 f2 c1 6a 35 04 d9 db fe c6 21 f5 62 cc 1f 32 fb 24 90 00

    from this message i cannot get plain data back from Single DES decryption result.

    what is the wrong ?
    please help me to solve this problem…
    thanks….

  • Hermann Zheboldov

    Hello,
    Can anybody tell me how I can convert any SamAV1 key to 2K3DES? I know, that appropriate byte of the abdu can be equal 0x00 for 3DES, 0x10 for Mifare, 0x20 for AES128 and 0x30 for 3K3DES but I can not find the value for 2K3DES.

    Thanks in advance

  • Hermann Zheboldov

    Hello,

    I tried to authenticate to Desfire card using SAM AV2 module in SAM AV1 compatibility mode.
    Starting data:
    Key AES128, KeyNo = 0x14, KeyData = 00000000000000000000000000000000, IV = 00000000000000000000000000000000.

    1. I send AA 00 command to the card and received the following:

    AF 9F 6E DD 56 86 6E C4 EA A6 38 9C D1 70 31 39 E1

    After decryption we can see RndB key:

    C6 35 29 DF FC 4A 93 FD BB 91 9A F3 FD 65 BD C3

    2. I send received data to the SAM module:

    80 0A 00 00 12 14 00 9F 6E DD 56 86 6E C4 EA A6 38 9C D1 70 31 39 E1 00

    and receive the answer which I send to the card:

    9C 5F 7F 4E FB 77 75 4F BB BC EC 97 4F B8 FD 29 80 E8 4B BA B6 8C 36 AF 5D 77 46 A2 CD 31 D9 D9 90 AF

    If dechiper this data using Initial Vector = 9F6EDD56866EC4EAA6389CD1703139E1, we can get RndA key

    RndA = 00905A88DBBCD5CAD5577B8C6854F446

    and shifted 1 byte left RndB:

    3529DFFC4A93FDBB919AF3FD65BDC3C6

    The card sends me the following string:

    00 03 7C A0 C1 17 CD CF 83 F9 28 EC 92 AB 9C 7F 1A

    After its decryption we can see shifted one byte left RndA key:

    905A88DBBCD5CAD5577B8C6854F44600

    It seems that all is Ok, but when I send the cryptogram to the SAM module

    80 0A 00 00 10 03 7C A0 C1 17 CD CF 83 F9 28 EC 92 AB 9C 7F 1A

    The answer from the module always the same:

    90 1E

    That means “CRC or MAC does not match data” and I don’t understand what error I made during authentication process. Maybe I need ещ ьфлу some additional settings of the SAM key or application key? Or something else?

  • Elmue

    I wrote the first Desfire EV1 library ever for the Arduino family. But the code is multiplatform. With few changes you can even compile it on Visual Studio. You find it in my article on Codeproject: http://www.codeproject.com/Articles/1096861/DIY-electronic-RFID-Door-Lock-with-Battery-Backup

    And additionally I published an extension to Ridrix blog! The examples here are not enough and outdated. I published examples for ISO and AES authentication and key change here: http://stackoverflow.com/questions/38283998/desfire-ev1-communication-examples

  • Hammad

    hi mustafa,
    i have problem with changing key, i created application with CAAD00020F05 and for changing 01 KeyNo i successfully authenticated with 0A00 but i am getting integrity error. I am following document from M075031_desfire.pfd from http://read.pudn.com/downloads165/ebook/753406/M075031_desfire.pdf

    writing my log below.

    old key : 0000000000000000
    new key : 12345678123456781234567812345678
    CRC16 (new key) : 03B8

    C4 + 01 + (Xored new key with old key) 12345678123456781234567812345678 + 03B8(CRC16 of Xored data + 03B8(CRC16 of new key) + 00000000(0 padding)

    Final command : C4011234567812345678123456781234567803B803B800000000

    enrypted to send : C4014A438AC15D8074B58244AE0E7477AF789DC8CB5257B16F98

    it gives me integrity error.
    quries:
    1) Why it takes me to add CRC16 two times(page 38).
    2) which padding to use (0 padding OR 80 padding) as 80 padding mensioned earlier in PDF.
    3) may be the tool i am using to encrypt command not correct but as i am successfully authenticating the key by encrypting with same tool so it seems something wrong with my process.
    4) how to use three cryptogram block chaining.

    Can u please make a full step wise command for me with above new key, Response would be really appreciated.

    thanks and regards,
    Hammad

  • Shehzad Ansari

    Hi Mustafa,

    Need to ask about Plain+MACed communication with AES crypto.

    Suppose the number of data bytes, to be written to a file, are more than 52; let us say 200 bytes,
    then:
    (1) Then what would be the 1st and the 2nd frame of WRITE command?
    (2) Does CMAC needs to be calculated for individual frames separately?

    What I understood is:
    (1) For 1st frame CMAC will be calculated on:
    [cmd + fileno + offset + length + data to write]
    Here this length will be 200 bytes and data to write would be first
    52 bytes (or 46 bytes if we consider 8 bytes of CMAC ).

    (2) For the 2nd frame CMAC will be calculated on:
    [ AF + data to write ]
    Here, this data to write will be 59 bytes (or 51 bytes if we consider 8 bytes of CMAC).

    Please help me out, I am confused with the implementation.

    Regards,

  • Mustafa Moripek

    Hi Shehzad,
    When sending data to PICC you will chain the data.
    When chaining, you append the CMAC at the
    end of the last frame.The first frame looks like
    as follows :
    3D (cmd)(1 byte) + File No. (1 byte) + Offset (3 bytes) +
    Length (3 bytes) + Data (1 up to 52 bytes)
    Following frames should look like :
    AF + Data (1 up to 59 bytes)
    The last frame should look like :
    AF+ Data (1 up to 59 bytes) + padding + CMAC
    Don’t forget the padding if it doesn’t fit to
    multiple of eight bytes. CMAC you have to calculate over
    cmd + file no. + offset + length + overall data + padding

Leave a reply to Zack Cancel reply