Home
Cryptographic functions in a smart card
Contents
1. The parameters in the data field are incorrect resp APDU LE 0 resp APDU LEN SIZE SW RESPONSE resp APDU SW1 0x6A resp APDU SW2 0x80 jelse for i 0 i lt SIZE KEY AES i key i com APDU data field i aes256 init amp ctx key for i 0 i lt N i for j 0 j lt SIZE BLOCK AES j buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j aes256 encrypt ecb amp ctx buf Encrypt data for j 0 j lt SIZE BLOCK AES j resp APDU data field i SIZE BLOCK AES j response APDU resp APDU 90 UM uM sw H F w Final Degree Project Antonio Bustos Rodr guez s buf j aes256 done amp ctx resp APDU LE SIZE BLOCK AES N resp APDU LEN SIZE BLOCK AES N SIZE SW RESPONSE resp APDU SW1 SW1 SUCCESS resp APDU SW2 SIZE BLOCK AES N BK RR ko k ko kok kok kok kok kok ke ke ke A A ke A A ee ck Ck ck k ck k ck k ck ck ck a A J BRK RR KK KKK kok ok kok ok AK A ok ko kok k kok o kok k AA k kok k kok I ke e kk Routine to check some parts of command APDU CLA 0x80 INS 0x09 Pl number blocks to copy like Encrypt2 void do AES NotEncrypt2 command APDU com APDU response APDU resp APDU uint8 t key SIZE KEY AES uint8 t buf SI
2. public static final int INS_AES_DECRYPT 6 public static final int INS_AES_DECRYPT_V2 7 public static final int INS SHAl 2 public static final int INS_SHA256 2 public static final int INS_SHA512 2 public static final int INS_DETAILS 12 public static final int INS SIMPLE APDU WITHDATA 5 public static final int INS SIMPLE APDU WITHDATA V2 9 public static final int INS SIMPLE APDU 3 public static final int INS AES NOT ENCRYPT 13 private static long tl private static long t2 Establish a connection with the smart card reader Qreturn Card xy public static Card connectCard TerminalFactory factory List CardTerminal terminals CardTerminal terminal Card card null tryl factory TerminalFactory getDefault terminals factory terminals list System out println Terminals terminals terminal terminals get 0 card terminal connect T 1 System out println card card Jcatch CardException exl System out println exl getMessage System exit 1 return card Disconnect the card param card public static void disconnectCard Card card try card disconnect false Jcatch CardException exl System out println exl getMessage System exit 1 Establish a channel with the smart card reader return CardChannel public static CardChannel establishChannel
3. void aes mixColumns uint8 t buf register uint8 t i a b Cc d e for i 0 i lt 16 i 4 a buf il b buf i 1 c buf i 2 d buf i 3 e a b c d buf i e rj xtime a b buf i 1 e rj xtime b c buf i 2 e rj xtime c d buf i 3 e rj xtime d a aes mixColumns e E E Ef void aes mixColumns inv uint8 t buf register uint8 ti a b c d e x y z for 1 07 1 lt 16 1 4 a buf i b buf i 1 c buf i 2 d buf i 3 e a b c d z rj xtime e x e rj xtime rj xtime z a c e rj xtime rj xtime z b d buf i x rj xtime a b buf i 1 y rj xtime b c buf i 2 x rj xtime c d buf i 3 y rj xtime d a aes mixColumns inv S san ees seeasasse esse ee Soe ee eee eo eee ee void aes expandEncKey uint8 t k uint8 t rc register uint8 t i k 0 rj sbox k 29 rc k 1 rj sbox k 30 k 2 rj sbox k 31 k 3 rj sbox k 28 rc F rc for i 4 i lt 16 i 4 k i k i 4 k i 1 k i 3 k i 2 k i 2 k i 3 k i 1 k 16 rj sbox k 12 k 17 rj sbox k 13 k 18 rj sbox k 14 k 19 rj sbox k 15 for i 20 i lt 32 i 4 k i k i 4 k i 1 k i 3 k i 2 k i 2 k i 3 k i 1 aes expand 4 EncKey void aes expandDecKey uint8 t k u
4. The parameters in the data field are incorrect resp APDU LE 0 resp APDU LEN SIZE SW RESPONSE resp APDU SW1 0x6A resp APDU SW2 0x80 jelse aes256 init amp ctx key for i 0 i lt N 1 for j 0 j lt SIZE BLOCK AES j buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j aes256 decrypt ecb amp ctx buf Decrypt data for j 0 j lt SIZE BLOCK AES j resp APDU data field i SIZE BLOCK AES j buf j aes256 done amp ctx resp APDU LE SIZE BLOCK AES N resp APDU LEN SIZE BLOCK AES N SIZE SW RESPONSE resp APDU SW1 SW1 SUCCESS resp APDU SW2 SIZE BLOCK AES N J BK RR RK kok kok kok kok kok kok Ae A AS J BRR RR kok ko kok kok kok kk A A ek A A ke A ke ee ck Ck ck k ck k ck ck ck ck ckck KK ES byte input block Routine performes AES More data transmit ina Can be used for A CLA 0x80 ncryption on an SIZI ES encryp INS 0x08 E BLOCK Al APDU improved t and internal authentica ce Pl dataln length SIZ E KEY A ES ES SIZE BLOCK Ai CX command_APDU com_A PDU i KEY A void do AES Encrypt2 aes256 context c uint8 t key SIZE _ uint8 t buf SIZE _ B S OCK Al p S i Jj N N com APDU P1 if N gt MAX N BLOCKS Al ES
5. Final Degree Project Antonio Bustos Rodr guez resp APDU data field 1 cal ref timer2 resp APDU data field 2 overflow J BRR RK ko kok kok kok kok kok Ae kok ee Ae A ke ke ke ee k Ck k Ck ck Ck ck ko kckckck oko J BR RR kok ko kok kok k kok ok kok ke ke ke A A A ke A A A A Ae ck Ck k k ck k ck k ck ck kck oko Routine to check some parts of command APDU CLA 0x80 INS 0x05 Pl size dataIn void test command withData command APDU com APDU response APDU resp APDU int N com APDU P1 for int i 0 i lt N itt resp APDU data field i com APDU data field i resp APDU LE N resp APDU LEN N SIZE SW RESPONSE resp APDU SWl1 SW1 SUCCESS resp APDU SW2 N J BR RR k kok kok kok kok kok kok AS J BRK RR oko ok kok kk kok kok RARA RRA k kok k ok k k kok k kok k kok kk Ok k kok k kok RRA k k kok ek k e ke e kk Routine performes AES decryption on an SIZE BLOCK AES byte input block CLA 0x80 INS 0x06 Pl length key plainText dataIn void do AES Decrypt command APDU com APDU response APDU resp APDU Extract dataIn from com APDU Call function encrypt with the dataIn and dataOut aes256 context ctx uint8 t key SIZE KEY AES uint8 t buf SIZE BLOCK AES i for i 0 i lt SIZE_KEY AES i key i com APDU data field i for i 0 i lt
6. x kk kk wA Pl P2 LC data _field INPUT_BUFF _field INPUT_BUFF ER_SIZ ER_SIZ 3 4 Global variables defined in some implementation file GLOBAL FUNCTIONS defined in some implementation file fendif Match the re definition guard T1_Comm_Lib h 8 AKI k ck ck ckck oko IAIK IAIK IAIK IAIK IAIK IAIK IAIK IAIK XRO 0X E n decrypti DO NOT MODIFY on his is the implementation of a basic smart card OS supporting the T 1 protokoll his version supports AES128 encryption and ck ck ck ck ck Ck ck ck ck ck ck Ck Ck A KA A KA ZA AK AA AA ZA KK AX AA KA KAZ AK AA KA KAZ ZK ko ko ko ko KK KEKKK KK AKA A KA KAZ A K A A AA KA KAZ ckockck ck ckckckck kckck k k kk File T1 functions h AX F FX Version 1 Last chang Author s 0 e 28 10 2005 Herbst Christoph CKCkCk ck k kk kc kckck kc kckckckckokckokckokckok ko ke ke ke ke e x 99 a Final Degree Project Antonio Bustos Rodr guez s ifndef T1 functions define T1 functions include globals h void send ATR void int request extended BWT response APDU send APDU char extension factor unsigned char receive APDU command APDU received APDU void send APDU response APDU send APDU endif 100 Fin
7. Incorrect application CLA parameter of a command If there is an error selecting the command the respond APDU is made up with the status word 6E 00 command not allowed invalid instruction byte Otherwise the command is selected successfully main c In this file appears the source code to execute every time the smart card is connected to a smart card reader 53 F RN M Final Degree Project Antonio Bustos Rodr guez At first the structure command APDU called rec APDU and the structure response APDU called res APDU are initialized The next loop waits sending an ATR Answer to Reset at least 400 cycles The main endless loop waits to receive a command APDU with the function receive APDU When a command APDU is received the return code of the last function has to be checked to prevent a Checksum error If there is an error the response APDU res APDU with the status word 67 01 incorrect length or address range error is returned If the receipt of the command APDU is successfully the function command Handler functions smartcard c is executed with the arguments as pointer rec APDU and res APDU The response APDU res APDU is sent out to the smart card and the variables of the structure res APDU are initialized to default values to repeat another time the endless loop External dependencies The files that make up this section are mostly header files included in the previou
8. com APDU P1 1f N gt 0 686 N lt 15 resp APDU LEN 2 resp APDU LE 0 91 TAS E 2 5 Final Degree Project Antonio Bustos Rodr guez resp APDU SW1 0x6A resp APDU SW2 0x88 jelse overflow 0 DDRB OxFF use all pins on PORTB for output TCNT1L 0x00 start value of T C1 low byte TCNTIH 0x00 start value of T Cl high byte TCCRIA 0 T C1 in timer mode TCCRIB 1 prescale ck cal ref timerL TCNT1L cal ref timerH TCNT1H Code to measure for i 0 i lt N i buffer i com APDU data field i cal ref timer2L TCNT1L cal ref timer2H TCNT1H if TIFR amp 0x04 0x04 overflow 1 cal ref timer2L 0x00 cal ref timer2H 0x00 resp APDU LEN 7 Z 245 resp APDU LE 5 resp APDU SW1 SW1 SUCCESS Ox9F resp APDU SW2 5 data field 0 cal ref timerH data field 1 cal ref timerL data field 2 overflow H O 0 I D U FU u N data field 3 cal ref timer2H data field 4 cal ref timer2L O G V U QG G E EU U C J BRR KR kk kk kk kk A A A ck kc k Ck A kCk KCk KCk KCk KCk kCk k ck k ck k ck kc kck a KK J BRR RR Ke kk Ck CKCkCkCkCKCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCk Ck k Ck Ck ck k ck k ck k ck ck ckck ko Routine performes AES encryption on an SIZE BLOCK
9. do AES Encrypt withTimers function This function measures the number of clock cycles necessary to encrypt 16 Bytes of input plain text with a key 32 Bytes of a key returning 16 Bytes of cipher text as output and the values of the timers The timer counter 1 is used to measure the clock cycles The class of the command APDU expected is 0x80 and the instruction is 0x0B The parameter 1 and the parameter 2 are not reguired to have any value The data field of the command APDU has to contain 16 Bytes of plain text to encrypt and the 32 Bytes of the key At the first the array of unsigned integer key and buf are created with a length of 32 Bytes and 16 Bytes respectively The key used in the encryption is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU The plain text to encrypt is stored in the array buf and it is composed of the next 16 Bytes after the first 32 Bytes In the subsection Encrypt class appears the structure of the command APDU The timer counter 1 is initialized with the next values DDRB OxFF TCNTIL 0x00 TCNTLH 0x00 TCCRIA 0 TCCR1B 1 The register DDRB is set up to use all the pins on PoRTB 8 bit bi directional I O port for output The registers TcnT11 low byte and TCNT1H high byte is set up to O to start value of timer counter 1 because the timer 1 is a 16 bit timer and it has 2 regi
10. public static byte concatenateArrayByte byte key byte plainText byte ret new byte SIZE KEY AES plainText length int i for i 0 i SIZE KEY AES i ret i key il for i SIZE KEY AES i SIZE KEY AES plainText length i ret i plainText i SIZE KEY AES return ret End Functions java Cryptographic applications on the smart card AES encryption and decryption Source files aes32 c Byte oriented AES 256 implementation All lookup tables replaced with on the fly calculations Copyright c 2007 2009 Ilya O Levin http www literatecode com Other contributors Hal Finney Permission to use copy modify and distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies HE SOFTWARE IS PROVIDED AS IS AND TH E T AUTHOR DISCLAIMS ALL WARRANTII WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR A W El un NY SPECIAL DIRECT INDIRECT OR CONSEOUENTIAL DAMAGES OR ANY DAMAGES HATSOEVER RESULTING FROM LOSS OF USE DATA OR PROFITS WHETHER IN AN ACTION OF CONTRACT NEGLIGENCE OR OTHER TORTIOUS ACTION ARISING OUT OF OR IN CONNECTION WITH THE USE OR P
11. Decrypt2 class This class has the same functionality than Decrypt class The difference is that in Decrypt class in a command APDU only is sent the key 32 Bytes and the 16 Bytes of cipher text concatenated in the data field while in Decrypt2 class can be send more than 16 Bytes of cipher text in the data field of a command APDU This is the same idea than in Encrypt2 class The maximum length of cipher text to send is 224 Bytes because the key 32 Bytes has to be sent too in the same command APDU and it is not possible to send more than 256 Bytes in the data field of acommand APDU As a result the execution tests of Decrypt2 it is impossible to send more than 96 Bytes of cipher text in one command APDU because there is a memory overflow in the smart card Unknown error Ox6f7 At the first a communication channel is established with the smart card For AES decryption it is necessary as parameter a key 32 Bytes and the cipher text at most 96 Bytes The cipher text is read from the file called C TMP output encrypted and the key is read from the file called c TMP key The method readFile Functions java is used to read the data from a file and save it as array of bytes If the cipher text is higher than 96 Bytes each sequence of cipher text of 96 Bytes is sent separately in the data field of its appropriate command APDU in blocks of 16 Bytes In each command APDU the key and the cipher text are concatenated because the
12. aes256 content aes256 init amp ctx key for i 0 i lt N 1 for j 0 j SIZE BLOCK AES j buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j aes256 decrypt ecb amp ctx buf for j 0 j SIZE BLOCK AES j resp APDU data field i SIZE BLOCK AES j buf j aes256 done 8ctx Finally the header of the response APDU resp APDU is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of data available to read in the data field The variable LE contains the value of the size of the data field SIZE BLOCK AES N and the variable LEN contains the sum of the value LE and the size of a status word 2 The data field was filled in the last loop do_AES Encrypt2 function This function can encrypt until 96 Bytes in blocks of 16 Bytes of input plain text with 32 Bytes of a key returning the clear text as output The class of the command APDU expected is 0x80 and the instruction is 0x08 The parameter 1 contains the number of blocks of 16 Bytes with plain text as maximum 6 The parameter 2 is not required to have any value The data field of the command APDU contains the plain text to encrypt in blocks of 16 Bytes as maximum 96 Bytes and 32 Bytes of the key In the subsection Encrypt2 class appears the structu
13. if plainText length SIZE BLOCK AES MAX N BLOCKS AES 0 N for int i 0 i lt N itt int a i SIZE BLOCK AES MAX N BLOCKS AES int b i 1 SIZE BLOCK AES MAX N BLOCKS AES if plainText length lt b plainTextBuf new byte plainText length al for int j 0 j plainText length a J plainTextBuf j plainText j a selse plainTextBuf new byte MAX BYTES AES for int j 0 j lt MAX BYTES AES j plainTextBuf j plainText j i MAX BYTES AES 75 UM uM svie H F Final Degree Project Antonio Bustos Rodr guez s try dataIn concatenateArrayByte key plainTextBuf int Pl dataIn length SIZE KEY AES SIZE BLOCK AES System out println Pl P1 data0ut sendAPDUwithData CLA INS AES NOT ENCRYPT V2 P1 0 dataln channel if plainTextBuf length dataOut length System out println Error in the data field received the length is not the same as expected break time getTimeExecution catch NullPointerException ex1 System out println exl getMessage System exit 1 jelse dataIn concatenateArrayByte key plainText int Pl dataIn length SIZE KEY AES SIZE BLOCK AES System out println P1 P1 dataOut sendAPDUwithData CLA INS AES NOT ENCRYPT V2
14. Example runtime Encrypt class with 64 Bytes as plain text Average of 10 iterations 1340 7 milliseconds 55 LS om Final Degree Project Antonio Bustos Rodr guez 1345 1344 1343 1342 1341 1340 1339 1338 1337 1336 Milliseconds ms Iterations Example runtime Encrypt2 class with 64 Bytes as plain text Average of 10 iterations 1139 3 milliseconds 1140 2 1140 1139 8 1139 6 1139 4 1139 2 1139 1138 8 1138 6 1138 4 Milliseconds ms Iterations Example runtime Encrypt class with 96 Bytes as plain text Average of 10 iterations 1998 9 milliseconds 2000 5 2000 1999 5 1999 1998 5 1998 1997 5 1997 1996 5 1996 1995 5 Milliseconds ms Iterations 56 goin A 2 Final Degree Project Antonio Bustos Rodr guez Example runtime Encrypt2 class with 96 Bytes as plain text Average of 10 iterations 453 5 milliseconds 455 5 455 454 5 454 453 5 453 452 5 452 Milliseconds ms Iterations Runtime of Encrypt class and Encrypt2 class The below statistics are made with real data until 320 Bytes of plain text Each value is calculated from 10 iterations of runtime The stat of Encrypt class has a constant slop because the data field of the command APDU always has the same size but the larger the plain text to encrypt the greater the number of commands APDU sent However Encrypt2 class does not work in the same way than Encrypt class be
15. Oxd5 0x7a Oxa6 Oxbd 0x03 Oxcl Oxd9 0x55 Oxe6 0x54 0x36 Oxf3 Ox2f Oxde 0xc2 Oxfa Oxd9 0x8b 0x68 0x65 Oxed 0x8d Oxbc 0xb3 Ox3f 0x13 0x67 Oxb4 Oxad 0x T5 0x29 0x18 0xd2 Oxcd 0x07 0x80 Oxb5 Oxc9 Ox2a 0x53 Ox77 0x21 Ox6f Oxab 0x47 0x72 0xf7 0x31 0x05 0xb2 Ox5a Ox2f Oxbl 0x58 0x33 Ox9f 0x38 Oxf3 0x44 0x19 0x90 0x0b 0x24 Oxe4 0x4e Oxae Oxb4 0x8b Oxf6 0x1d 0x8e 0x28 0x42 Oxbb Oxab 0xd7 Oxff 0xe9 0x23 0xc3 0x24 0xd1 0x98 Oxb6 Oxb9 0x9d 0xd3 0x45 OxOf 0x8a Oxdc Oxe6 0x35 Oxdf Oxc5 Oxbe 0x79 Ox5a 0xc7 Oxec Ox4a 0x9c Oxf5 0x99 Oxd6 0x0c Oxc5 Ox76 Oxf0 Oxc0 Oxct 0x15 0x9a 0x75 Oxa0 0x84 Ox5b Oxcf 0x85 Oxa8 Oxf5 0xd2 0x17 0x73 0x88 Oxdb Ox5iG 0x79 0xa9 0x08 0xc6 0x8a 0x0e 0x9e 0x94 Oxdf 0x68 0x16 0x38 Oxfb 0x87 Oxcb 0x3d 0x4e 0xb2 0x25 0x16 0x92 Oxda 0x84 0x0a 0x06 0x02 0x6b Oxea 0x73 0x85 Ox6e 0x89 Oxib 0x20 Oxf4 0x31 Ox5f Ox0d Oxef Oxb0 0x61 0x26 0x7d 82 UM Un aM 5 Final Degree Project Antonio Bustos Rodr guez define rj sbox x sbox x define rj sbox inv x sboxinv x else tableless subroutines uint8 t gf alog uint8 t x calculate anti logarithm gen 3 uint8 t atb 1 z
16. Y etsinf NERS x lao SS VW RUNA MASARYK UNIVERSITY FACULTY OF INFORMATICS UNIVERSITAT POLIT CNICA DE VAL NCIA ESCOLA T CNICA SUPERIOR D ENGINYERIA INFORM TICA Cryptographic functions in a smart card Final Degree Project Antonio Bustos Rodr guez 2009 2010 Brno This Project consists from setting up development environment for a particular class of smart cards and developing cryptographic application that will demonstrate smart card capabilities TAS E Re b Final Degree Project Antonio Bustos Rodr guez Contents Introduction pec X 4 A AA couse EAE a case cies uous easeapeet xvuboek ances EE EEE 4 Command APD U reinis redate aaien her egeo aix iore oi eoa ae nte e ets eate TREE KRS 4 Response APD U e D 5 TRANSMISSION protocols etai ta ee cd cas cento ai 6 Communication with smart cards sess enne nsii nnne enne 7 Java Card Technology c E 7 MAU SO iwa 7 Answer to reset ATR ia 8 Advanced Encryption Standard AES c ccccsccccccsssceceessececeessececeeseeeeceesaeeeceesaeeeceesaeeeeeesaeeeeees 9 Electronic codebook ECB iza 9 AVR timers counters aza 10 Timer Counter Oi aida 10 Se Ua AA p RE ERREUR 11 Objectives and Work plan das 13 Materialsanamethod ii iii 15 ATOOSSS 1S X M 15 ATmegal1063 oe oes a las 16 PC UW CD 16 Dynamite Plus Smartcard Programmer cocococcc
17. while x z atb atb lt lt 1 if z 0x80 atb Oxlb atb z return atb gf alog ay uint8 t gf log uint8 t x calculate logarithm gen 3 uint8 t atb 1 i 0 z do if atb x break z atb atb lt lt 1 if z amp 0x80 atb Oxlb atb z while i gt 0 return i gf log x uint8 t gf mulinv uint8 t x calculate multiplicative inverse return x gf alog 255 gf log x 0 gf mulinv xz uint8 t rj sbox uint8 t x 1 uint8 t y sb sb y gf mulinv x y y lt lt 1 y gt gt 7 sb y y y lt lt 1 y gt gt 7 sb y y y lt lt 1 y gt gt 7 sb y y y lt lt 1 y gt gt 7 sb y return sb 0x63 rj sbox f uint8 t rj sbox inv uint8 t x 1 uint8 t y sb y x 0x63 sb y y lt lt 1 y gt gt 7 y y lt lt 2 y gt gt 6 sb y y y lt lt 3 y gt gt 5 sb y return gf mulinv sb rj sbox inv fendif 83 oa Final Degree Project Antonio Bustos Rodr guez uint8 t rj xtime uint8 t x return x amp 0x80 x lt lt 1 Oxlb x lt lt 1 rj xtime JR Ses S o See eo U nd void aes subBytes uint8 t buf 1 register uint8 t i 16 while i buf i rj sbox buf i aes subBytes ya AA void aes s
18. for int i20 i SIZE BLOCK AES i dataOut i cipherText length dataOutBuf i Jf dataOut deletePadding dataOut writeFile C TMP output plainText dataOut disconnectCard card System out println Decryption duration time System out println Decryption succesful End Decrypt2 java SHA1 class package src2 import java io UnsupportedEncodingException import javax smartcardio public class SHA1 extends Functions public static void main String args Card card connectCard CardChannel channel establishChannel card byte dataOut byte dataIn 0x61 0x62 0x63 dataIn has to be minor than 1024B int Pl dataIn length System out println P1 Bytes sent dataOut sendAPDUwithData CLA INS SHA1 0 0 dataln Channel try String s new String dataOut UTF 8 System out println s catch UnsupportedEncodingException exl System out println exl getMessage System exit 1 System out println getHexString dataOut disconnectCard card 72 Pa F a Final Degree Project Antonio Bustos Rodr guez SHA256 class package src2 import javax smartcardio public class SHA256 extends Functions public static void main String args Card card connectCard CardChannel channel establishChannel card byte dataIn dataOut dataln read
19. int N plainText length SIZE BLOCK AES int resto plainText length SIZE BLOCK AES byte plainText2 null if resto 0 add padding int n2 N 1 SIZE BLOCK AES resto n2 plainText length plainText2 new byte n2 for int i20 i lt plainText2 length i if i lt plainText length plainText2 i plainText i jelse plainText2 i byte resto jelse plainText2 plainText return plainText2 concatenateArrayByte method This method returns a concatenated array of bytes from two arrays of bytes called key and plainText It is a simple routine to do not dirty the other classes if an array of bytes concatenation is necessary public static byte concatenateArrayByte byte key byte plainText byte ret new byte SIZE KEY AES plainText length 37 ATA x a AM Final Degree Project Antonio Bustos Rodr guez int i for i 0 i SIZE KEY AES i ret i key il for i SIZE KEY AES i SIZE KEY AES plainText length i ret i plainText i SIZE KEY AES return ret connectCard method The method connectCard establish a connection with the smart card reader the initialization of the variables necessary Card class to start to work with the smart card At first the terminals supported by the default Terminal
20. method is the most important method of the Functions class This method is the responsible to send a command APDU and return an array of bytes from the data field of the response APDU obtained The global variables t1 and t2 are initialized to calculate the runtime of the command APDU The command APDU is built with the next values in the header the variable clas defines the class the variable ins defines the instruction the variables P1 and P2 defines the parameters The array of bytes dataIn constitutes the data field The variable channel is necessary to send the command APDU to the smart card If the status word 1 of the response APDU is not 159 Ox9F the NullPointerException exception is thrown The CardException exception is caught if the card operation failed and its message is showed in the console public static byte sendAPDUwithData int clas int ins int Pl int P2 byte dataIn CardChannel channel throws NullPointerException byte dataOut null ResponseAPDU r null CommandAPDU c null tryl c new CommandAPDU clas ins Pl P2 dataln tl System currentTimeMillis r channel transmit c t2 System currentTimeMillis dataOut r getData catch CardException exl1 System out println Error sendAPDUwithData exl getMessage System exit 1 if r getSW1 159 NullPointerException ex2
21. test timer0 com APDU resp APDU break case 0x05 test command function with data test command withData com APDU resp APDU break case 0x06 Decrypt function do AES Decrypt com APDU resp APDU break case 0x07 Execute Decrypt2 AES function improved do AES Decrypt2 com APDU resp APDU break case 0x08 Execute Encrypt2 AES function improved do AES Encrypt2 com APDU resp APDU break case 0x09 Execute Encrypt2 AES function without Encrypt code do AES NotEncrypt2 com APDU 94 Pn si F Final Degree Project Antonio Bustos Rodr guez s resp APDU break case 0x0A function test timer counter1 test timerl com APDU resp APDU break case Ox0B Encrypt function with timers do AES Encrypt withTimers com APDU resp APDU break case 0x0C Return a string with the main application of the smart card detailsApps com APDU resp APDU break case 0x0D Execute Encrypt AES function without Encrypt code do AES NotEncrypt com APDU resp APDU break default resp APDU LEN 2 resp APDU LE 0 resp APDU SW1 0x6d resp APDU SW2 0x00 Command not allowed Invalid instruction byte INS break break default resp APDU LEN 2 resp APDU LE 0 resp APDU
22. 0x04 resp APDU data field 20 TCNT1L resp APDU data field 19 TCNT1H jelsel resp APDU data field 18 1 resp APDU data field 20 0x00 resp APDU data field 19 0x00 Finally in the data field of the response APDU is copied the array but which contains the cipher text obtained The header is composed with the value Ox9F Success in the status word 1 and the value 0x15 in the status word 2 number of bytes of data available to read in the data field The structure of the response APDU is showed below O SW2 TCNT1 TCNT1 TCNT1 TCNT1 Cipher text 16 Bytes H L TIFR H L Timer 1 before Timer1 after encryption encryption sw1 Ox9F 0x10 Structure of the response APDU resp_APDU detailsApps function This function returns a string encoded in UTF 8 in the data field of the response APDU resp APDU This string contents a short explanation of the features developed in the smart card The class of the command APDU expected is 0x80 and the instruction is OxOC The parameter 1 and the parameter 2 are not required to have any value The data field of the command APDU contains the description of the smart card In the array of unsigned char name appears the description of the smart card that it is copied in the next loop to the data field of resp APDU for 1 0 i lt 29 i resp APDU data field i name i Fin
23. 15 309375 208 20 69519231 15 72067308 224 20 7 15 58705357 240 20 69625 15 50166667 256 20 7 15 41757813 272 20 69522059 15 33860294 288 20 68958333 15 27048611 59 Final Degree Project Antonio Bustos Rodr guez 304 20 694 73684 15 54046053 320 20 6890625 15 4765625 The average of Encrypt class per byte of plain text sent is 20 82 milliseconds The average of Encrypt2 class per byte of plain text sent is 16 015 milliseconds Runtime NotEncrypt class and NotEncrypt2 class This statistic represents the runtime of a command APDU that executes the command do AES NotEncrypt NotEncrypt test command withData2 NotEncrypt2 class and class The command test command withData2 works on the same way than the command do AES Encrypt2 except that the encryption code is not executed The command do AES NotEncrypt works also on the same way than the command do AES Encrypt except that the encryption code is not executed This graph has the same shape than Runtime Encrypt and Encrypt2 The graph of NotEncrypt class remains lineal against the NotEncrypt2 class In this case the peaks of NotEncrypt2 are higher than in the other statistic because now the encryption code does not influence in the final runtime o c o o o 2 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 320 Runtime NotEncrypt By
24. 208 224 240 256 272 288 304 320 Runtime Encrypt code Bytes plain text Runtime Encrypt2 code The average of the encryption code per byte is 12 14 milliseconds with the command do AE S E nerypt2 61 wan Final Degree Project Antonio Bustos Rodr guez Bytes plain text Runtime Encrypt code Runtime Encrypt2 code 16 223 2016 224 32 447 7007 412 48 672 1003 597 64 897 9011 783 6 80 1117 6002 970 8 96 1340 6002 1157 6 112 1566 1003 1379 7 128 1788 0008 1567 2 144 2012 1001 1752 3 160 2235 8001 1941 176 2459 1002 2128 1 192 2685 1005 2315 85 208 2908 7004 2540 3 224 3132 8032 2722 5 240 3358 4017 2912 256 3584 7006 3099 2 272 3808 5002 3285 2 288 4032 4001 3472 304 4258 4001 3692 4 320 4482 5001 3881 2 Conclusions In agreement with the values of the statistics the difference between the runtime of the encryption code and sending the command APDU is 4 milliseconds so the most runtime of sending a command APDU to execute the command do AES Encrypt2 is spent to execute the encryption code The runtime of the encryption code is faster in the Encrypt2 class because in the command do AES Encrypt2 the structure is aes256 context initialized and released only one time to encrypt more than 16 Bytes However in the Encrypt class this structure is initialized and released once to encr
25. AES DECRYPT INS AES DECRYPT V2 INS AES ENCRYPT INS AES ENCRYPT V2 belong to the numbers of instruction of each encryption and decryption functions implemented in the smart card The variable INS DETAILS belong to the instruction to get details about the functions implemented in the smart card The variables INS SHA1 INS SHA256 and INS SHA belong to the functions to digest data in the smart card but they have never implemented The variables INS SIMPLE APDU INS SIMPLE APDU WITHDATA INS AES NOT ENCRYPT V2 INS AES NOT ENCRYPT belong to testing functions in the smart card used in the development of the previous cryptographic functions Ultimately the variables MAX BYTES AES MAX N BLOCKS AES SIZE BLOCK AES and SIZE KEY AES are used to simplify the constant values used in the encryption and decryption process The description of the methods of the Functions class appears below addPadding method This method adds padding to a array of bytes until the array would be multiple of SIZE BLOCK AES If plainText is not multiple of SIZE BLOCK AES the method returns a new array with a length multiple of SIZE BLOCK AES and with the padding added If the padding is not necessary to add the method returns the variable plainText public static byte addPadding byte plainText
26. Card card CardChannel channel null channel card getBasicChannel return channel Add padding to a array of bytes until the array would be multiple of SIZE BLOCK AES iparam plainText Greturn byte 77 UM uM svie H F w Final Degree Project Antonio Bustos Rodr guez s y public static byte addPadding byte plainText int N plainText length SIZE BLOCK AES int resto plainText length SIZE BLOCK AES byte plainText2 null if resto O add padding int n2 N 1 SIZE BLOCK AES resto n2 plainText length plainText2 new byte n2 for int i20 i lt plainText2 length i if i lt plainText length plainText2 i plainText i jelsel plainText2 i byte resto jelsel plainText2 plainText return plainText2 Deletes the padding in the dataOut array of bytes if there is padding in the array If there is not padding in the array returns the same dataOut array param dataOut return byte public static byte deletePadding byte dataOut boolean pad false int last int dataOut dataOut length 1 if last gt 0 amp amp last lt SIZE BLOCK AES pad true for int i dataOut length last i lt dataOut length 84 pad i if dataOut i last pad false if pad return dataOut jelsel int N dataOut length las
27. SIZE BLOCK AES i buf i com APDU data field i SIZ A K D 2 aes256 init amp ctx key aes256 decrypt ecb amp ctx buf aes256 done amp ctx for i 0 i lt SIZE BLOCK AES i resp APDU data field i buf i resp APDU LE SIZE BLOCK AES resp APDU LEN SIZE BLOCK AES SIZE SW RESPONSE resp APDU SWl1 SW1 SUCCESS resp APDU SW2 SIZE B OCK AES J BK RR oko ko kok kok kok kok kok kok kok Ak A kk ke ke kk ke ck k ck k ck k ck ck kckckck He J BRR RK kok kok kok kok oko k kok kok kok kok kok kok k KCk kCk KCk kCk KCk KCk KCk kCk k Ck kok k ck k ck kc kck ck a oe Routine performes AES decryption on an SIZE BLOCK AES byte input block CLA 0x80 INS 0x07 Pl dataIn length SIZE KEY AES SIZE BLOCK AES void do AES Decrypt2 command APDU com APDU response APDU resp APDU aes256 context ctx uint8 t key SIZE KEY AES 89 UM uM 5 Final Degree Project 4 Antonio Bustos Rodriguez uint8 t buf SIZl E BLOCK Al p Sl i Jj N N com APDU P1 for i 0 i lt SIZE K i EY A ES 1 key i if N gt MAX N B OCKS Al com APDU data field i ES
28. SW1 0x6e resp APDU SW2 0x00 Incorrect application CLA parameter of a command break J BRK RR KK KKK kok kok ok kok eo kok k oko ok oko kok k kok o kok k AA A A ek ke e ke e kk maln c A Kk A A A A A A A Ck k kc k Ck k k ck k ck k ck ck ck ck ckckokok E This is the implementation of a basic smart card OS supporting the T 1 protokoll he kKA kXK AK K AK AA KA KAZ A K A A KA X A KK A AZ A AZ KA KK AKA A KA KAZ AZ KA A ZA ZA ZK ck k kk KK KEKKK KK KK AA KA KAZ A K A A AA KA KAZ AKA A kckckck kckck k k kk File main c KCKCKCKCkCkCkCk Ck k Ck k Ck k Ck k k ck Ck k k ck Ck ck k ck ck ck ck ckckckokckok ok include globals h tinclude T1 Comm Lib h include functions smartcard h void main void 95 A quU A Final Degree Project Antonio Bustos Rodr guez unsigned char result 1 command APDU rec APDU response APDU res APDU for i 0 1 lt 50 i struct for command APDU struct for response APDU wait with the ATR at least 400 cycles send the Answer to Reset according endless loop to receive respond and process commands send ATR to ISO for result receive APDU amp rec APDU T 1 if result OK error code res APDU NAD res APDU PCB res APDU LEN res APDU LE res APDU SW1 receive APDU according to if EDC Checksum rror return rec APDU NAD rec APDU
29. The smart card sends an Answer to Reset ATR after the smart card is inserted in the smart card reader in other words after the supply voltage clock signal and reset signal have been applied The ATR is made up of a data string which contains various parameters related to the transmission protocol and the characteristics of the smart card This data string which contains at most 33 bytes is always sent with a divider value clock rate conversion factor of 372 in compliance with the ISO IEC 7816 3 standard In the main code of the smart card the ATR is sent at the first to send to the reader the information about the smart card but this information is provided by the external library included in the code More information in the chapter 6 2 Answer to Reset ATR p 377 from Smart Card Handbook 2004 Wolfgang Rankl and Wolfgang Effing st P 3 ye aM Final Degree Project Antonio Bustos Rodr guez Advanced Encryption Standard AES The Advanced Encryption Standard is a symmetric key encryption standard based in the principle known as a Substitution permutation network AES has a fixed block size of 128 bits and a key size of 128 192 or 256 bits but the block and the key sizes can be any multiple lengths of 32 bits The blocksize has a maximum of 256 bits but the key size has not theorically any maximum This algorithm came up as improvement of the Data Encryption Standard DES and nowdays it is used deeply and it
30. be higher than 256 Bytes maximum length of data field on command APDU Moreover the channel of the communication with smart card has to be sent on the method call The commands to calculate digest are developed in other AVR project so the instruction codes are not have to be different than the last Finally the data returned 20 Bytes on the previous method is the digest which is showed on the terminal SHA256 class This class calculates the digest of the input data with the algorithm SHA 256 implemented in the smart card It works on the same way of SHA1 class at the first establish a channel communication with the smart card reader and read the input data to digest from the file located in c TMP input To calculate the digest an command APDU is sent to the smart card with the function Y sendAPDUwithData and selects the command do SHA256 with the class 128 cla the instruction 2 INS SHA256 and the length of the data to digest in the instruction parameter 1 The length of the data cannot be higher than 256 Bytes maximum length of data field on command APDU Moreover the channel of the communication with smart card has to be sent on the method call Finally the data returned 20 Bytes on the previous method is the digest which is showed on the terminal SHA512 class This class calculates the digest of the input data with the algorithm SHA 512 implemented in the smart card It works on the same way o
31. byte addPadding byte plaintext public static void byte concatenateArrayByte byte key byte plainText int lengthPlainText public static Card connectCard public static byte deletePadding byte dataOut e public static void disconnectCard Card card e public static CardChannel establishChannel Card card e public static long getTimeExecution public static byte readFile String fileName public static sendAPDUwithData int clas int ins int Pl int P2 bytel dataIn CardChannel channel throws NullPointerException e public static void sendSimpleAPDU int cla int ins CardChannel channel e public static byte sendSimpleAPDUwithData int clas int ins CardChannel channel throws NullPointerException public static void writeFile String fileName byte data write The list of static final Integer variables is as follows e CLA e INS AES DECRYPT e INS AES DECRYPT V2 e INS AES ENCRYPT e INS AES ENCRYPT V2 e INS DETAILS e INS SHA1 e INS SHA256 e INS SHA512 e INS SIMPLE APDU e INS SIMPLE APDU WITHDATA e INS AES NOT ENCRYPT V2 e MAX BYTES AES e MAX N BLOCKS AES e SIZE BLOCK AES e SIZE KEY AES 36 ATA x a UM a Final Degree Project Antonio Bustos Rodr guez The list of private static long variables e tl e t2 The variable cra defines the number of class of the instructions on the smart card which always have the number 128 The variables INS
32. channel time getTimeExecution for int i 0 i lt dataOutBuf length i dataOut i dataOutBuf i if ov32 dataIn concatenateArrayByte key plainTextBuf2 plainTextBuf2 length dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT dataIn length 0 dataln channel time getTimeExecution for int i 0 i lt SIZE BLOCK AES i dataOut i plainText length dataOutBuf i writeFile C TMP output encrypted dataOut disconnectCard card System out println Encryption2 duration time System out println Encryption2 succesful End Encrypt2 java Decrypt2 class import javax smartcardio Class to decrypt data in the smart card with a improved way In one APDU can be send more data higher SIZE BLOCK AESB to decrypt Input files i 1 output encrypted this file contains the data to decrypt 2 key this file contains SIZE KEY AES bytes of data that contains the key Output files 1 output plainText this file contains the data encrypted Ef public class Decrypt2 extends Functions public static void main String args long time 0 boolean ov32 false 70 UM uM H Final Degree Project Antonio Bustos Rodr gu x 4 ez Card card connectCard CardChannel channel
33. depends on the block boundary to which the message needs to be extended in this case as maximum 16 plainText addPadding plainText If the plain text is higher than 96 Bytes each sequence of plain text of 96 Bytes is sent separately in the data field of its appropriate command APDU in blocks of 16 Bytes In each command APDU the key and the plain text are concatenated because the key is not stored in the smart card and each time the key is requested If the plain text is not higher than 96 Bytes the plain text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data 33 p Sgn as H ww Final Degree Project Antonio Bustos Rodr guez The length of the data field of response APDU is compared with the data field of the command APDU to verify that has the same size and the output is correct To send the command APDU is necessary to use the method sendAPDUwithData in the manner shown below The command APDU is made up of a header with the Class cra the instruction INS AES NOT ENCRYPT V2 command ao AES NotEncrypt2 ofthe smart card the instruction parameter 1 contains the number of blocks of 16 bytes that are in the data field and the instruction parameter 2 is not necessary The data field contains the array of bytes of data to send Moreover the channel of the communication with the smart card has to be sent on the method The s
34. globals h 42 om Final Degree Project o T1 Comm Lib h e External dependencies common h deprecated h fuse h inttypes h io h iomega163 h libT1 Comm Lib a lock h portpins h sfr defs h stdint h string h O O O O O O O O O o o o version h e Other files o AES encrypt decrypt Iss o AES encrypt decrypt map Antonio Bustos Rodr guez The external library used is libT1 Comm Lib a to communicate with the smart card reader using the commands APDU and responses APDU The configuration of the compilers is for the Device atmega163 smart card used in the project The configuration file of the project is attached in the appendix The images of the command APDU and response APDU used in each function appear previously in the section Interface in Java with the smart card In the structure response APDU appears the variables Li EN and L E The variable 11 7 EN refers to the length of the prologue field of the command APDU and its value is always the p length of the data field plus the 2 Bytes of the status word The variable LE refers to the length of the data field The source code of the AVR project appears in the appendix Header files aes32 h The header file aes32 h contains the declaration of the functions available to encrypt and decryption data in the smart card Also it contains the structure struct aes256 context used to store the
35. in the data field The LE variable contains the value of the size of the n data field SIZE BLOCK aEs N and the LEN variable contains the sum of the value LE and the size of a status word 2 The data field was filled in the last loop test timer1 function This function measures the number of clock cycles necessary to copy the data available in the command APDU in a local array of unsigned integer The timer counter 1 is used to measure the clock cycles The class of the command APDU expected is 0x80 and the instruction is 0x0A The parameter 1 contains the length of the data field The parameter 2 is not reguired to have any value The data field of the command APDU contains the data to copy in the local array If the parameter 1 of the header does not contains a number higher than O and smaller than 15 the response APDU resp with the status word 6A 68 referenced data not found is returned and the function ends At the first the timer 1 is initialized with the next values overflow 0 DDRB OxFF TCNT1L 0x00 TCNT1H 0x00 TCCRIA 0 TCCRIB 1 The variable overflow checks if an overflow happens between in sampling clock cycles The register DDRB is set up to use all the pins on PORTB 8 bit bi directional I O port for output The registers TCNT1L low byte and rentin high byte is set up to O to start value of timer counte
36. is 0x05 The parameter 1 contains the length of the data field The parameter 2 is not required to have any value The data field of the command APDU contains the data to copy in resp APDU The loop copies the data between the command APDU to response APDU for int i20 i N 1 resp APDU data field i com APDU data field i The status word 1 of the response APDU resp APDU is sW1 success and the status word 2 is the amount of bytes in the data field in this case the parameter 1 of the command APDU The data field contains the data copied The values LE and LEN are set up with the length of the data field and the length of the data field with the header respectively do_AES Decrypt function This function is the responsible of the simple decryption and it can decrypt 16 Bytes of input cipher text with 32 Bytes of a key returning 16 Bytes of clear text as output 46 w Final Degree Project Antonio Bustos Rodr guez The class of the command APDU expected is 0x80 and the instruction is 0x06 The parameter 1 and the parameter 2 are not required to have any value The data field of the command APDU has to contain 16 Bytes of cipher text to decrypt and the 32 Bytes of the key At the first the array of unsigned integer key and buf are created with a length of 32 Bytes and 16 Bytes respectively The key used in the decryption is stored in t
37. is read from the file called c TMP key The method readFile Functions java is used to read the data from a file and save it as array of bytes The plain text has to be multiple of 16 Bytes so padding is calculated if it is necessary The byte padding used is PKCS7 this is described in RFC 3852 The padding is in whole bytes and the value of each added byte is the number of bytes is added The number of bytes added will depends on the block boundary to which the message needs to be extended in this case as maximum 16 plainText addPadding plainText If the plain text is higher than 96 Bytes each sequence of plain text of 96 Bytes is sent separately in the data field of its appropriate command APDU in blocks of 16 Bytes In each command APDU the key and the plain text are concatenated because the key is not stored in the smart card and each time the key is requested The structure of the command APDU is showed in the next image header command APDU data field command APDU Key 32 Bytes 1 Plain text 16 Bytes Structure of the command APDU sent to the smart card Encrypt2 class If the plain text is not higher than 96 Bytes the plain text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data The output encrypted is sent in a single response APDU and the data field of that response is stored in a buffer When all the seg
38. key i com APDU data field i for i 0 i lt SIZE BLOCK AES i buf i com_APDU data_field i SIZE KEY AES for i 0 i lt SIZE BLOCK AES i 93 UM uM svie H F Final Degree Project Antonio Bustos Rodr guez s resp APDU data field i buf i resp APDU LE SIZE BLOCK AES resp APDU LEN SIZE BLOCK AES SIZE SW RESPONSE resp APDU SW1 SW1 SUCCESS Ox9F resp_APDU SW2 SIZE BLOCK AES J BK RR k k ko kok kok kok kok kok A ke A A A A ke A Ae A A ck k ck k ck k ck ck kck oko J BRR RK kok kok kok kok kok kok kok kok kok kok A ok kok A kc k kCk KCk kCk KCk kCk k Ck kc k k ck k ck ko kck a oe Main command Handler void command Handler command APDU com APDU response APDU resp APDU resp APDU NAD com APDU NAD resp APDU PCB com APDU PCB if com APDU PCB 0xC1 S Block Handling resp APDU NAD com APDU NAD resp APDU PCB OxEl1 resp APDU LEN 1 resp APDU data field 0 com APDU CLA else I Block Handling 1 switch com_APDU CLA case 0x80 switch com_APDU INS case 0x02 Encrypt function do AES Encrypt com APDU resp APDU break case 0x03 test command function test command com APDU resp APDU break case 0x04 function test timer counter0
39. new NullPointerException Error with the APDU response data returned invalid throw ex2 jelse return dataOut 40 Final Degree Project Antonio Bustos Rodr guez sendSimpleAPDU method The sendSimpleAPDU method sends a simple command APDU to the smart card The command APDU has not any data on its data field so it is built with the variables c1a that defines the class and ins that defines the instruction in the header The variable channe1 is necessary to send the command APDU to the smart card The global variables t1 and t2 are initialized to calculate the runtime of the command APDU In the console is showed a string representation of the response APDU obtained The CardException exception is caught if the card operation failed and its message is showed in the console public static void sendSimpleAPDU int cla int ins CardChannel channel tryl CommandAPDU c new CommandAPDU cla ins 0 0 tl System currentTimeMillis ResponseAPDU r channel transmit c t2 System currentTimeMillis System out println r catch CardException exl System out println exl getMessage System exit 1 sendSimpleAPDUwithData method The sendSimpleAPDUwithData method works on the same way than sendAPDUwithData The method is the responsible to send a command APDU and return an array of bytes from the data field of
40. old Dynamite Programmer dated May 2005 developed by Duolabs The new Dynamite Plus is smart card programmer with a size similar as a packet of cigarettes The Dynamite Plus works with Cas Studio software The technical information about the device is described below e Full speed USB Device at 46 MHz internal speed 17 w Final Degree Project Antonio Bustos Rodr guez e Noneed for external power supply The energy is transmited by the USB cable connection e USB 1 1 2 0 connection e Multilanguage software e Fully programmable flash firmware for future software updates The programmer supports smartcards up directly via USB The list of OS cards supported is very long and keep on being updated and it appears in the latest version of Cas Interface Studio The smart cards PrussianCard3 Funcard5 AT90S8515 24C512 and FunCard ATmega163 ATmega163 24C256 are included in the list of PIC and ATMEL AVR supported microcontrollers smartcards but the list is very long to show and keep on being updated Cas Interface Studio Cas Studio is a software specifically developed by Duolabs to use Dynamite Plus programmer Cas Studio can be executed in Windows 98 ME 2000 XP The software is able to identify the smart card connected to the smart card programmer and to self adapt to it by enabling disabling the appropriate options The application needs to be connected to the smart card programmer to start to run and when the p
41. processing speed The features of the ATmega163 are described below e 16K bytes of In System Self Programmable Flash e 512 bytes EEPROM e 1024 bytes SRAM e 32 general purpose I O lines e 32 general purpose working registers connected directly to the Arithmetic Logic Unit ALU e 3 flexible Timer Counters with compare modes e Internal and external interrupts e A byte oriented Two wire Serial Interface an 8 channel 10 bit ADC a programmable Watchdog Timer with internal Oscillator a programmable serial UART an SPI serial port and four software selectable power saving modes The On chip ISP Flash can be programmed through an SPI serial interface or a conventional programmer in the project Dynamite Plus Programmer By combining an 8 bit CPU with In System Self Programmable Flash on a monolithic chip the Atmel ATmega163 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications More details about ATmega163 microcontroller in the official document of Atmel see Bibliography PC Twin PC Twin is a smart card reader developed by Gemalto which handles all types of ISO IEC 7816 compatible smart cards The main features of PC Twin are e Atransparent design to show the inserted card e USB or Serial connection simply by cable insertion In the project case an USB connection e Modular concept with accessories stand floppy disk tray to simplify logisti
42. smart card NoEncrypt class The length of the data field of response APDU is compared with the data field of the command APDU to verify that has the same size and the output is correct Plain text 96 Bytes Structure of the response APDU sent from the smart card NoEncrypt class To send the command APDU is necessary to use the method sendAPDUwithData in the manner shown below The command APDU is made up of a header with the Class cra the instruction INS AES NOT ENCRYPT command do AES NotEncrypt of the smart card the instruction parameter 1 and the instruction parameter 2 are not necessary The data field 35 qe M Final Degree Project Antonio Bustos Rodriguez contains the array of bytes of data to send Moreover the channel of the communication with the smart card has to be sent on the method dataIn concatenateArrayByte key plainTextBuf dataOutBuf sendAPDUwithData CLA INS AES NOT ENCRYPT dataln length 0 dataln channel At the end the card is released and the runtime of sent the command APDU without execute the encryption code is showed in the console Functions class This class contains all the additional methods used by the previous classes To keep the project clean any class contains duplicated methods Also in Functions class are initialized the global variables used by the previous classes The list of methods is as follows public static
43. 198 AVRFREAKS Timer Counter Basics Design note 024 http www avrfreaks net modules FreaksFiles files 388 DN_024 pdf consulted in November 2009 ATMEL 8 Bit AVR Microcontroller with 8K bytes In System Programmable Flash AT90S8515 http www atmel com atmel acrobat doc1142 pdf consulted in November 2009 ATMEL 8 Bit AVR Microcontroller with 16K bytes In System Programmable Flash ATmega163 and ATmega163L http www atmel com dyn resources prod documents doc1142 pdf consulted in November 2009 PC Link Readers article in Gemalto web http www gemalto com products pc link readers consulted in October 2009 Dynamite Programmer Plus article in Duolabs web http www duolabs com dynamite html consulted in October 2009 DUOLABS Cas Interface 3 User s Guide May 2005 published in Internet http www qboxsvn com duolabs ManualeCas3 EN pdf consulted in October 2009 AVR Studio 4 article in Atmel web http www atmel com dyn Products tools card asp tool id 2725 consulted in November 2009 ATMEL AVR Studio 3 5 User guide 2001 http www atmel com dyn resources prod documents doc1663 pdf consulted in January 2010 Introduction article in AVR Libc web site http www cs mun ca paul cs4723 material atmel avr libc user manual 1 6 5 consulted in November 2009 Library reference in AVR Libc web site http www cs mun ca paul cs4723 material atmel avr libc user manual 1 6 5 modules html consulted in November 2009 Eclipse sof
44. 2 java e Functions java e TestAPDU java e NotEncrypt2 java e SHAl java e SHA256 java e SHA512 java In addition there is a class called Functions java where are implemented all the methods that the previous classes use The source code of the classes can be read in the appendix Encrypt class Briefly this class calls the command do AES Encrypt implemented in the smart card At the first a communication channel is established with the smart card For the AES encryption it is necessary as parameter a key 32 Bytes and the plain text multiple of 16 Bytes The plain text is read from the file called c TMP input and the key is read from the file called c TMP key The method readFile Functions java is used to read the data from a file and save it as array of bytes The plain text has to be multiple of 16 Bytes so padding is calculated if it is necessary The byte padding used is PKCS7 this is described in RFC 3852 The padding is in whole bytes and the value of each added byte is the number of bytes is added The number of bytes added will depends on the block boundary to which the message needs to be extended in this case as maximum 16 plainText addPadding plainText If the plain text is higher than 16 Bytes each sequence of plain text of 16 Bytes is sent separately in the data field of its appropriate command APDU In each command APDU the key and the plain text are concatenat
45. AES byte input block Can be used for AES encrypt and internal authenticate CLA 0x80 INS 0x0B Pl length key plainText dataIn void do AES Encrypt withTimers command APDU com APDU response APDU resp APDU Extract dataIn from com APDU Call function encrypt with the dataIn and dataOut aes256 context ctx uint8 t key SIZE KEY AES uint8 t buf SIZE BLOCK AES uint8 t i for i 0 i lt SIZE KEY AES i key i com APDU data field i for i 0 i lt SIZE BLOCK AES i buf i com_APDU data_field i SIZE KEY AES DDRB OxFF use all pins on PORTB for output TCNT1L 0x00 start value of T C1 low byte TCNTIH 0x00 start value of T Cl high byte TCCRIA 0 T C1 in timer mode TCCRIB 5 prescale ck 92 TAS E 2 5 Final Degree Project Antonio Bustos Rodr guez resp APDU data field 18 0 resp APDU data field 17 TCNT1L resp APDU data field SIZE BLOCK AES TCNT1H Code to measure aes256 init amp ctx key aes256 encrypt ecb amp ctx buf aes256 done amp ctx if TIFR amp 0x04 0x04 resp APDU data field 20 TCNT1L cal ref timer2L resp APDU data field 19 TCNT1H cal ref timer2H jelse resp APDU data field 18 1 overflow resp APDU dat
46. ATA 5 t we Final Degree Project Antonio Bustos Rodr guez AVR Studio 4 AVR Studio 4 is the Integrated Development Environment IDE for developing 8 bit AVR applications in Windows NT 2000 XP Vista 7 environments AVR Studio 4 provides a complete set of features including debugger supporting run control including source and instruction level stepping and breakpoints registers memory and I O views and target configuration and management as well as full programming support for standalone programmers The features of AVR Studio 4 are described below e Integrated Assembler e Integrated Simulator e Integrates with GCC compiler plug in e Support for all Atmel tools that support the 8 bit AVR architecture including the AVR ONE JTAGICE mkl JTAGICE mkil AVR Dragon AVRISP AVR ISPmkil AVR Butterfly STK500 and STK600 e AVRRTOS plug in support e ATIOPWM1 and ATtiny40 support e Command Line Interface tools updated with TPI support e Online help The AVR Studio offers a source code editor project manager assembler compiler interface and a debugger to develop the applications AVR libc The AVR libc package is a standard library for the C language which can be used in Atmel AVR 8 bit RISC microcontroller This library provides the basic functions to use in the C language which are necessary in the most applications for example to work with strings stdio h header file AVR libc can be freely used and redistr
47. ERFORMANCE OF THIS SOFTWARE X OX F F OX Xo F Xo Xo F Xo Xo HF FX a include aes32 h gt gt 7 1 0x1b define F x x lt lt 1 x x amp 1 0x8d 0 define FD x x gt gt 1 define BACK TO TABLES tifdef BACK TO TABLES const uint8 t sbox 256 81 AS x v Final Degree Project Antonio Bustos Rodriguez 0x63 0x30 Oxca Oxad 0xb7 0x34 0x04 0x07 0x09 0x52 0x53 Ox6a 0xd0 0x45 0x51 Oxbc Oxcd Oxc4 0x60 0x46 Oxe0 0xc2 Oxe7 0x6c Oxba Oxe8 0x70 0x61 Oxel 0x9b 0x8c 0x41 l 0x7c 0x01 0x82 Oxd4 Oxfd Oxa5 0xc7 0x12 0x83 0x3b Oxdl Oxcb Oxef Oxf9 0xa3 Oxb6 0x0c Oxa7 0x81 Oxee 0x32 0xd3 Oxc8 0x56 0x78 Oxdd 0x3e 0x35 Oxf8 Oxle Oxal 0x99 0x77 0x67 Oxc9 0xa2 0x93 Oxe5 0x23 0x80 0x2c Oxd6 0x00 Oxbe Oxaa 0x02 0x40 Oxda 0x13 0x7e Ox4f Oxb8 0x3a Oxac 0x37 Oxf4 0x25 0x74 Oxb5 0x57 0x98 0x87 0x89 0x2d 0x7b 0x2b 0x7d Oxaf 0x26 Oxfl 0xc3 0xe2 Oxla 0xb3 Oxed 0x39 Oxfb 0x7f Ox8f 0x21 Oxec 0x3d Oxdc 0x14 0x0a 0x62 0x6d Oxea 0x2e Ox1lf 0x66 Oxb9 0x11 Oxe9 0x0d OxOf const uint8 t sboxinv 256 0x52 Oxbf 0x7c 0
48. ES r S System out println Length data to decrypt cipherText length if cipherText length gt SIZE BLOCK AE int N cipherText length SIZI for int i 0 i lt N itt for int j 0 j SIZE BLOCK AES j cipherTextBuf j cipherText j i SIZE BLOCK AES dataIn concatenateArrayByte key cipherTextBuf Management exception NullPointerException dataOutBuf sendAPDUwithData CLA INS AES DECRYPT n _BLOCK_AES 0 0 dataln channel time getTimeExecution for int j 0 j lt SIZE BLOCK AES j dataOut j i SIZE BLOCK AES dataOutBuf jJ jelsel dataIn concatenateArrayByte key cipherText dataOut sendAPDUwithData CLA INS AES DECRYPT 0 0 dataln channel time getTimeExecution dataOut deletePadding dataOut Functions WriteFile C TMP output plainText dataOut disconnectCard card System out println Decryption duration time System out println Decryption succesful End Decrypt java Encrypt2 class import javax smartcardio 68 TAS E 2 5 Final Degree Project Antonio Bustos Rodr guez Class to encrypt data in the smart card with a improved way E In one APDU can be send more data higher SIZE BLOCK AE
49. Factory are collected in a list The connection is established with the first terminal of the list and with the protocol used is the block oriented T 1 protocol The details of the card connected are showed in the console and the list of the terminals supported by the default TerminalFactory are also showed by the console that are the terminals connected in the computer The method returns a Card object with the connection necessary to transmit command APDU and receive response APDU public static Card connectCard TerminalFactory factory List lt CardTerminal gt terminals CardTerminal terminal Card card null try factory TerminalFactory getDefault terminals factory terminals list System out println Terminals terminals terminal terminals get 0 card terminal connect T 1 System out println card card Jcatch CardException exl System out println exl getMessage System exit 1 return card deletePadding method The deletePadding method deletes the padding in the array of bytes called dataout if there is padding in the array If there is not padding in the array the method returns the same data0ut array At first the method checks if there are padding in aataout and if there is below it is deleted public static byte deletePadding byte dataOut boolean pad false int last int dataOut dataOut length 1 if last gt 0
50. File C TMP input maximum size dataln for SHA256 data0ut sendAPDUwithData CLA INS SHA256 dataln length dataln channel System out println getHexString dataOut disconnectCard card 0 SHA512 class package src2 import javax smartcardio public class SHA512 extends Functions public static void main String args Card card connectCard CardChannel channel establishChannel card byte dataln dataOut dataIn readFile C TMP input maximum size dataIn for SHA512 dataOut sendAPDUwithData CLA INS SHA512 dataln length dataln channel System out println getHexString dataOut disconnectCard card 0 DetailsSC class import java io UnsupportedEncodingException import javax smartcardio public class DetailsSC extends Functions public static void main String args Card card connectCard CardChannel channel establishChannel card byte dataOut dataOut sendSimpleAPDUwithData CLA INS DETAILS channel try String s new String dataOut UTF 8 System out println s catch UnsupportedEncodingException exl System out println exl getMessage 73 UM Ma ade svie F e Final Degree Project Antonio Bustos Rodr guez y System exit 1 disconnectCard card TestAPDU class import javax smartcardio public class TestAPDU extends Func
51. OCK AES j data0utBuf 3 jelsel dataIn concatenateArrayByte key plainText data0ut sendAPDUwithData CLA INS_AES ENCRYPT 0 0 dataln channel time getTimeExecution catch NullPointerException ex3 System out println ex3 getMessage System exit 1 writeFile C TMP output encrypted dataOut disconnectCard card System out println Encryption duration time System out println Encryption succesful j mc 67 UM Ma ade svie F e Final Degree Project Antonio Bustos Rodr guez y End Encrypt java Decrypt class import javax smartcardio Class to decrypt data in the smart card Input files 1 output encrypted this file contains the data to decrypt 2 key this file contains 32 bytes of data that contains the key Output files ES 1 output cipherText this file contains the plain text decrypted x public class Decrypt extends Functions public static void main String args long time 0 Card card connectCard CardChannel channel establishChannel card byte key readFile C TMP key byte cipherText readFile C TMP output encrypted byte dataIn dataOut cipherTextBuf dataOutBuf dataOut new byte cipherText length cipherTextBuf new byte SIZE BLOCK A dataOutBuf new byte SIZE BLOCK A
52. OEVER RESULTING FROM LOSS OF USE DATA OR PROFITS WHETHER IN AN ACTION OF CONTRACT NEGLIGENCE OR OTHER TORTIOUS ACTION ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE include lt inttypes h gt typedef struct uint8 t key 32 uint8 t enckey 32 uint8 t deckey 32 aes256 context void aes256 init aes256 context uint8 t key void aes256 done aes256 context void aes256 encrypt ecb aes256 context uint8 t plaintext void aes256 decrypt ecb aes256 context uint8 t cipertext functions smartcard h 8K kok kok k Kk ok kok kok kok AS IAIK IAIK IAIK IAIK IAIK IAIK IAIK IAIK This is the implementation of a basic smart card E OS supporting the T 1 protokoll E ck ck ck ck ck Ck ck ck ck ck ck KAZ A KA A KA AA AK K AA AA ZA KK AXA A KA KAZ AK AA KA KA ZK ko ko ko ko ko ck ck ck ck ck Ck kk ck ck ck ck Ck Ck AKA AAA AKA KK AKA A KA KA KA AAA File functions smartcard h A KCKCKCkCkCkCkck Ck ck Ck k Ck ke k ck kk kk k ck k ck k ck k ck ck ck ck ckckckckckcsk UWA ifndef IAIK SC OS functions define IAIK SC OS functions include globals h update void do AES Encrypt command APDU com APDU response APDU resp APDU void test command command APDU com APDU response APDU resp APDU void test timer0 command APDU com APD
53. P1 0 dataln channel if plainText length dataOut length System out println Error in the data field received the length is not the same as expected time getTimeExecution System out println Runtime APDU with data time ms disconnectCard card Functions class import java io File import java io FileInputStream import java io FileNotFoundException import java io FileOutputStream import java io IOException import java util List import javax smartcardio Card import javax smartcardio CardChannel import javax smartcardio CardException import javax smartcardio CardTerminal import javax smartcardio CommandAPDU import javax smartcardio ResponseAPDU import javax smartcardio TerminalFactory Functions to use with the interface smart card author antonio public class Functions public static final int SIZE BLOCK AES 16 public static final int SIZE KEY AES 32 public static final int MAX N BLOCKS AES 6 public static final int MAX BYTES AES 96 public static final int CLA 128 public static final int INS AES ENCRYPT 2 public static final int INS AES ENCRYPT V2 76 UM uM svie H F w Final Degree Project Antonio Bustos Rodr guez s
54. PCB 2 0 0x67 res APDU SW2 0x01 jelsel command Handler amp rec APDU send APDU amp res APDU Reset all APDUS res APDU NAD 0x00 res APDU PCB 0x00 res APDU LEN 2 res APDU LE 0 res APDU SW1 0x64 res APDU SW2 0x00 rec APDU NAD 0x00 rec APDU PCB 0x00 rec APDU LEN 0 rec APDU LE 0 rec APDU LC 0 rec APDU CLA 0x00 rec APDU INS 0x00 res APDU send the result APDU Header files aes32 h Byte oriented AES 256 implementation All lookup tables replaced with on the fly calculations X Copyright c 2007 2009 Ilya O Levin http www literatecode com ES Other contributors Hal Finney Permission to use copy modify and distribute this software for any purpose with or without fee is hereby granted provided that the above E copyright notice and this permission notice appear in all copies THE SOFTWARE IS PROVIDED AS IS AND THE AUTHOR DISCLAIMS ALL WARRANTIES i WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL DIRECT INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 96 UM uM svir F e Final Degree Project Antonio Bustos Rodr guez s WHATS
55. PDU data field i SIZE BLOCK AES j buf j aes256 done amp ctx n Finally the header of the response APDU resp APDU is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of data available to read in the data field The variable LE contains the value of the size of the n E data field SIZE BLOCK AES N and the variable Len contains the sum of the value Li and the size of a status word 2 The data field was filled in the last loop do AES NotEncrypt2 function This function works in the same way than do AES Encrypt2 except from this function does not execute the encryption code The goal of this function is helpful to calculate the runtime of the encryption process with subtracting of the runtime do AES Encrypt2 function and do AES NotEncrypt2 function The class of the command APDU expected is 0x80 and the instruction is 0x09 The parameter 1 contains the number of blocks of 16 Bytes as maximum 6 The parameter 2 is not required to have any value The data field of the command APDU contains the data to copy in blocks of 16 Bytes as maximum 96 Bytes In the subsection NotEncrypt2 class appears the structure of the command APDU and response APDU The variable n contains the number of blocks to
56. Register A TCCR1B Timer Counter Control Register B TCCR1L Timer Counter Value Low Byte TCCR1H Timer Counter Value High Byte OCR1AL Output Compare Register A Low Byte OCR1AH Output Compare Register A High Byte OCR1BL Output Compare Register B Low Byte OCR1BH Output Compare Register B High Byte ICR1L Input Capture Register Low Byte O O O O 000 O0 o ICR1H Input Capture Register High Byte e Interrupt registers o TIFR Timer Interrupt Flag Register o TIMSK Timer Interrupt Mask Register o GIMSK General Interrupt Mask Register In the timer mode of operation the timer is supplied by an internal signal After each clock cycle the meter reading is increased by 1 This signal is produced by n times the amount of the oscillator signal The factor x can have the following result 1 8 64 256 and 1024 for instance 1024 only after 1024 cycles of the oscillators the timer is raised the frequency is only fosc 1024 These results can be set with register TCCR1B The timer is adjusted through writing the following results into the register initial value used frequency Initial value Used frequency 11 A Final Degree Project 1 ck 2 ck 8 3 ck 64 4 ck 256 5 ck 1024 Antonio Bustos Rodr guez 12 RN M Final Degree Project Antonio Bustos Rodriguez Objectives and work plan Motivation In this period called by many people information age the
57. SB to encrypt Input files 1 input this file contains the data to encrypt 2 key this file contains SIZE KEY AES bytes of data that contains the key Output files 1 output encrypted this file contains the data encrypted E public class Encrypt2 extends Functions public static void main String args long time 0 boolean ov32 false Card card connectCard CardChannel channel establishChannel card byte key readFile C TMP key byte plainText readFile C TMP input byte dataIn dataOut plainTextBuf dataOutBuf byte plainTextBuf2 new byte 16 dataOut null plainTextBuf null dataOutBuf new byte SIZE BLOCK AES plainText addPadding plainText System out println Length data to encrypt plainText length if plainText length MAX BYTES AES 32 Z ov32 true for int i 0 i lt SIZE BLOCK AES i plainTextBuf2 i plainText i plainText length SIZE BLOCK AES plainTextBuf new byte plainText length SIZE BLOCK AES for int i20 i lt plainTextBuf length 1 plainTextBuf i plainText i plainText plainTextBuf int N plainText length SIZE BLOCK AES MAX N BLOCKS AES if ov32 dataOut new byte plainText length SIZE BLOCK AES Lf else dataOut new b
58. U response APDU resp APDU void test command withData command APDU com APDU response APDU resp APDU void do AES Decrypt command APDU com APDU response APDU resp APDU void do AES Decrypt2 command APDU com APDU response APDU resp APDU void do AES Encrypt2 command APDU com APDU response APDU resp APDU void do AES NotEncrypt2 command APDU com APDU response APDU resp APDU void test timerl command APDU com APDU response APDU resp APDU void do AES Encrypt withTimers command APDU com APDU response APDU resp APDU void detailsApps command APDU com APDU response APDU resp APDU void do AES NotEncrypt command APDU com APDU response APDU resp APDU void command Handler command APDU com APDU response APDU resp APDU fendif globals h J ECKCKCK kk kk kk kk kk kk kk Kk Kk A AS IAIK IAIK IAIK IAIK IAIK IAIK IAIK IAIK This is the implementation of a basic smart card a OS supporting the T 1 protokoll x This version supports AES128 encryption and a decryption 97 UM Ma ade svie F e Final Degree Project s Antonio Bustos Rodr guez Ck ck ckck kck AKA A KA KAZ A K A A KA X AZ XK AZ AA ZA KAZ AKA A KA KAZ AZ KA A ZA ZA ZK ko ko ko kk k KEKKK KK KK KK KA KAZ AK A A AA KA KAZ AKA A KA KA KK kk kc File globals h Fk Ae ke Ck k Ck k ke k ck Ck k k ck Ck ck k c
59. ZE BLOCK AES i j N N com APDU P1 if N gt MAX N BLOCKS AES The parameters in the data field are incorrect resp APDU LE 0 resp APDU LEN SIZE SW RESPONSE resp APDU SW1 0x6A resp APDU SW2 0x80 jelse for i 0 i lt SIZE KEY AES i key i com APDU data field i for i 0 i lt N i for j 0 j lt SIZE BLOCK AES j buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j for j 0 j lt SIZE BLOCK AES j resp APDU data field i SIZE BLOCK AES j buf 31 resp APDU LE SIZE BLOCK AES N resp APDU LEN SIZE BLOCK AES N SIZE SW RESPONSE resp APDU SW1 SW1 SUCCESS resp APDU SW2 SIZE BLOCK AES N J BK RR ko kok kok kok kok A ke Ae A kCkCkCkCkCkCkCkCkCkCk kCkCKCkCkCkCkCkCk Ck Ck k k ck k ck ck ck ck ckck oko J BRR KK Ck Ck kk kk kk Kk CkCkCKCkCkCkCKCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCkCk Ck Ck k ck Ck ck k ck k ck AA Routine to check th xecution of the encryption code CLA 0x80 INS 0x0A Pl size dataIn void test timerl command APDU com APDU response APDU resp APDU uint8 t N i overflow uint8 t cal ref timerL cal ref timerH uint8 t cal ref timer2L cal ref timer2H uint8 t buffer com APDU P1 N
60. a field 20 0x00 cal ref timer2L resp APDU data field 19 0x00 cal ref timer2H for i 0 i lt SIZE BLOCK AES i resp APDU data field i buf i resp APDU LE 21 resp APDU LEN 21 SIZE SW RESPONSE resp APDU SWl1 SW1 SUCCESS resp APDU SW2 21 J BRR RK ke ke Saa A A A ke ke A ee Ck k ck Ck k k ck k ck ck ckck ckck oko J BK RR k kok kok kok kok ke ke ke A ke A A ke kek ke A Ck k ck k ck k ck k ck ck ck ck ckck oko Return a string with the main application of the smart card CLA 0x80 INS 0x0C void detailsApps command APDU com_APDU response APDU resp APDU uint8 t name 29 0x41 0x45 0x53 0x20 0x45 Ox6e 0x63 0x72 0x79 0x70 0x74 0x69 Ox6f Ox6e 0x20 0x61 Ox6e 0x64 0x20 0x44 0x65 0x63 0x72 0x79 0x70 0x74 0x69 Ox6f 0x6e uint8 t i for i 0 i lt 29 i resp APDU data field i name i resp APDU LE 29 resp APDU LEN 31 resp APDU SW1 SW1 SUCCESS resp APDU SW2 29 J BRR KR kok kok kok kok kok kok kok kok oko kok kok kck Ck ck kc k A ok kok KCk KCk KCk kCk k ck kc k k ck a a oe Routine to check some parts of command APDU CLA 0x80 INS 0x0D Pl size dataIn void do AES NotEncrypt command APDU com APDU response APDU resp APDU uint8 t key SIZE KEY AES uint8 t buf SIZE BLOCK AES uint8 t i for i 0 i lt SIZE KEY AES i
61. al Degree Project Antonio Bustos Rodr guez 101
62. ally the header of the response APDU resp APDU is composed with the value Ox9F Success in the status word 1 and the value Ox1D in the status word 2 number of bytes of data available to read in the data field do_AES NotEncrypt function This command works in the same way than do AES Encrypt except from this function does not execute the encryption code The goal of this command is helpful to calculate the runtime 52 F RN M Final Degree Project Antonio Bustos Rodr guez of the encryption process with subtracting of the runtime ao AES Encrypt command and do AES NotEncrypt command The class of the command APDU expected is 0x80 and the instruction is OxOD The parameter 1 and the parameter 2 are not required to have any value The data field of the command APDU contains the data to copy In the subsection NotEncrypt class appears the structure of the command APDU and response APDU At the first the array of unsigned integer key and but are created with a length of 32 Bytes and 16 Bytes respectively The key is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU The plain text to copy is stored in the array put and it is composed of the next 16 Bytes after the first 32 Bytes The structure of the main loop is the same than in do AES Encrypt but now there are not any functi
63. ame return byte public static byte readFile String fileName File file FileInputStream fis byte data read null int read 1 try file new File fileName fis new FilelnputStream file int N fis available data read new byte N read fis read data read catch FileNotFoundException ezi System out println exl getMessage catch IOException ex2 System out println ex2 getMessage catch Exception ex3 System out println ex3 getMessage if read 1 return data_read jelsel return null Writes an array of Bytes data write to a fileName file param fileName param data write public static void writeFile String fileName byte data write File file FileOutputStream fis tryl file new File fileName fis new FileOutputStream file 80 UM Ma ade svie F e Final Degree Project Antonio Bustos Rodr guez y fis write data write Jcatch FileNotFoundException ex1 System out println exl getMessage Jcatch IOException ex2 System out println ex2 getMessage Jcatch Exception ex3 System out println ex3 getMessage Returns an array of bytes with the key and the plain text concatenated ready to send in the data field of the command APDU param key param plainText return byte
64. amp amp last lt SIZE BLOCK AES pad true for int i dataOut length last i dataOut length amp amp pad i t if dataOut i last pad false if pad return dataOut selse 38 ATA x a AM Final Degree Project Antonio Bustos Rodr guez int N dataOut length last byte dataOut2 new byte N for int i20 i N i dataOut2 i dataOut il return dataOut2 disconnectCard method The disconnectCard method disconnects the cara to release the connection established before If the disconnect operation fails a CardException is caught and the message is showed in the console public static void disconnectCard Card card try card disconnect false Jcatch CardException exl System out println exl getMessage System exit 1 establishChannel method The establishChannel returns the channel CardChannel object for the basic logic channel of the card The basic logical channel has a channel number of 0 public static CardChannel establishChannel Card card CardChannel channel null channel card getBasicChannel return channel getTimeExecution method The getTimeExecution method returns the runtime of the command APDU sent to the smart card The value is calculated from the subtraction global variables 2 with c1 The value of the previous variables is set up i
65. by the holders of the key This cryptographic method has been in use for thousands of years with the same concept than now encrypting or decrypting some information with the same key For example in Roman times the emperors used this technique to communicate between the senior But since these times the main problem of the symmetric key cryptography is sharing the key between the sender and receiver because it is necessary a secure channel to transmit it Nowadays the key is transmitted using an asymmetric cryptography algorithm for example when the Secure Shell network protocol The smart cards are very used in the security world because some of them are developed with cryptographic tools Besides more and more the smart cards are being used in our normal life for example in the phones card transport cards identification cards etc so the development of smart cards applications is increasing and its importance in the science computer Main Purpose The project work would consist from setting up development environment for particular class of cards and developing cryptographic application We must be able to communicate with the smart card to send some data and expect this data are returned in an encrypted manner To 13 F RN M Final Degree Project Antonio Bustos Rodr guez do this we have to write an application on the smart card to encrypt data with an AES algorithm for example Besides to offer the encryption an
66. cause the size of the data field of a command APDU sent can change The size of the data field does not influence a lot in the runtime of a command APDU but sending more than one command APDU to the smart card influences in the total runtime of encryption That is the reason because appears some peaks in the graph of Encrypt2 and they appear in the transition of send another extra command APDU to continue encrypting the plain text The peaks appear between 96 and 112 Bytes 192 and 208 Bytes 288 and 304 Bytes Besides the difference between two classes increases with increase plain text and it is a good improvement of Encrypt2 class With 1024 Bytes of plain text the runtime difference between both classes is 5515 5 milliseconds 57 Final Degree Project Antonio Bustos Rodriguez a o c o o a 2 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 320 Encrypt Bytes plain text Encrypt2 16 348 2 349 4 32 678 6 576 3 48 1008 9 800 22 64 1340 7 1025 9 80 1666 2 1253 96 1995 2 1478 8 112 2326 5 1806 6 128 2654 3 2032 8 144 2985 2258 4 160 3314 3 2485 9 176 3643 6 2712 2 192 3976 2 2939 4 208 4304 6 3269 9 224 4636 8 3491 5 240 4967 1 3720 4 256 5299 2 3946 9 272 5629 1 4172 1 288 5958 6 4397 9 304 6291 2 4724 3 320 6620 5 4952 5 Encrypt2 class runtime and Encrypt class runtime per data field load The below Stati
67. copy indicated in the parameter 1 At the first the array of unsigned integer key and buf are created with a length of 32 Bytes and the value of N respectively The key used is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU If the number of blocks to copy n is higher than the maximum the response APDU resp APDU with the status word 6A 68 referenced data not found is returned and the command ends The structure of the main loop is the same than in do AES Encrypt2 but now there are not any functions to encrypt The loop consists in copy per blocks of 16 Bytes the data field of the command APDU com APDU to buf and after that copies the value of the array buf in the data field of the response APDU resp APDU The loop starts to copy after the key for i 0 i lt N 1 for j 0 j SIZE BLOCK AES 3 buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j for j 0 j SIZE BLOCK AES j resp APDU data field i SIZE BLOCK AES j buf j Finally the header of the response APDU resp APDU is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of 49 F RN M Final Degree Project Antonio Bustos Rodr guez data available to read
68. cs and inventory Not used in the project e Supports ISO IEC 7816 Class A B and C cards 5V 3V and 1 8V e Reads from and writes to all ISO IEC 7816 microprocessor cards and supports the transmission protocol T 0 and T 1 e Supports memory cards using Synchronous Card API Short circuit detection The human interface of the reader consists in a LED with one color Green The LED has 2 states blinking waiting card insertion constant on card reading writing The Cable USB reader has as maximum 1 5m long USB 2 0 type A connector power supply through USB port maximum operating current 100mA and operating voltage 4 4 5 5V 16 ATA 5 at w Final Degree Project Antonio Bustos Rodr guez The API to work with the reader is Microsoft PC SC environment with associated drivers CT APl and synchronous Card API for support of memory cards The operating systems supported are e Windows 9505R2 NT4 00 for PC Twin in serial mode e Windows 98 98SE Me 2000 XP Server 2003 x64 editions Vista 32 64 bits Seven Server 2008R2 e Win CE 4 1 4 2 5 0 6 0 USB readers e Linux Kernel 2 6 and higher e MacOSX Panther Tiger Leopard 32 editions USB readers e Support for Solaris XP embedded USB readers The drivers can be downloaded from support gemalto com and the guide installation for each system appears in the same website Dynamite Plus Smartcard Programmer The Dynamite Plus is the evolution of the
69. d 16 Bytes respectively The key used in the encryption is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU The plain text to encrypt is stored in the array buf and it is composed of the next 16 Bytes after the first 32 Bytes The structure aes256 content has to be initialized with the key and after that it is possible to encrypt the plain text with the function aes256 encrypt ecb The function aes256 done release the key from the structure aes256 content aes256 init amp ctx key aes256 encrypt ecb amp ctx buf aes256 done amp ctx Finally in the data field of the response APDU is copied the array buf which contains the u cipher text obtained The variable LE contains the value of the size of a block SIZE_BLOCK_AES and the variable LEN contains the sum of the value LE and the size of a status word 2 The header is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of data available to read in the data field The structure of the response APDU appears in the subsection Encrypt class test_command function This function sends a simple response APDU when it is selected The class of the command APDU expected is 0x80 and the instruction is 0x03 The parameter 1 and the parameter 2 are not required to hav
70. d decryption solutions the hash functions SHA 1 and SHA 2 digest going to be developed in the smart card But the implementations found were incompatible with the microcontrollers because most of them were designed to 32 bit microprocessors The attempts to convert the implementations to an 8 bit design failed and the few implementations that can be compiled by the libc module returned wrong digest As a result of this situation the developing of the hash functions stopped and only the classes implemented on Java still working These classes allow the communication with the hypothetical hash commands of the smart card To work with the smart card commands developed in the smart card an interface to communicate between the smart card and the computer was developed in Java This interface is capable to select a file read it sent it to the smart card in blocks and save the cipher output to a file The software development process used in the project is the spiral model because the activities are not fixed a priori and they are chosen based on risk analysis and the needs emerged in each step This model has been chosen because the risk at the first to develop the code in the smart card and for the interface with Winscard Smart Card API The work plan of the project was at first be used to the smart card topic and look for the information relative of the topic After that set up my laptop to be ready with all the programs necessary to start t
71. dataln channel time getTimeExecution for int j 0 j lt SIZE BLOCK AES j dataOut j i SIZE BLOCK AES dataOutBuf j 74 UM uM svie F e Final Degree Project Antonio Bustos Rodr guez y selse dataIn concatenateArrayByte key plainText dataOut sendAPDUwithData CLA INS AES NOT ENCRYPT dataIn length 0 dataln channel time getTimeExecution catch NullPointerException ex3 System out println ex3 getMessage System exit 1 disconnectCard card System out println NOT Encryption duration time System out println NOT Encryption succesful tryl System out println new String data0ut UTF 8 catch UnsupportedEncodingException ezi System out println exl getMessage End NotEncrypt java NotEncrypt2 class import javax smartcardio public class NotEncrypt2 extends Functions public static void main String args Card card connectCard CardChannel channel establishChannel card long time 0 byte plainText readFile C TMP input byte key readFile C TMP key byte dataIn plainTextBuf dataOut plainText addPadding plainText System out println Length data sent to encrypt plainText length int N plainText length SIZE BLOCK AES MAX N BLOCKS AES if N gt 0
72. decrypt default AES_encrypt decrypt hex gt Process of upload a file into the smart card successfully Installation guide The installer file has to be downloaded from the website of Duolabs http www duolabs com in the Download section Before starting the installation the Dynamite Plus programmer has not to be connected to the PC with a USB cable The steps of the installation are the next e Follow the instructions of the setup program e Connect the Dynamite Plus programmer with the USB cable to the PC e Execute Cas Studio and if it is necessary change the interface language Depending of the operating system you will need to some extra actions to complete the installation e Windows XP and older Windows XP displays Found New Hardware Wizard window Select Install from a list or specific location click Next select Include this location in the search and then click Browse to open the Browse for Folder dialog Search and select the c Programs duolabs Cas_Studioxxx drivers folder you have created Attention this path may be different if you have specified a different folder during setup or if Windows is in other language xxx stands for the release version of Cas Studio Click OK select Next and wait for the process to complete Once the setup is completed click End e Windows Vista The drivers are automatically recognized and installed any action is needed 23
73. dls us ad data 68 Decrypt2 cl SS LT 70 SEI RENE 72 SHIA 25 6 WA 73 HASI EE 73 PIICUEeTErrseecc UR 73 TestAPDU Class eet dnt rrr Herten SERERE nne pan aiT rea aa a aAA a raid 74 NotEncrypt elasS ecciesie mete E MM M IM 74 NotEncrypta A Etc idas 75 F Rctions claSS P 76 Cryptographic applications on the smart card AES encryption and decryption 81 Tec a E A E aE E a E ESKATE E aSK 81 Header files ccoo ii cad 96 ATA 5 t we Final Degree Project Antonio Bustos Rodr guez Introduction Smart card A smart card is a card with embedded integrated circuits which can process data This implies that it can receive input data which is processed and delivered as an output There are two types of smart cards memory cards and microprocessor card Memory cards contain only memory storage components for example to store some data in the card Microprocessor cards contain memory components and microprocessor components The smart card is made of plastic generally PVC like the older credit cards with magnetic strip and its size is similar to the older credit cards There are two technologies to use the smart cards contact smart card and contactless smart card Contact smart cards transmit the data with the metal conductors or pins of the card Contactless smart card transmits the data through radio frequencies and for example they are used in electronic passports The smart cards help t
74. e any value The response APDU resp APDU is made up of a header with the next values 0x90 in the status word 1 Ox00 in the status word 2 SIZE SW RESPONSE in the variable LEN and 0 in the variable LE there is not any bytes of data available to read in the data field The status word of the response means that the command has been executed without error The use of this function is to verify that the smart card is working and response with a simple command APDU test_timer0 function This function measures the number of clock cycles necessary to copy the data available in the command APDU in a local array of unsigned integer The class of the command APDU expected is 0x80 and the instruction is 0x04 The parameter 1 contains the length of the data field The parameter 2 is not required to have any value The data field of the command APDU contains the data to copy in the local array If the parameter 1 of the header does not contains a number higher than O and smaller than 15 the response APDU resp with the status word 6A 68 referenced data not found is returned and the function ends At the first the timer 0 is initialized with the next values overflow 0 DDRB OxFF TCNTO 0 45 F RN M Final Degree Project Antonio Bustos Rodr guez TCCRO 1 The variable overflow checks if a overflow happens between
75. e smart card and each time is needed like is showed in the next image header command APDU data field command APDU Key 32 Bytes Cipher text 16 Bytes Structure of the command APDU sent to the smart card Decrypt class If the cipher text is not higher than 16 Bytes the cipher text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data The output decrypted is sent in a single response APDU and the data field of that response is stored in a buffer When all the segments to decrypt have been received the buffer contains the clear data The structure of the response APDU is showed below v v Sw1 Sw2 Ox9F 0x10 Structure of the response APDU received from the smart card Decrypt class Plain text 16 Bytes To send the command APDU is necessary to use the method sendAPDUwithData To decrypt the data is necessary to select the command of the smart card ao AES Decrypt with the class 128 ca and the instruction 6 INS AES DECRYPT The instruction parameter 1 and the instruction parameter 2 are not necessary and in the data field appears the array of bytes of data to decrypt Moreover the channel of the communication with the smart card has to be sent on the method dataOutBuf sendAPDUwithData CLA INS AES DECRYPT 0 0 dataln channel The array of bytes aataout contains the clear data but it is compulsory to check if padd
76. e smart card has to be sent on the method dataln concatenateArrayByte key cipherTextBuf cipherTextBuf length int Pl dataIn length SIZE KEY AES SIZE BLOCK AES try dataOutBuf sendAPDUwithData CLA INS AES DECRYPT V2 P1 0 dataIn channel The array of bytes aataout contains the data decrypted but it is compulsory to check if padding has been applied to the data encrypted and delete it if there is necessary dataOut deletePadding dataOut Finally the buffer that contains the clear data is written in a file c TMP output plainText The method writeFile Functions java is used to write the array of bytes in a file After writing the file the card is disconnected and the runtime of sent the command APDU is showed in the console 31 F RN M Final Degree Project Antonio Bustos Rodr guez SHA1 class This class is responsible to do the digest of the input data with the algorithm SHA 1 implemented in the smart card At the first establish a channel communication with the smart card reader and read the input data to digest from the file located in c TMP input To calculate the digest an command APDU is sent to the smart card with the command sendAPDUwithData and selects the function of the smart card do SHA1 with the class 128 Cra the instruction 2 INS SHA1 and the length of the data to digest in the instruction parameter 1 The length of the data cannot
77. ed because the key is not stored in the smart card and each time is needed like is showed in the next image 26 1 XN 3 ate aM om Final Degree Project Antonio Bustos Rodr guez header command APDU CLASS INS data field command APDU Structure of the command APDU sent to the smart card Encrypt class Key 32 Bytes Plain text 16 Bytes If the plain text is not higher than 16 Bytes the plain text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data The output encrypted is sent in a single response APDU and the data field of that response is stored in a buffer When all the segments to encrypt have been received the buffer contains the data encrypted The structure of the response APDU is showed below SW1 BENE T Ox9F 0x10 Cipher text 16 Bytes Structure of the response APDU received from the smart card Encrypt class To send the command APDU is necessary to use the method sendAPDUwithData in the manner shown below To encrypt the data is necessary to select the command of the smart card do AES Encrypt with the Class 128 cra and instruction 2 INS AES ENCRYPT The instruction parameter 1 and the instruction parameter 2 are not necessary and in the data field appears the array of bytes of data to send Moreover the channel of the communication with the smart card has to be sent on the method dataI
78. establishChannel card byte key readFile C TMP key byte cipherText readFile C TMP output encrypted byte dataIn dataOut cipherTextBuf dataOutBuf byte cipherTextBuf2 cipherTextBuf2 new byte 16 dataOut new byte cipherText length dataOutBuf new byte SIZE BLOCK AES System out println Length data to decrypt cipherText length if cipherText length3MAX BYTES AES 32 ov32 true for int i 0 i lt SIZE BLOCK AES i cipherTextBuf2 i cipherText i cipherText length SIZE BLOCK AES cipherTextBuf new byte cipherText length SIZE BLOCK AES for int i 0 i lt cipherTextBuf length i cipherTextBuf i cipherText i cipherText cipherTextBuf int N cipherText length SIZE BLOCK AES MAX N BLOCKS AES YAYA if ov32 dataOut new byte cipherText length SIZE BLOCK AES else dataOut new byte cipherText length if N gt 0 if cipherText length SIZE BLOCK AES MAX N BLOCKS AES 0 Ntt for int i 0 i lt N i int a i SIZE BLOCK AES MAX N BLOCKS AES int b i 1 SIZE BLOCK AES MAX N BLOCKS AES if cipherText length lt b cipherTextBuf new byte cipherText length al for int j 0 j lt cipherText length a j ciphe
79. f AES 32 integrated in the smart card uses the simplest mode of encryption the electronic codebook ECB The reason of usage of this mode of encryption is to accelerate the runtime of the encryption code because it is oriented to 8 bit microcontrollers This mode is not the most secure of all of the others but if it used to a small amount of plain text it should works fine in a security perspective From the above causes it is recommended to use the commands to encrypt or to decrypt of the smart card to sizes of plain text smaller than 1024 Bytes for example the text of an e mail A new idea to use for this smart card is to encrypt or decrypt messages shared with some users via instant messaging applications That requires a modification of the applications to be able to use the smart card to encrypt or decrypt the text and it can be developed like a plug in The code developed in Java is directed to use in a console mode but it can be easily modified to add a graphic user interface This graphic user interface will allow to the user selects the file to encrypt or decrypt and the key required and selects the destination folder where save the output generated To recreate a possible usage scenario of the smart card the key would be stored into the personal smart card of the user With that smart card the user would be able to encrypt or decrypt whatever file requested in an easily way The problem would be appear if the smart card is stolen f
80. f SHA1 class and SHA256 class except the changes on the number of instruction used 2 INS SHA512 DetailsSC class This class receives the details of the functions implemented in the smart card using the command detailsApps of the smart card At the first a communication channel is established with the smart card with the functions connectCard and establishChannel To select get the details of the smart card a simple command APDU is sent It is made up of a header with the class CLA the instruction INS_DETAILS and without any data in the data field The method sendSimpleAPDUwithData is used to send the command APDU because an array of bytes is expected in the data field of the response APDU 32 w Final Degree Project Antonio Bustos Rodr guez The data field of the response APDU contains the string coded in hexadecimal with UTF 8 so the data field has to be converted in a string to read it comfortably At the end the card card is released TestAPDU class This class sends a simple command APDU using the method sendSimpleAPDU Functions class This class is used to verify that the smart card responses with a simple response APDU only status word and it is working The command APDU is made up of a header with the class cia and the instruction INS SIMPLE APDU To send the command APDU to the smart card the channel CardChannel is required Also the runtime
81. has been analyzed extensibely and some attacks have been published This algorithm can be executed in an 8 bit microcontroller like the microcontroller incorporated in the smart card used and it is used in other environments successfully About the security of AES in the Advanced Encryption Standard article in Wikipedia there is a section about this topic for more details consults the Bibliography Electronic codebook ECB The electronic codebook is an encryption mode to encrypt data in the symmetric key algorithms and it is the simplest mode In the electronic codebook the message is divided in blocks of the same length and they are encrypted or decrypted sperately like appears in the below figure Plaintext Plaintext Plaintext LI O TI 1 Y M v Block Cipher Block Cipher Block Cipher Key Encryption Key Encryption Key Encryption Y v LI LI LI Ciphertext Ciphertext Ciphertext Electronic Codebook ECB mode encryption Ciphertext Ciphertext Ciphertext CONN TITITI Y Block Cipher Block Cipher Block Cipher Key Decryption Key gt Decryption Key Decryption t ITITITI LITI Plaintext Plaintext Plaintext Electronic Codebook ECB mode decryption If the plain text is longer than the block length it has to be separated in blocks of a determinate length and if the length is not multiple of the block length in the last block has to be added padding It is not recommended to encrypt b
82. he array key and it is composed of the first 32 Bytes of the data field of the command APDU The cipher text to decrypt is stored in the array buf and it is composed of the next 16 Bytes after the first 32 Bytes In the subsection Decrypt class appears the structure of the command APDU and response APDU The structure aes256 content has to be initialized with the key and after that it is possible to decrypt the cipher text with the function aes256 decrypt ecb The function aes256 done release the key from the structure aes256 content aes256 init amp ctx key aes256 decrypt ecb amp ctx buf aes256 done amp ctx Finally in the data field of the response APDU is copied the array but which contains the clear text obtained The variable E Fr contains the value of the size of a block SIZE BLOCK AES and the variable LEN contains the sum of the value LE and the size of a status word 2 The header is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of data available to read in the data field do AES Decrypt2 function This function can decrypt until 96 Bytes in blocks of 16 Bytes of input cipher text with 32 Bytes of a key returning the clear text as output The class of the command APDU expected is 0x80 and the instruction is 0x07 The paramete
83. he project The first step was uploading a hex file into the smart card Afterwards started to develop simple commands in the smart card to be used to the code development and the project started seriously with the adding of the AES implementation and the test executions The development of the project is described in the appendix Report project per week The materials used in the project are described in the next section 14 w Final Degree Project Antonio Bustos Rodr guez Materials and method The smart cards used in the project were FunCard 5 Atmel AT90S8515 microcontroller and FunCard ATmega163 Atmel ATmega163 microcontroller which are Atmel cards with microcontrollers and programmable memory To connect the smart card with the PC the PC Twin smart card reader was utilized with the USB connection To program the smart card the Dynamite Plus Smartcard Programmer was used The software used to the development of the project has been AVR Studio 4 Eclipse and Cas Studio The interface between the smart card and the PC was developed under Eclipse the program of the smart card was developed under AVR Studio 4 and to upload the hex file obtained through the AVR Studio Cas Studio was used AT90S8515 The AT90S8515 FunCard5 card is a low power CMOS 8 bit microcontroller based on the AVR RISC architecture The freguency of the microcontroller approximately is 1 MIPS per MHz allowing optimizing power consumption versu
84. here is a free implementation called PC SC lite This specification allows to the applications to work directly with the smart card and it is available in the most used programming languages like C C Java and Basic MUSCLE Movement for the Use of Smart Cards in a Linux Environment is a project created to coordinate the development of drivers for smart card readers and a API to help the applications to communicate with the smart cards in a Linux environment At first it was started because for a long time the drivers required for using smart card with Linux were not available but they were appearing it was necessary establish an interface in Linux to work with smart card for example for operations such as logging on With regard to its architecture MUSCLE is strongly passed on PC SC but in contrast to PC SC the source code is available under a GPL license Java Card Technology Java Card is a technology to develop applications to run in Java compatible smart cards This applications or commonly called applets are designed to run securely on smart cards because they are executed with a Java Card Virtual Machine inside the smart card The Java card applets are very portable because they can be executed in any Java compatible smart card and the applets are executed securely because this technology offers data encapsulation an applet firewall cryptographic functions and the features of the Java language Java Card 3 0 is a new vers
85. ibuted provided the license conditions detailed in the project web The list of the modules supported by the library is described below e Bootloader support utilities o include lt avr io h gt o include lt avr boot h gt e CRC computations o include avr crcl6 h e EEPROM handling O include lt avr eeprom h gt e AVR device specific IO definitions o include lt avr sfr defs h gt e Program space string utilities o include lt avr io h gt o include lt avr pgmspace h gt 24 e x 4 2 5 S Pana v Final Degree Project Antonio Bustos Rodr guez e Power management and sleep modes O include lt avr sleep h gt e Watchdog timer handling o include lt avr wdt h gt e Character operations o include lt ctype h gt e System errors errno include lt errno h gt ypes include lt inttypes h gt atics o e Integert o e Mathem o include lt math h gt e Setjmp and Longjmp e Standard IO facilities o e General o e Strings o include lt stdio h gt utilities include lt stdlib h gt include lt string h gt e Interrupts and signals o include lt signal h gt e Special function registers Eclipse Eclipse is a multi language integrated development environment with a useful extensible plug in system It is oriented to write Java source code but it can be used to develop applications in other languages as C C COBOL P
86. ic static final int INS d INS SHASI2 int B input 3 public static final int INS FF INS DETAILS int key INS SIMPLE APDU WIT GBA JRE System Library res 1 F INS_SIMPLE_APDU_WIT f amp sinmuros 2 public static final int INS SHA1 F Ns SIMPLE APDU int 65 test 3 public static final int INS SEAZ Aes public static final int INS_SHASI2 2 a public static final int INS DETAILS 12 e comectcardd Card public static final int INS SIMPLE APDU WITHDATA S ela Card card public static final int INS SIMPLE APDU ITHDATA V2 9 po en public static final int IWS SIMPLE APDU 3 Ps AN private static long ti o ram private static long t2 e deletuPaddino byte I ud sendAPDUwithData nt sendSimpleAPDUnithDat 6 getTimeExecution lor sendSimpleAPDU nt int z s Y 5 nethexstina hvteM lo gt smartinsert 224 1 Screen capture of Eclipse 25 o Final Degree Project Antonio Bustos Rodr guez Project analysis Interface in Java with the smart card An interface was developed in Java to communicate with the smart card with commands and responses APDU Moreover this interface includes extra methods to help with the common routine with the arrays of byte processing in Java The interface consists in series of classes to do a concrete cryptographic function These classes are e Decrypt java e Decrypt2 java e DetailsSC java e Encrypt java e Encrypt
87. ig amounts of blocks with the same key sm p 4 z 5 we Final Degree Project Antonio Bustos Rodr guez because this encryption mode always returns the same byte encrypted of a byte of plain text For example if the same block to encrypt appears more than once in the plain text this block is always the same cipher text For lengthy messages the ECB mode may not be secure If the message is highly structured it may be possible for a cryptanalyst to exploit these regularities For example if it is known that the message always start out with certain predefined fields then the cryptanalyst may have a number of known plain text cipher text pairs to work with If the message has repetitive elements with a period of repetition a multiple of b bits then these elements van be identified by the analyst This may help in the analysis or may provide an opportunity for substituting or rearranging blocks Cryptography and Network Security Principles and Practice William Stallings 2010 p 200 Original Encrypted using ECB mode Other modes than ECB results in pseudo randomness The first image corresponds to the original message the next image is the message encrypted using ECB and the last image is the message encrypted with improved versions of ECB In the original message appears some parts that are identical like the colours so these parts always produces the same cipher text and it is easily to identify the original image More i
88. in sampling clock cycles The register DDRB is set up to use all the pins on PoRTB 8 bit bi directional I O port for output The register rento timer counter O value is set up to O to start value of timer counterO The register rccro timer counter O control register is set up to 1 to set the oscillator frequency The variables cai ref timer and cal ref timer2 contains the clock cycles between the main loop cal ref timer TCNTO for i 0 i lt N 1 buffer i com APDU data field i cal ref timer2 TCNTO It is necessary to check if the register TIFR timer interrupt flag register is set to avoid an overflow in the measure of the values of the timer counter 0 if TIFR amp 0x01 0x01 overflow 1 cal ref timer2 0x00 The status word 1 of the response APDU resp APDU is sw1 success and the status word 2 is the amount of bytes in the data field in this case 3 The data field consists of e First byte value of cal ref timer e Second byte value of cai ref timer2 e Third byte value of overflow If this byte is set an overflow happened in the measure of the previous values and they are incorrect test command withData function This function copies the data field of the command APDU com APpU in the data field of the response APDU resp APDU The class of the command APDU expected is 0x80 and the instruction
89. ing has been applied to the data encrypted and delete it if there is necessary dataOut deletePadding dataOut Finally the buffer that contains the clear data is written in a file c TMP output plainText The method writeFile Functions java is used to write the array of bytes in a file After writing the file the card is disconnected and the runtime of sent the command APDU is showed in the console Encrypt2 class This class has the same functionality than Encrypt class The difference is that in Encrypt class in one command APDU only is sent the key 32 Bytes and the plain text 16 Bytes concatenated while in Encrypt2 class can send more than 16 Bytes of plain text in the data field of a command APDU The maximum length of plain text to send is 224 Bytes because the key 32 Bytes has to be sent too in the same command APDU and it is not possible to send more than 256 Bytes in the data field of a command APDU 28 an 4 H oa Final Degree Project Antonio Bustos Rodr guez As a result the execution tests of Encrypt2 it is impossible to send more than 96 Bytes of plain text in one command APDU because there is a memory overflow in the smart card Unknown error Ox6f7 At the first a communication channel is established with the smart card For AES encryption it is necessary as parameter a key 32 Bytes and the plain text The plain text is read from the file called c TMP input and the key
90. int8 t rc 85 UM Un Final Degree Project Antonio Bustos Rodriguez pi S uint8 t i for i 28 i gt 16 i 4 k i 0 k i 4 k i 1 k i 3 k i 2 k i 2 k i 3 k i 1 k 16 rj sbox k 12 k 17 rj sbox k 13 k 18 rj sbox k 14 k 19 rj sbox k 15 for i 12 i 0 i 4 k i 0 k i 4 k i 1 k i 3 k i 2 k i 2 k i 3 k i 1 rc FD rc k 0 rj sbox k 29 rc k 1 rj sbox k 30 k 2 rj sbox k 31 k 3 rj sbox k 28 aes expandDecKey void aes256 init aes256 context ctx uint8 t k uint8 t rcon 1 register uint8 t i for i 0 i lt sizeof ctx gt key i ctx gt enckey i ctx gt deckey i k i1 for i 8 i aes expandEncKey ctx gt deckey amp rcon aes256_init void aes256 done aes256 context ctx register uint8 t i for i 0 i lt sizeof ctx gt key i ctx gt key i ctx gt enckey i ctx gt deckey i 0 aes256 done void aes256 encrypt ecb aes256 context ctx uint8 t buf 1 uint8 t i rcon aes addRoundKey cpy buf ctx gt enckey ctx gt key for i 1 rcon 1 i lt 14 i aes subBytes buf aes shiftRows buf aes mixColumns buf if i amp 1 aes addRoundKey buf amp ctx gt key 16 else aes expandEncKey ctx gt key amp rcon aes addRoundKey buf ctx gt key aes subB
91. ion byte dataOut null ResponseAPDU r null CommandAPDU c null try c new CommandAPDU clas ins 0 0 tl System currentTimeMillis r channel transmit c t2 System currentTimeMillis System out println r dataOut r getData Jcatch CardException exl System out println Error sendAPDUwithData exl getMessage System exit 1 if r getSW1 159 NullPointerException ex2 new NullPointerException Error with the APDU response data returned invalid throw ex2 jelsel return dataOut Returns the runtime of the command APDU sent to the smart card measured in the method sendAPDUwithData with the global variables tl and t2 return long public static long getTimeExecution return t2 t1 79 UM uM svie H F a Final Degree Project Antonio Bustos Rodr guez s Send a simple command APDU to the smart card param cla param ins iparam channel WA public static void sendSimpleAPDU int cla int ins CardChannel channel try CommandAPDU c new CommandAPDU cla ins 0 0 tl System currentTimeMillis ResponseAPDU r channel transmit c t2 System currentTimeMillis System out println r catch CardException exl System out println exl getMessage System exit 1 Return an array of Bytes read from a fileName file param fileN
92. ion of this technology and it has two editions The Classic Edition is an evolution of the previous version of Java Card and supports the previous java card applets developed The Connected Edition includes a new virtual machine and a new environment to execute applets with network oriented features However we cannot use this technology with our smart cards because they are incompatible Module scard The smartcard scard module is a library to communicate in C language with the smart card readers compatible with the PC SC specification The module is the lower layer of the pyscard framework and it is an application programming interface to work with the smart card and provides the next functions e SCardAddReaderToGroup e SCardBeginTransaction e SCardCancel e SCardConnect w Final Degree Project Antonio Bustos Rodr guez e SCardControl e SCardDisconnect e SCardEndTransaction e SCardEstablishContext e SCardForgetCardType e SCardForgetReader e SCardForgetReaderGroup e SCardGetAttrib e SCardGetCardTypeProviderName e SCardGetErrorMessage e SCardGetStatusChange e SCardintroduceCardType e SCardintroduceReader e SCardlntroduceReaderGroup e SCardlsValidContext e SCardListInterfaces e SCardListCards e SCardListReaders e SCardListReaderGroups e SCardLocateCards e SCardReconnect e SCardReleaseContext e SCardRemoveReaderFromGroup e SCardSetAttrib e SCardStatus e SCardTransmit Answer to reset ATR
93. ional to send is the information field which is composed by the command or response APDU The structure of a block is showed below prologue field information field epilogue field protocol ies control byte APDU EDC PCB 0 254 bytes 1 2 bytes The structure of a T 1 transmission block The prologue field consists in three bytes node address NAD protocol byte PCB and length LEN The node addres contains the destination and source addresses for the block the protocol control byte supervises the transmission protocol and the length indicates the length of the information field in other words the command or response APDU The information field contains the command APDU and his content is not analyzed or used in this layer The epilogue field is used to detect errors in the transmission of the block More information about the T 1 transmission protocol in the chapter 6 4 3 p 409 from Smart Card Handbook 2004 Wolfgang Rankl and Wolfgang Effing ATA 5 t Final Degree Project Antonio Bustos Rodr guez Communication with smart cards PC SC Personal Computer Smart Card is specification to integrate smart cards in a computing environment particulary Windows environments needing a driver of the smart card reader compatible with this specification PC SC is implemented in almost all the Microsoft operating systems like Microsoft Windows 2000 XP For other computing environments like Mac OS X or Linux t
94. is encrypted separately The functions available to use are the next void aes256 init aes256 context uint8 t key void aes256 done aes256 context void aes256 encrypt ecb aes256 context uint8 t plaintext void aes256 decrypt ecb aes256 context uint8 t cipertext functions smartcard c In this file appears the source code of the applications implemented to encrypt and decrypt data with the AES 32 algorithm in the smart card In this source file the arguments of the functions are a pointer of a command APDU and a pointer of a response APDU because the management of sending and receiving of the command APDU is in the file main c The functions developed are do AES Encrypt function This function is the responsible of the simple encryption and it can encrypt 16 Bytes of input plain text with 32 Bytes of a key returning 16 Bytes of cipher text as output The class of the command APDU expected is 0x80 and the instruction is 0x02 The parameter 1 and the parameter 2 are not reguired to have any value The data field of the command APDU has to contain 16 Bytes of plain text to encrypt and the 32 Bytes of the key The structure of the command APDU appears in the subsection Encrypt class 44 F RN M Final Degree Project Antonio Bustos Rodr guez At the first the array of unsigned integer key and buf are created with a length of 32 Bytes an
95. k ck ck ee I ee Avoid including this file more than once ifndef Globals define Globals WA INCLUDE FILES a Standard include files 7 kk 3 DECLARATIONS ER VT Global constants kk TRUE ifndef TRU define TRU endif FALSE NULL bs ifndef FALS define FALS endif ij E ifndef NULL define NULL 0 endif Return codes define OK define DATA define RTR WNE ox define ERROR 1 define FULL 2 define EMPTY 3 define BUSY 4 define INPUT BUFFER SIZE 200 EEO 3 2 Global macros kk kk kK 33 Global type definitions y define SIZE BLOCK AES 16 define SIZE KEY AES 32 define MAX N BLOCKS AES 6 define SW1 SUCCESS 159 define SIZE SW RESPONSE 2 98 svie s tana tS 1A F Final Degree Project Antonio Bustos Rodr guez typedef struct Ge unsigned unsigned unsigned unsigned unsigned unsigned unsigned unsigned int LE unsigned neral char char char char char char char char char command APDU typedef struct Ge unsigned unsigned unsigned unsigned unsigned unsigned unsigned neral char char char char char char char response APDU kk k
96. k kc kck a KK k oko kk kk Ck Ck kk Kk Ck A ke A A kCkCkCkCkCKCkCkCkCkCkCkCkCkCkCk ck k ck k ck k ck ck ck ck ckckokok Routine to check some parts of command APDU CLA 0x80 INS 0x03 void test command command APDU com APDU response APDU resp APDU resp APDU LEN SIZE SW RESPONSE resp APDU LE 0 resp APDU SW1 0x90 resp APDU 0x00 SW2 J BK RR ko kok kok kok kok kok k kok ke AS EEE AS Routine to check th xecution of the encryption code CLA 0x80 INS 0x04 Pl size dataIn void test timer0 command APDU com APDU response APDU resp APDU uint8 t N i uint8 t cal ref timer uint8 t cal ref timer2 uint8 t overflow uint8 t buffer com APDU P1 N com APDU P1 if N gt 0 amp amp N lt 15 resp APDU resp APDU resp APDU resp APDU N 2 Ox6A 0x88 Sw1 SW2 E js E else overflow 0 DDRB OxFF TCNTO 0 TCCRO 1 cal ref timer TCNTO for i 0 i lt N 1 buffer i com APDU data field i check if the the overflow bit of the TIFR register is set cal ref timer2 TCNTO 1f TIFR 0x01 0x01 overflow 1 cal ref timer2 0x00 resp APDU LEN 3 SIZE SW RESPONSE resp APDU LE 3 resp APDU SW1 SW1 SUCCESS resp APDU SW2 3 resp APDU data field 0 cal ref timer 88 UM uM
97. key in memory for the encryption or decryption process functions smartcard h This header file contains the declaration of u n functions smartcard c the functions written in 43 F RN M Final Degree Project Antonio Bustos Rodr guez globals h This header file contains some global constants like true false null return codes The global type definitions are also included e g the constants used in functions of functions smartcard c the structure command APDU and the structure response APDU The latter structures are very important because there are fundamental in the project and they are widely used T1 Comm Lib h This header file contains the declaration of the functions implemented in the external library libT1 Comm Lib a The functions declared are fundamental because they are responsible of the management of the commands APDU and responses APDU void send ATR void int request extended BWT response APDU send APDU char extension factor unsigned char receive APDU command APDU received APDU void send APDU response APDU send APDU Source files aes32 c The file aes32 c contains the source code of the byte oriented implementation of the algorithm Advanced Encryption Standard AES 32 for encrypt and decrypt blocks of 16 Bytes with a key of 32 Bytes The mode of encryption used is the electronic codebook ECB where the message is divided into blocks and each block
98. key is not stored in the smart card and each time it is requested The structure of the command APDU is showed in the next image 30 san 28 an 4 z H S Final Degree Project Antonio Bustos Rodr guez header command APDU data field command APDU Key 32 Bytes 1 Cipher text 16 Bytes Structure of the command APDU sent to the smart card Encrypt2 class If the cipher text is not higher than 96 Bytes the cipher text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data The output decrypted is sent in a single response APDU and the data field of that response is stored in a buffer When all the segments to decrypt have been received the buffer contains the clear data The structure of the response APDU is showed below Plain text 96 Bytes Structure of the response APDU received from the smart card Decrypt2 class To send the command APDU is necessary to use the method sendAPDUwithData in the manner shown below To decrypt the data is necessary to select the comand of the smart card do AES Decrypt2 with the Class 128 cra and instruction 7 INS AES DECRYPT v2 The instruction parameter 1 contains the number of blocks of 16 bytes that are in the data field the instruction parameter 2 is not necessary and in the data field appears the array of bytes of data to send Moreover the channel of the communication with th
99. ments to encrypt have been received the buffer contains the data encrypted The structure of the response APDU is showed below Cipher text 96 Bytes Structure of the response APDU received from the smart card Encrypt2 class 29 F RN M Final Degree Project Antonio Bustos Rodr guez To send the command APDU is necessary to use the method sendAPDUwithData in the manner shown below To encrypt the data is necessary to select the command of the smart card do AES Encrypt2 with the Class 128 cra and instruction 8 INS AES ENCRYPT V2 The instruction parameter 1 contains the number of blocks of 16 bytes that are in the data field the instruction parameter 2 is not necessary and in the data field appears the array of bytes of data to send Moreover the channel of the communication with the smart card has to be sent on the method dataIn concatenateArrayByte key plainTextBuf plainTextBuf length int P1 dataIn length SIZE KEY AES SIZE BLOCK AES try dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT V2 Pl 0 dataln channel Finally the array of bytes that contains the data encrypted is written in a file TC TMP output encrypted The method writeFile Functions java is used to write the array of bytes in a file After writing the file the card is disconnected and the runtime of sent the command APDU is showed in the console
100. n concatenateArrayByte key plainTextBuf plainTextBuf length dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT 0 0 dataln channel Finally the buffer that contains the data encrypted is written in a file C TMP output encrypted The method writeFile Functions java is used to write the array of bytes in a file After writing the file the card is disconnected and the runtime of sent the command APDU is showed in the console Decrypt class This class is the responsible to decrypt a cipher text on the smart card It works in a similar way than Encrypt class At the first a communication channel is established with the smart card For the AES decryption it is necessary as parameter the key 32 Bytes and the cipher text The cipher text is read from the file C TMP output encrypted and the key is read from the file called c TMP key The method readFile Functions java is used to read the data from a file and to store it as array of Bytes The cipher text is multiple of 16 Bytes so padding is not necessary to calculate The problem of padding will appear after decryption process If the cipher text is higher than 16 bytes each sequence of cipher text of 16 Bytes is sent separately in the data field of its appropriate command APDU In each command the key and 27 goin A 2 Final Degree Project Antonio Bustos Rodr guez the cipher text are concatenated because the key is not stored in th
101. n connected devices ex Add On Dynamite PLUS v 2 0 SN 612204H1KAX2A876 1112 Main screen of the application To program the PIC based and AVR based smart cards supported by Cas Studio click on the button Card Programmer The following dialog displays below There are available the operations Read Write and Erase to the smart card The smart card will be recognized automatically after inserting in the programmer 19 sm p 4 Hd oom Final Degree Project Antonio Bustos Rodriguez Programmer M lt No card inserted gt lt No card inserted gt Internal EEPROM lt gt Flash memory lt gt External EEPROM lt gt lt gt No Configuration lt gt Fash memory C nema kea J emaren Yi Write El Read El Erase El Dialog of the Card Programmer No Image Upload a hex file into the smart card At first insert the card into the smart card connector of the Dynamite Plus programmer and the dialog displayed has to be like the below The smart card will be recognized automatically if does not click the button with the question mark to allow the smart card to be automatically identified 20 Antonio Bustos Rodr guez Internal EEPROM 512Byte Flash memory 8KByte External EEPROM lt gt 64KBit AT90S8515 Flash memory Internal EEPROM External EEPROM Dialog of the Card Programmer with the card rec
102. n the methods sendAPDUwithData sendSimpleAPDU and sendSimpleAPDUwithData public static long getTimeExecution return t2 tl readFile method The readFile method returns an array of bytes resulting of the read of a file located in the fileName path This method creates the objects File and FileInputStream to read the content of the file Previously of read the array of bytes is initialized with the length of the content of the file The exceptions FileNotFoundException IOException and Exception are caught and them respective error messages are showed in the console If finally there is not any data read the method returns null public static byte readFile String fileName File file FileInputStream fis byte data_read null 39 Pa Final Degree Project Antonio Bustos Rodr guez y int read 1 tryl file new File fileName fis new FilelnputStream file int N fis available data read new byte N read fis read data read catch FileNotFoundException ex1 System out println exl getMessage catch IOException ex2 System out println ex2 getMessage Jcatch Exception ex3 System out println ex3 getMessage if read 1 return data read jelse return null sendAPDUwithData method The sendAPDUwithData
103. nformation in the chapter 6 2 Electronic code book p 198 from Cryptography and Network Security Principles and Practice 2010 William Stallings AVR timers counters Timer Counter 0 TimerO is an 8 bit timer counter which can count from O to OxFF in the microcontroller ATmega163 The used registers are e Timer registers o TCCRO Timer Counter O Control Register o TCNTO Timer Counter 0 Value e Interrupt registers o TIFR Timer Interrupt Flag Register o TIMSK Timer Interrupt Mask Register o GIMSK General Interrupt Mask Register 10 ww Final Degree Project Antonio Bustos Rodr guez In the timer mode of operation the timer is provided by an internal signal After each clock cycle the value of the TCNTO register is increased by one The clock rate is x times the oscillator frequency The factor x can have the following values 1 8 64 256 and 1024 for example 1024 the timer is increased after 1024 cycles of the oscillator signal This prescaling is controlled by writing one of the following values into the register Initial value Used frequency 1 ck 2 ck 8 3 ck 64 4 ck 256 5 ck 1024 Timer Counter 1 In contrast to timer 0 timer 1 is a 16 bit timer counter in the microcontroller ATmega163 It can be used for longer counting sequences and the counting extent is between 0x0000 and OxFFFF The used registers are e Timer registers TCCR1A Timer Counter Control
104. nnnncnonononnnnnnnonnnononononnnnnnnnnnnononnnnnnncnnnnnnnnnnnnnnnnos 17 Cas Interface Studio vomita li ios 18 Upload a hex file into the smart Card coconnnccconcnncnoconononnnnnnnnnnnonononnnnnnnnnononononnnnnnnnnanano nacos 20 A II 23 AVR boa a o o O RR r 24 AVR ll varita 24 A A MM E 25 Project anay waa aaa daaa aa eaa Wa ahaaa uda UV aaa 26 Interface in Java with the smart card mani eee cnn rre rra nnn enne nnne 26 Encrypt elas iaa 26 Decrypt aaa 27 Enctypt2 aa E E E E E cad 28 D crypt2 ClaSS MEM 30 ATA 5 at b Final Degree Project Antonio Bustos Rodr guez SIAL NT 32 SHA256 das ni ias 32 SHA512Cl35S c O O 32 Details SC das caida 32 IS gre 33 NotEncrypt2 class it toU de ode ae oU Ee dex Dare eee ONES cas 33 NoEncrypt cldss ua daa bene eos 34 A go t S 36 Cryptographic applications on the smart card AES encryption and decryption 42 Header tiles 43 KI fe 44 External dependencia ada 54 Results and conclusion ee Eee reae terere toot onere Rea Rer ese eatis 55 Runtime Measurements AA ti Denuo coca euge cte bueno eu koz ccce nae oed ceu v st E Ee cen icono 55 CONCIUSIONS m AA 62 Bibliography ls ld ed O ES 64 erolla e h e E T INIT 67 Interface in Java with the smart card nennen enne nnne 67 Encrypt iii 67 Decrypt elass o III P M 68 ENCrypt2
105. not execute the encryption functions Without executing the encryption code the runtime of the encryption code can be calculated by subtracting of the runtime of Encrypt class and NoEncrypt class At the first a communication channel is established with the smart card As in Encrypt class the key 32 Bytes and the plain text are read The plain text has to be multiple of 16 Bytes so padding is calculated if it is necessary The byte padding used is PKCS7 this is described in RFC 3852 The padding is in whole bytes and the value of each added byte is the number of bytes is added The number of bytes added will depends on the block boundary to which the message needs to be extended in this case as maximum 16 plainText addPadding plainText If the plain text is higher than 16 Bytes each sequence of plain text of 16 Bytes is sent separately in the data field of its appropriate command APDU In each command APDU the key and the plain text are concatenated because the key is not stored in the smart card and each time is needed If the plain text is not higher than 16 Bytes the plain text and the key are concatenated in an array of bytes dataIn and a command APDU is sending to the smart card with this data The structure of the command APDU sent is showed below header command APDU INS 0x0D data field command APDU Key 32 Bytes Plain text 16 Bytes A Structure of the command APDU sent to the
106. o h gt include lt avr iom163 h gt include lt compat deprecated h gt J BRR RK kk kok kk kk kk Ck Ck A kok kok A kCk KC A A KCk KCk KCk KC kok kok k ck kc kck oe Routine performes AES encryption on an SIZE BLOCK AES byte input block Can be used for AES encrypt and internal authenticate CLA 0x80 INS 0x02 Pl length key plainText dataIn void do AES Encrypt command APDU com APDU response APDU resp APDU Extract dataIn from com APDU Call function encrypt with the dataIn and dataOut aes256 context ctx uint8 t key SIZE KEY AES uint8 t buf SIZE BLOCK AES uint8 t i for i 0 i SIZE KEY AES 1 key i com APDU data field i for i 0 i SIZE BLOCK AES i buf i com APDU data field i SIZ A K gt E 87 UM uM svie H F s a Final Degree Project Antonio Bustos Rodr guez aes256 init amp ctx key aes256 encrypt ecb amp ctx buf aes256 done amp ctx for i 0 i lt SIZE BLOCK AES i resp APDU data field i buf i resp APDU LE SIZE BLOCK AES resp APDU LEN SIZE BLOCK AES SIZE SW RESPONSE resp APDU SW1l SW1 SUCCESS Ox9F resp APDU SW2 SIZE BLOCK AES J BRR RK A oko kok A Ck kc k Ck Ck kCk Ck Ck A kCk KCk KCk KCk kok kok kok k ck k c
107. o make easier the routine actions like user identification user authentication data storage because they are devices with a small size and they can be carried in a simple wallet An example of usage of a smart card is the user authentication in a large companies or instutions to sign on or access in restricted areas To work with the contact smart card the card has to be inserted in the smart card reader and when the communication is done between the reader and the contact pads of the card so it is no necessary add a battery in the smart card because the energy is supplied by the reader to the card The smart cards are defined in the standards The ISO IEC 7816 and ISO IEC 7810 The standards define the physical characteristic of the card the communication protocol used basic functionality Command APDU The message structure used to transmit data between the smart card and the smart card reader is the Application Protocol Data Unit or commonly called APDU The structure of an APDU is defined by the ISO IEC 7816 standards and the concept of the command APDU is similar to the TCP IP protocol in networks A command APDU is composed with a header and with a command body The header consists of four bytes Class CLA Instruction INS Parameter 1 P1 and Parameter 2 P2 The class byte indicates the standard which the command is executed the instruction byte defines the command to execute and the two parameters P1 and P2 are used to tran
108. of the sending the command APDU is calculated and showed in the console At the end the card card is released NotEncrypt2 class This class works on the same way than Encrypt2 class but the difference is not using the same command in the smart card The NotEncrypt2 class executes the command INS AES NOT ENCRYPT V2 instead of INS_AES ENCRYPT V2 as Encrypt2 class The main of this class is to calculate the runtime of a command APDU with the same structure than in Encrypt2 class and with the same response APDU expected but the instruction INS AES NOT ENCRYPT V2 do not execute the encryption functions Without executing the encryption code the runtime of the encryption code can be calculated by subtracting of the runtime of Encrypt2 class and NotEncrypt2 class At the first a communication channel is established with the smart card As in Encrypt2 the key 32 Bytes and the plain text are read The plain text is read from the file called c TMP input and the key is read from the file called c TMP key The method readFile Functions java is used to read the data from a file and save it as array of bytes The plain text has to be multiple of 16 Bytes so padding is calculated if it is necessary The byte padding used is PKCS7 this is described in RFC 3852 The padding is in whole bytes and the value of each added byte is the number of bytes is added The number of bytes added will
109. ognized Select the files you wish to use for programming with the folder button normally in the Flash memory Click in the Write button You can also specify in which part you wish to write by clicking the side icon In the next images appears the process of upload a hex file into the smart card 21 p ja as SV 5 ame Final Degree Project Antonio Bustos Rodr guez n Programmer x Help r Configuration Memory Lock Internal EEPROM Mode 1 Off 512Byte Flash memory 8KByte External EEPROM lt gt 64KBit AT90S8515 Flash memory lt C Users antonio Documents e extemal N ib Dialog of the Card Programmer with the file to write selected Programmer x Fie Options r Configuration Memory Lock Internal EEPROM Mode 1 Off y 512Byte Flash memory 8KByte External EEPROM lt gt 64KBit AT90S8515 Flash memory lt C Users antonio Documents e z u w Wait Please Writing AT90S8515 Current progress Current progress Process of writing a file into the smart card 22 A Final Degree Project Antonio Bustos Rodr guez Programmer File Options AMEL FunCard Internal EEPROM 512Byte Flash memory 8KByte External EEPROM lt gt 64KBit AT90S8515 lt C Users antonio Documents ei PFC smartcard AVR AES_encrypt
110. ons to encrypt The loop consists in copy the data field of the command APDU com APDU to buf and after that copies the value of the array but in the data field of the response APDU resp APDU The loop starts to copy after the key for i 0 i SIZE KEY AES i key i com APDU data field i for i 0 i SIZE BLOCK AES i buf i com APDU data field i SIZE KEY AES for i 0 i SIZE BLOCK AES i resp APDU data field i buf i Finally the header of the response APDU resp APDU is composed with the value Ox9F Success in the status word 1 and the value 0x10 in the status word 2 number of bytes of data available to read in the data field command Handler function This is the main function of the source file functions smartcard c This function selects the code of the command implemented previously to execute depending of the class and instruction of the command APDU The node address NAD and the protocol control byte PCB of the response APDU resp APDU has the same value than the command APDU com APDU Depending of the block structure of the command APDU the system blocks S blocks are managed in a different ways than the information blocks I Blocks There are a switch to select the command to execute and if there is an error selecting the application the respond APDU is made up with the status word 6E 00
111. overview jsp consulted in November 2009 e Module scard article in pyscard sourceforge http pyscard sourceforge net epydoc smartcard scard scard module html consulted in November 2009 e Direct application selection article in CardWerk Smarter Card Solutions http www cardwerk com smartcards smartcard standard ISO7816 4 9 application independent_card_services aspx ISO7816 4_9 3 2 consulted in November 2009 e Triple DES article in Wikipedia publication in Internet http en wikipedia org wiki Triple DES consulted in November 2009 e Data Encryption Standard in Wikipedia publication in Internet http en wikipedia org wiki Data Encryption Standard consulted in November 2009 e Answer to reset article in Wikipedia publication in Internet http en wikipedia org wiki Answer to reset consulted in November 2009 e Advanced Encryption Standard article in Wikipedia publication in Internet http en wikipedia org wiki Advanced Encryption Standard consulted in December 2009 e Electronic codebook ECB section of the Block cipher modes of operation article in Wikipedia publication in Internet http en wikipedia org wiki Block cipher modes of operationfElectronic codebook _ 28ECB 29 consulted in December 2009 64 Final Degree Project Antonio Bustos Rodr guez STALLINGS William Cryptography and Network Security Principles and Practice Prentice Hall January 2010 5 edition Chapter 6 2 Electronic code book consulted p
112. protection of the information is an aim for the society and more and more people understand it like a right In the science computer the protection of the user space is a fascinating objective because it needs improvement constantly to prevent the attacks The user space is represented with all the files and messages which the users work daily and this user space can be more important than what users think because more and more the life of the users is exposed to the computer world The only solution to guarantee this security to the users it is use the cryptographic tools The cryptography has to guarantee the next properties e Privacy The files and messages used by a user have to be secret to everybody and privacy is sometimes related to anonymity e Integrity The files and messages received to a user have to be exactly in the same than the issuer user sent and by the way anybody should modify the data transmitted e Authentication The act of establishing or confirming a user as authentic that is that claims made by or about the subject are true e Irrefutability The fact that the sender of the information cannot deny that he has sent the information The symmetric key cryptography refers to encryption methods in which the information is encrypted and decrypted with the same key and this key is shared by the sender and receiver It is used to guarantee the privacy of the information because this information can be accessed only
113. r 1 because the timer 1 is a 16 bit timer and it has 2 registers to save the value The register TccR1a is set up to O to set the timer counter 1 in timer mode The register Tccr1B timer counter 0 control register is set up to 1 to set the oscillator frequency The variables cal ref timerl cal ref timerH cal ref timer2L and cal ref timer2H contains the clock cycles between the main loop cal ref timerL TCNT1L cal ref timerH TCNT1H for i 0 i lt N i buffer i com APDU data field i cal ref timer2L TCNT1L cal ref timer2H TCNT1H It is necessary to check if the register TIFR timer interrupt flag register is set to avoid an overflow in the measure of the values of the timer counter 1 if TIFR amp 0x04 0x04 overflow 1 cal ref timer2L 0x00 cal ref timer2H 0x00 The status word 1 of the response APDU resp APDU is sW1 success and the status word 2 is the amount of bytes in the data field in this case 5 The data field consists of 50 Final Degree Project Antonio Bustos Rodr guez e First byte value of cal ref timerH e Second byte value of cai ref timerL e Third byte value of overflow If this byte is set an overflow happened in the measure of the previous values and they are incorrect e Fourth byte value of cal ref timer2H e Fifth byte value of cal ref timer21
114. r 1 contains the number of blocks of 16 Bytes with cipher text as maximum 6 The parameter 2 is not required to have any value The data field of the command APDU contains the cipher text to decrypt in blocks of 16 Bytes as maximum 96 Bytes and 32 Bytes of the key In the subsection Decrypt2 class appears the structure of the command APDU and response APDU The variable n contains the number of blocks to decrypt indicated in the parameter 1 At the first the array of unsigned integer key and but are created with a length of 32 Bytes and the value of x respectively The key used in the decryption is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU If the number of blocks to decrypt n is higher than the maximum the response APDU resp APDU with the status word 6A 68 referenced data not found is returned and the command ends The structure aes256 content has to be initialized with the key After that appears the main loop that iterates depending the number of blocks to decrypt In each iteration the block t is copied in bur it is decrypted with the function aes256 decrypt ecb and the clear 47 F RN M Final Degree Project Antonio Bustos Rodr guez output buf is copied in the data field of the response APDU resp APDU After all the blocks are decrypted the function aes256 done release the key from the structure
115. rTextBuf 3 cipherText j a jelsel cipherTextBuf new byte MAX BYTES AES for int j 0 j MAX BYTES AES j cipherTextBuf j cipherText j i MAX BYTES AES dataIn concatenateArrayByte key cipherTextBuf int Pl dataIn length SIZE KEY AES SIZE BLOCK AES try dataOutBuf sendAPDUwithData CLA INS AES DECRYPT V2 P1 0 dataln channel time getTimeExecution catch NullPointerException exl System out println exl getMessage System exit 1 71 UM uM svie F Final Degree Project Antonio Bustos Rodr guez y for int j 0 j lt dataOutBuf length j dataOut j i SIZE BLOCK AES MAX N BLOCKS AES dataOutBuf j jelsel dataIn concatenateArrayByte key cipherText int Pl dataln length SIZE KEY AES SIZE BLOCK AES Revise Exception NullPointerException dataOutBuf sendAPDUwithData CLA INS AES DECRYPT V2 Pl 0 dataln channel time getTimeExecution for int i 0 i lt dataOutBuf length i dataOut i dataOutBuf i if ov32 dataIn concatenateArrayByte key cipherTextBuf2 cipherTextBuf2 length dataOutBuf sendAPDUwithData CLA INS AES DECRYPT dataIn length 0 dataln channel time getTimeExecution
116. re of the command APDU and response APDU The variable n contains the number of blocks to encrypt indicated in the parameter 1 At the first the array of unsigned integer key and buf are created with a length of 32 Bytes and the value of Nn respectively The key used in the encryption is stored in the array key and it is composed of the first 32 Bytes of the data field of the command APDU If the number of blocks to encrypt n is higher than the maximum the response APDU resp APDU with the status word 6A 68 referenced data not found is returned and the command ends The structure aes256 content has to be initialized with the key After that appears the main loop that iterates depending the number of blocks to encrypt In each iteration the block t is copied in buf it is encrypted with the function aes256 encrypt ecb and the cipher output buf is copied in the data field of the response APDU resp APDU After all the blocks are encrypted the function aes256 done release the key from the structure aes256 content aes256 init amp ctx key for i 0 i lt N 1 for j 0 j lt SIZE BLOCK AES j 48 F RN M Final Degree Project Antonio Bustos Rodr guez buf j com APDU data field SIZE KEY AES i SIZE BLOCK AES j aes256 encrypt ecb amp ctx buf for j 0 j SIZE BLOCK AES j resp A
117. rogrammer is connected it display the serial number of the programmer If a problem occurs or the device cannot be identified the application displays an error code AE Cas Acie Version 8 7 0 DEMO Mode WinDriver v xxx T qe 6 Dynamite PLUS Connected Waiting to start program 18 s WA d 5 w Final Degree Project Antonio Bustos Rodr guez The applications is recognizing the device The top panel of the window displays the menu that enables you to select the category of options you can enable These are e Smart card It is enabled for the devices Cas Interface 3 Cas Interface 2 Add on and Dynamite Plus It contains the programming tools for smart cards e Cam Module It is enabled for the devices Cas Interface 3 and Cas Interface 2 It contains the programming options for CAMs e Repair It is enabled for the device Cas Interface 3 only It contains the reparation options for CAMs e Receiver It is enabled for the devices Cas Interface 3 and Cas Interface 2 e Utilities It is enabled for the devices Cas Interface 3 Cas Interface 2 Add on and Dynamite CAS Studio v 8 7 0 F z smartcard cam Module 1 uM 1 Receiver pal utilities ETI Forum c y A CARD DU GENERATOR by gt CARD CARD SMARTCARD PROGRAMMER GENERATOR OPOS CARD MII CARD CEREBRO K3 CARD DIDEM CARD DA 1 ANACONDA CARD CARD GAMMA GAMMA CARD vrww duolabs com Options become available depending o
118. rom an attacker because the key is stored into the smart card but other security solutions can be integrated to this scenario 63 ATA 5 at e Final Degree Project Antonio Bustos Rodr guez Bibliography e Smart card article in Wikipedia publication in Internet http en wikipedia org wiki Smart_card consulted in November 2009 e Contactless smart card article in Wikipedia publication in Internet http en wikipedia org wiki Contactless smart card consulted in November 2009 e RANKL Wolfgang Smart card applications design models for using and programming smart cards Wiley June 2007 Chapters consulted o Chapter 2 3 3 Transmission protocols p 24 o Chapter 2 3 3 1 T 0 transmission protocol for contact smart cards p 25 o Chapter 2 3 3 2 T 1 Transmission protocol for contact smart cards p 25 e RANKL Wolfgang EFFING Wolfgang Smart Card Handbook Wiley January 2004 Chapters consulted o 6 5 2 Structure of the response APDU p 424 o 6 4 3 The T 1 transmission protocol p 409 o 114 1 PC SC p 667 o 114 4 MUSCLE p 672 o 6 2 Answer To Reset ATR p 377 e PC SC article in Wikipedia publication in Internet http en wikipedia org wiki PC SC consulted in November 2009 e Java Card article in Wikipedia publication in Internet http en wikipedia org wiki Java Card consulted in November 2009 e Java Card Technology Overview article in Sun Developer Network SDN http java sun com javacard
119. s processing speed The features of the AT90S8515 microcontroller are described below e 8K bytes of In System Programmable Flash e 512 bytes EEPROM e 512 bytes SRAM e 32 general purpose I O lines e 32 general purpose working registers connected directly to the Arithmetic Logic Unit ALU e Flexible timer counters with compare modes e Internal and external interrupts e A programmable serial UART programmable Watchdog Timer with internal oscillator an SPU serial port and two software selectable power saving modes The device is manufactured using Atmel s high density nonvolatile memory technology The On Chip In System Programmable Flash allows the program memory to be reprogrammed In System through an SPI serial interface or by a conventional nonvolatile memory programmer in the project Dynamite Plus Programmer By combining an enhanced RISC 8 bit CPU with In System Programmable Flash on a monolithic chip the Atmel AT90S8515 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications More details about AT90S8515 microcontroller in the official document of Atmel see Bibliography 15 we Final Degree Project Antonio Bustos Rodr guez ATmega163 The ATmega163 is a low power CMOS 8 bit microcontroller based on the AVR architecture The freguency of the microcontroller approximately is 1 MIPS per MHz allowing optimizing power consumption versus
120. sly header files and source files These external dependencies are provided by the modules available from AVR libc except the library 1ibT1 Comm Lib a that is added directly to the project and provides the functions related in the header file 1ibT1 Comm Lib n 54 t MJ E Para t Final Degree Project Antonio Bustos Rodr guez Results and conclusion Runtime measurements As a result of the code written several tests have been done in the code and the result has been successful The code to encrypt and to decrypt works fine and below appears the graphics of the runtime for each encrypt class Encrypt class and Encrypt2 class It is worth mentioning than in the Encrypt class when the command APDU is sent selects the do AES Encrypt function class 128 instruction 2 In the Encrypt2 class when the command APDU is sent selects the do AES Encrypt2 function class 128 instruction 8 The difference between these two functions is explained previously in the section AES encryption and decryption The stats of the runtime of Encrypt class and Encrypt2 class are detailed below The next stats have a margin of error as maximum of 3 or 4 milliseconds in 10 iterations so the results obtained are right Example runtime Encrypt class with 32 Bytes as plain text Average of 10 iterations 678 6 milliseconds 680 5 680 679 5 679 678 5 678 677 5 677 676 5 676 675 5 Milliseconds ms Iterations
121. smit extra information to the command The command body is composed with a maximum of three elements Lc length command Le length expected and the data field The length command defines the length of the data in the data field of the command APDU and the length expected contains the length of the data reguested from the smart card which is returned in the data field of the response APDU The data field is the part where the data is sent to the smart card and it has a maximum length of 256 Bytes Se Ja M Final Degree Project Antonio Bustos Rodr guez A command APDU has four different combinations and in the next image each combination is called a case The case 1 does not contain any command body the case 2 contains the byte Length command from the data field the case 3 is similar than the case 2 but in this case there are transmitted in the data field and the case 4 is the full command APDU Header Command Body Structure of the command APDU More information in the chapter 6 5 1 Structure of the command APDU from Smart Card Handbook 2004 Wolfgang Rankl and Wolfgang Effing Response APDU The response APDU is the reply of a command APDU and it is composed of the status word and the data field The status word SW1 and SW2 informs about the processing status of the command execution and it is composed of two bytes and the standard defines a serie of status word The data filed contains the data ret
122. sters to save the value The register TCCR1A is set up to O to set the timer counter 1 in timer mode The register rccr18 timer counter O control register is set up to 5 to set the oscillator frequency In this function the variable overflow does not exists cause it is stored in the byte eighteenth of the response APDU resp APDU This byte checks if an overflow happens between in sampling clock cycles To reduce memory usage of the function the variables to save the contents of the timer 1 before and after the encryption process are stored directly in the data field of the response APDU e 16 Byte value of the register TCNT1H before encryption process e 17 Byte value of the register TcnT11 before encryption process e 18 Byte value of the register TIFR overflow byte e 19 Byte value of the register TCNT1H after encryption process e 20 Byte value of the register TcNT1L after encryption process 51 Final Degree Project Antonio Bustos Rodr guez It is necessary to check if the register TIFR timer interrupt flag register is set to avoid an overflow in the measure of the values of the timer counter 1 resp APDU data field 18 0 resp APDU data field 17 TCNT1L resp APDU data field SIZE BLOCK AES TCNT1H aes256 init amp ctx key i aes256 encrypt ecb amp ctx buf aes256 done amp ctx if TIFR amp 0x04
123. stics are made with real data until 320 Bytes of plain text Each value is calculated from 10 iterations of runtime The statistic represents the runtime of encrypt 1 Byte depending the data field load of the command APDU 58 TA E Re A Final Degree Project Antonio Bustos Rodriguez The graph of time per byte in Encrypt class remains more or less lineal because the runtime to send a command APDU is always the same because the length of data field of this command APDU is always the same However the changes of size of the data field in the Encrypt2 class force to reduce the runtime in the first command APDU sent to encrypt the data but after that the graph remains more or less lineal Between sending an extra command APDU appears peaks in the same way than in Runtime of Encrypt class and Encrypt2 class H U1 HG o W e fa o a un 2 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 320 Time per byte Encrypt Time per byte Encrypt2 Bytes plaintext Time per byte Encrypt Time per byte Encrypt2 Bytes plain text 16 21 7625 21 8375 32 21 20625 18 009375 48 21 01875 16 67125 64 20 9484375 16 0296875 80 20 8275 15 6625 96 20 78333333 15 40416667 112 20 77232143 16 13035714 128 20 73671875 15 88125 144 20 72916667 15 68333333 160 20 714375 15 536875 176 20 70227273 15 41022727 192 20 709375
124. t byte dataOut2 new byte N for int i 0 i lt N itt dataOut2 i dataOut i return dataOut2 Send a APDU command with data and returns the data of the response APDU param clas param ins param Pl param P2 param dataIn param channel return byte throws NullPointerException t OR OR OR HF FF HF F x public static byte sendAPDUwithData int clas int ins int Pl int P2 byte dataIn CardChannel channel throws NullPointerException 78 UM uM as SY n H Final Degree Project Antonio Bustos Rodr guez byte dataOut null ResponseAPDU r null CommandAPDU c null try c new CommandAPDU clas ins Pl P2 dataln tl System currentTimeMillis r channel transmit c t2 System currentTimeMillis dataOut r getData catch CardException exl1 System out println Error sendAPDUwithData exl getMessage System exit 1 if r getSW1 159 NullPointerException ex2 new NullPointerException Error with the APDU response data returned invalid throw ex2 jelsel return dataOut Send a APDU command without data and returns the data of the response APDU Gparam clas param ins param channel Greturn byte throws NullPointerException x A A A A A HF F x public static byte sendSimpleAPDUwithData int clas int ins CardChannel channel throws NullPointerExcept
125. t card Encrypt class import javax smartcardio Class to encrypt data in the smart card without timers Input files 1 input this file contains the data to encrypt he 2 key this file contains 32 bytes of data that contains the key Output files El 1 output encrypted this file contains the data encrypted 87 public class Encrypt extends Functions public static void main String args long time 0 Card card connectCard CardChannel channel establishChannel card byte key readFile C TMP key byte plainText readFile C TMP input byte dataIn dataOut plainTextBuf dataOutBuf dataOut null plainTextBuf new byte SIZE BLOCK AES dataOutBuf new byte SIZE BLOCK AES plainText addPadding plainText dataOut new byte plainText length System out println Length data to encrypt plainText length try if plainText length gt SIZE BLOCK AES int N plainText length SIZE BLOCK AES for int i 0 i lt N itt take the segment of plainText to encrypt for int j 0 j lt SIZE BLOCK AES j plainTextBuf j plainText j i SIZE BLOCK AES dataIn concatenateArrayByte key plainTextBuf dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT 0 0 dataln channel time getTimeExecution for int j 0 j lt SIZE BLOCK AES dataOut j i SIZE BL
126. tes in the file located in the fileName path This method creates the objects File and FileOutputStream to write the content of the array and in the variable fis is written the entire array The exceptions FileNotFoundException the file to open denoted by a specified pathname has failed IOException if an I O error occurs and Exception are caught and them respective error messages are showed in the console public static void writeFile String fileName byte data write File file FileOutputStream fis tryl file new File fileName fis new FileOutputStream file fis write data write Jcatch FileNotFoundException ex1 System out println exl getMessage Jcatch IOException ex2 System out println ex2 getMessage Jcatch Exception ex3 System out println ex3 getMessage Cryptographic applications on the smart card AES encryption and decryption The code of AES encryption and decryption was developed with the integrated development environment AVR Studio version 4 17 For the development a project was created with the name AES encryption and decryption The organization of the project appears below The description of each section and the subsections appears later the organization e Source files o aes32 c o functions smartcard c o main c e Header files o aes32 h o functions smartcard h o
127. tes plain text Runtime NotEncrypt2 Bytes plain text Runtime Not Encrypt Runtime Not Encrypt2 16 124 9984 125 4 32 230 8993 164 3 48 336 7997 203 22 64 442 7989 242 3 80 548 5998 282 2 96 654 5998 321 2 60 om oa Final Degree Project Antonio Bustos Rodr guez 112 760 3997 426 9 128 866 2992 465 6 144 972 8999 506 1 160 1078 4999 544 9 176 1184 4998 584 1 192 1291 0995 623 55 208 1395 8996 729 6 224 1503 9968 769 240 1608 6983 808 4 256 1714 4994 847 7 272 1820 5998 886 9 288 1926 1999 925 9 304 2032 7999 1031 9 320 2137 9999 1071 3 Runtime of encryption code Encrypt2 class The next statistic represents the runtime of encryption code obtained from subtracting the runtime of the commands do AES Encrypt2 and test command withData2 The fact for which there is a difference between the runtime of Encrypt code and Encrypt2 code is because the structure aes256 context in the command do AES Encrypt2 Encrypt2 class is initialized and released one time for more than one block to encrypt Nevertheless inthe command do AES Encrypt this structure is initialized and released with a command APDU in other words with every block to encrypt 5000 4500 4000 3500 3000 2500 2000 1500 Milliseconds 1000 500 16 32 48 64 80 96 112 128 144 160 176 192
128. the response APDU obtained The global variables t1 and c2 are initialized to calculate the runtime of the command APDU The difference between this method and sendAPDUwithData is that the command APDU is built only with the variable cias defines the class in the header and with the variable ins defines the instruction in the header If the status word 1 of the response APDU is not 159 Ox9F the NullPointerException exception is thrown The CardException exception is caught if the card operation failed and its message is showed in the console public static byte sendSimpleAPDUwithData int clas int ins CardChannel channel throws NullPointerException byte dataOut null ResponseAPDU r null CommandAPDU c null tryl c new CommandAPDU clas ins 0 0 tl System currentTimeMillis r channel transmit c t2 System currentTimeMillis System out println r dataOut r getData Jcatch CardException exl System out println Error sendAPDUwithData exl getMessage System exit 1 41 P nza M Final Degree Project Antonio Bustos Rodr guez if r getSW1 159 NullPointerException ex2 new NullPointerException Error with the APDU response data returned invalid throw ex2 selse return dataOut writeFile method Y The writeFile method writes the data write array of by
129. tions public static void main String args Card card connectCard CardChannel channel establishChannel card sendSimpleAPDU CLA INS SIMPLE APDU channel System out println Time TestAPDU Functions getTimeExecution disconnectCard card NotEncrypt class import java io UnsupportedEncodingException import javax smartcardio Card import javax smartcardio CardChannel public class NotEncrypt extends Functions public static void main String args long time 0 Card card connectCard CardChannel channel establishChannel card byte key readFile C TMP key byte plainText readFile C TMP input byte dataIn dataOut plainTextBuf dataOutBuf dataOut null plainTextBuf new byte SIZE BLOCK AES dataOutBuf new byte SIZE BLOCK AES plainText addPadding plainText data0ut new byte plainText length System out println Length data to NOT encrypt plainText length tryl if plainText length gt SIZE BLOCK AES int N plainText length SIZE BLOCK AES for int i 0 i lt N itt u i take the segment of plainText to encrypt for int j 0 j lt SIZE BLOCK AES j plainTextBuf j plainText j i SIZE BLOCK AES dataIn concatenateArrayByte key plainTextBuf dataOutBuf sendAPDUwithData CLA INS AES NOT ENCRYPT dataIn length 0
130. tructure of the command APDU sent is showed below header command APDU CLASS INS P1 p2 0x80 0x09 0x06 0x00 data field command APDU Key 32 Bytes 1 Plain text 16 Bytes Structure of the command APDU sent to the smart card NotEncrypt2 class dataln concatenateArrayByte key plainTextBuf int Pl dataIn length SIZE KEY AES SIZE BLOCK AES dataOut sendAPDUwithData CLA INS AES NOT ENCRYPT V2 P1 0 dataIn channel The array of bytes aataout stores the plain text returned from the smart card and to check if the data received is correct the length of the plain text sent and the plain text returned has to be the same Plain text 96 Bytes Structure of the response APDU sent from the smart card NotEncrypt2 class At the end the card is released and the runtime of sent the command APDU without execute the encryption code is showed in the console NoEncrypt class This class works on the same way than Encrypt class but the difference is not using the same function in the smart card The NoEncrypt class executes the command INS AES NOT ENCRYPT instead of INS AES ENCRYPT as Encrypt class 34 v Sy 3 ate aM A Final Degree Project Antonio Bustos Rodr guez The main of this class is to calculate the runtime of a command APDU with the same structure than in Encrypt class and with the same response APDU expected but the instruction INS AES NOT ENCRYPT do
131. tware article in Wikipedia http en wikipedia org wiki Eclipse_ software consulted in November 2009 Eclipse Java development tools JDT Overview article in Eclipse website http www eclipse org jdt overview php consulted in November 2009 Padding cryptography article in Wikipedia http en wikipedia org wiki Padding cryptography consulted in January 2010 Java TM Smart Card 1 0 API in Package javax smartcardio http java sun com javase 6 docs jre api security smartcardio spec consulted in December 2009 Smart Card Authentication article in MSDN Library http msdn microsoft com en us library aa380142 v VS 85 aspx consulted in November 2009 65 ATA 5 at we Final Degree Project Antonio Bustos Rodr guez e Application Example and Algorithms article in Atmel website http www atmel com dyn products app notes asp part id 2027 consulted in November 2009 e GlobalPlatform article in Wikipedia http en wikipedia org wiki GlobalPlatform consulted in November 2009 e An Introduction to Java Card Technology article in Sun Developer Network SDN http java sun com javacard reference techart javacard1 consulted in December 2009 e Introduction to cryptography Part 2 Symmetric cryptography article in IBM deveolperWorks http www ibm com developerworks library s crypt02 html 66 UM uM sw F w Final Degree Project Antonio Bustos Rodr guez s Appendixes Interface in Java with the smar
132. ubBytes inv uint8 t buf register uint8 t i 16 while i buf i rj sbox inv buf i aes subBytes inv JK uzssscstusesSscecnedsocesesestcensscsteeseunsssseccsdiuessenesc AUAWA void aes addRoundKey uint8 t buf uint8 t key register uint8 t i 16 while i buf i key i aes addRoundKey prem A y void aes addRoundKey cpy uint8 t buf uint8 t key uint8 t cpk register uint8 t i 16 while i buf il cpk i key i cpk 16 1 key 16 i aes addRoundKey cpy E ee ee se ee ee ee void aes shiftRows uint8 t buf register uint8 t i j to make it potentially parallelable i buf 1 buf 1 buf 5 buf 5 buf 9 buf 9 buf 13 buf 13 1 i buf 10 buf 10 buf 2 buf 2 i j buf 3 buf 3 buf 15 buf 15 buf 11 buf 11 buf 7 buf 7 ji j buf 14 buf 14 buf 6 buf 6 j aes shiftRows A 55 SB ESSE a 5 A Sn S LE Au void aes shiftRows inv uint8 t buf register uint8 t i j same as above i buf 1 buf 1 buf 13 buf 13 buf 9 buf 9 buf 5 buf 5 84 Final Degree Project Antonio Bustos Rodr guez i buf 2 buf 2 buf 10 buf 10 i j buf 3 buf 3 bu 7 buf 7 buf 11 buf 11 buf 15 buf 15 ji j buf 6 buf 6 buf 14 buf 14 j aes shiftRows inv
133. urned from the smart card wich was processed into the smart card The length of the data field can be specified in the byte Le of the previous command APDU and the data field has a maximum length of 256 Bytes There are two variants for a response APDU and they are related in the next image The first variant is a reponse APDU without data field and the second variant returns data to the reader w Final Degree Project Antonio Bustos Rodr guez Case 1 response APDU Case 2 response APDU Trailer Body Structure of the response APDU More information in the chapter 6 5 2 Structure of the response APDU from Smart Card Handbook 2004 Wolfgang Rankl and Wolfgang Effing Transmission protocols There are two transmission protocols to transmit the data between the smart card and the reader The T 0 transmission protocol transmit the data per bytes and has a poor layer separation The T 1 transmission protocol transmit the data per blocks and is an asynchronous half duplex protocol for smart cards It is an improvement of the previous protocol because it has a strict layer separation This protocol features strict layer separation which means that data destined for higher layers such as the application layer can be processed completely transparently by the data link layer A block in the T 1 tranmission protocol consists of a prologue field an information field and a epilogue field The only part that is opt
134. x34 0x54 Oxee 0x08 0x76 0x72 Oxd4 0x6c 0x5e 0x90 Oxf7 0xd0 Oxcl 0x3a 0x97 0x96 Oxe2 0x47 Ox6f Oxfc 0x9a Oxif Oxbl 0x60 0x2d Oxa0 Oxc8 0x17 Oxel 0x09 0x40 0xe3 0x8e 0x7b Ox4c 0x2e 0x5b Oxf8 Oxa4 0x70 0x15 Oxd8 Oxe4 0x2c Oxaf 0x91 Oxf2 Oxac Oxf9 Oxf1 0xb7 0x56 Oxdb Oxdd 0x12 0x51 Oxe5 OxeO Oxeb 0x2b 0x69 Ox6a 0xa3 0x39 0x43 0x94 0x95 Oxal 0xa2 Oxf6 Ox5 0x48 0x46 Oxab 0x58 Oxle Oxbd 0x11 Oxcf 0x74 0x37 Oxla 0x62 0x3e O0xc0 0xa8 0x10 OxT f 0x7a 0x3b Oxbb 0x04 0x14 Oxd5 0x9e 0x82 0x44 0x32 0x0b 0x66 0x49 0x64 Oxcc 0x50 0x57 0x00 0x05 Ox8f 0x03 0x41 Oxce 0x22 Oxe8 0x71 0x0e 0x4b Oxfe 0x33 0x59 0xa9 Ox9f 0x4d 0x3c 0x7e 0x63 Oxf2 Oxfe Oxfa 0x9c 0x36 0x71 0x18 Oxeb Oxib 0x29 0x20 0x4a 0x43 0x50 0x92 0x10 Ox5f 0x64 0x22 Oxde 0x49 0x91 0x8d 0x65 Oxic Ox4b 0x48 0x86 0x69 Oxce Oxbf 0x50 ll 0x30 0x81 0x9b Oxc4 0xa6 0x42 0x28 0x6d 0x86 0x5d Oxfd 0xa7 0x8c Oxb8 Oxca 0x01 Ox4f Oxf0 Oxe7 Oxic 0x1d Oxaa Oxc6 0x78 0x88 0x27 0x19 0x93 Oxae 0x83 Oxba 0x55 0x6b Oxd7 0x59 0xa4 Ox3f Oxd8 0x96 0x27 Ox6e 0xe3 Oxfc Ox4c 0x4d 0x3c 0x9d Oxff 0x97 0x5d Ox2a Ox5e 0x06 0x95
135. ypt 16 Bytes each time The difference of runtime of the encryption code for 1024 Bytes of plain text is 1981 8002 milliseconds The most difference of runtime between Encrypt class and Encrypt2 class is when these classes send the data command APDU and receive the data response APDU The NotEncrypt and NotEncrypt2 classes have been used to calculate the runtime of send and receive the data without execute any encryption code in the smart card The difference is quite significant because sometimes the NotEncrypt2 class send 96 Bytes as plain text the maximum available capacity of the command APDU With 1024 Bytes of plain text the difference between NotEncrypt and NotEncrypt2 classes reaches until 3533 6998 milliseconds The limit of 96 Bytes to send or receive with the smart card is not the maximum due theoretically the data field of a command APDU has 256 Bytes as maximum length In this 62 F RN M Final Degree Project Antonio Bustos Rodr guez case if sent more than 96 Bytes the smart card return an error code due an overflow with the memory thus is another limit to not reduce the runtime of Encrypt2 class The smart card can be used to encrypt small pieces of plain text because the runtime of encryption is more or less acceptable until 1024 Bytes To encrypt higher amounts of plain text these functions are not recommended because the smart card will spent more than 15 seconds to do the encryption The implementation o
136. yte plainText length if N 0 if plainText length SIZE BLOCK AES MAX N BLOCKS AES O N for int i 0 i lt N itt int a i SIZE BLOCK AES MAX N BLOCKS AES int b i 1 SIZE BLOCK AES MAX N BLOCKS AES if plainText length lt b plainTextBuf new byte plainText length a for int j 0 j plainText length a j plainTextBuf j plainText jtal jelse plainTextBuf new byte MAX BYTES AES for int j 0 j MAX BYTES AES j plainTextBuf j 69 UM uM svie H F w Final Degree Project Antonio Bustos Rodr guez s plainText j i MAX BYTES AES dataIn concatenateArrayByte key plainTextBuf int Pl dataIn length SIZE KEY AES SIZE BLOCK AES tryl dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT V2 Pl 0 dataln channel time getTimeExecution Jcatch NullPointerException ex1 System out println exl getMessage System exit 1 for int j 0 j lt dataOutBuf length j dataOut j i SIZE BLOCK AES MAX N BLOCKS AES dataOutBuf j jelsel dataIn concatenateArrayByte key plainText int Pl dataln length SIZE KEY AES SIZE BLOCK AES Revise Exception NullPointerException dataOutBuf sendAPDUwithData CLA INS AES ENCRYPT V2 Pl 0 dataln
137. ytes buf aes shiftRows buf aes expandEncKey ctx gt key amp rcon aes addRoundKey buf ctx gt key aes256 encrypt 86 UM uM sw F s x Final Degree Project Antonio Bustos Rodr guez void aes256 decrypt ecb aes256 context ctx uint8 t buf 1 uint8 t i rcon aes addRoundKey cpy buf ctx deckey ctx gt key aes shiftRows inv buf aes subBytes inv buf for i 14 rcon 0x80 i if isl aes expandDecKey ctx gt key amp rcon aes addRoundKey buf amp ctx gt key 16 else aes_addRoundKey buf ctx gt key aes mixColumns inv buf aes shiftRows inv buf aes subBytes inv buf aes addRoundKey buf ctx gt key aes256 decrypt functions smartcard c J ECKCKCKCkCkCkCk kk Ck A A A A A A A A A k kk k Ck k ck k ck k ck ck ck ck ckckokok R This is the implementation of a basic smart card OS supporting the T 1 protokoll Ck ck ck ck kck ck ck ck A ck ck K AZ A K A A KA ZAZ kk AZ A AZ KA kk AKA A KA KAZ ZK A A ZA KA KK ck ck kk kk KEKKK KK AK AA KA KAZ AK K A A AA ZA KAZ AKA A KA KA ZK KK kk kc File functions smartcard c i KCKCKCKCkCkCkCk Ck k Ck k Ck k Ck k k ck k ck k ck Ck ck k ck ck ck ck ckck ckokckok ok ke include string h include functions smartcard h include globals h include T1 Comm Lib h include aes32 h include lt avrisfr defs h gt include lt avr i
138. ython Perl PHP and it offers a multiple tools with the plug in available to install in Ecliplse Released under the terms of the Eclipse Public License Eclipse is free and open source software Java interface pc smart card src src2 Functions java Eclipse nx File Edit Source Refactor Navigate Search Project Scripts Run Window Help E gt E e ji ela 1 0 18808 a 5 Package Explorer 2 l Functions java 23 D BE outine 3 _ a B E 7 gt 12 interface pesmartcard gt jS src gt E src2 Functions P gefTimeExecutionO long TO wt 7 e E interface pe smart card 1 package src2 8 os E EB sre 2 import dedarations E B default package import java io File EQ Functions EB sez B E SIZE BLOCK AES int Deaypt java SIZE KEY AES int Functions to use with the interface smart card ad Decrypt2 java P MAX_N_BLOCKS_AES amp amp J DetalssC java iuis BF MAX BYTES AES int E J Encryptjava x SF ga nt 21 F nt D Encrypt2 java 22 public class Functions A Wi AES wanami 1 Functions java 23 public static final int SIZE BLOCK AES 16 r INS _AES_ENORYPT_V2 a D SHAL java 24 public static final int SIZE KEY AES 32 E an EN J SHA256 Java 25 public static final int MAX N JNS AES DECRYPT V2 SHAS12 java 26 public static final int MAX B INS SHAL J TestaPDU java 2 public static final int CLA gt PF INS SHA256 int TestaPDUwithData java publ
Download Pdf Manuals
Related Search
Related Contents
Xerox WorkCentre C226 PSG 29 et 30 octobre 2013 50 m illions d`arbres Sierra Wireless DART 300 Modem User Manual IAN 78834 - Lidl Service Website Copyright © All rights reserved.
Failed to retrieve file