Rem Autor:@@Jan Klečka@@
Rem ------------------------------------------------------------------
'~ Karta je zde v roli Terminálu, tedy ověřovatele. Porovnání hodnot R1 a R2 
'~ je zde pomocí SW1 a SW2 bitu. Terminál porovná, zda hodnota po příkazu je 90 00.
'~ Při předávaní hodnot R1 ze strany terminálu.
Rem ------------------------------------------------------------------
Option Explicit

#Include COMMANDS.DEF
#Include ECCARD.DEF
#include MISC.DEF
#include SHA.DEF
#include TLV.DEF
#Include Card.def
#include EC-p.def
#include Funkce.def

Declare Key 1(16) 


EEPROM Kr1$
EEPROM e$

EEPROM prk$
EEPROM pubk$

EEPROM pubkTerm$
Const UsedCurveIndex=7
call ECpSetCurve (UsedCurveIndex)

Command &H20 &H00 GetCurveIndex (CurveIndex As Integer)
  CurveIndex = UsedCurveIndex
End command


Command &H88 &H01 GenerujKlice()
call GenerujObaKlice(prk$,pubk$)
If LibError <> 0 Then SW1SW2 = LibError : LibError = 0 : exit command
end command


Command &H88 &H03 DostanVerejnyKlic (PublicKey$) 
PublicKey$ = pubk$
If LibError <> 0 Then SW1SW2 = LibError : LibError = 0 : exit command
end command


Command &H88 &H06 VytVorKlicProSifru(PublicTerminalu$)
private temp$
private klicKarta$
private KlicTerminal$
klicKarta$ = prk$
KlicTerminal$ = PublicTerminalu$
call EcpMultiplyPoint(KlicTerminal$,klicKarta$)
temp$  = Mid$(KlicTerminal$,1,32)
Key(1) = temp$
If LibError <> 0 Then SW1SW2 = LibError : LibError = 0 : exit command
end command

Command &H88 &H07 ZiskejPublicTerminalu (PublicTerminalu2$)
 PublicTerminalu2$= pubkTerm$
end command


Command &H88 &H13 PredejKr (Data2$)
e$ = Vyzva()
Data2$  = Kr1$ +e$
If LibError <> 0 Then SW1SW2 = LibError : LibError = 0 : exit command
End Command


Command &H88 &H11 Vypocitej_Kr1 ()
Private Kcs$
Private IDr1$

Kcs$ = GenerujK_CS()
IDr1$ = GenerujID_R1()

private HashBuff$
call Sha256Start(HashBuff$)
call Sha256Append (HashBuff$,Kcs$)
call Sha256Append (HashBuff$,IDr1$)


Kr1$ = Sha256End(HashBuff$) 
end command

Command &H88 &H12 VypocitejR2 (DataZterminalu$)
Private R1$
private R2$
private IDg1$
R1$=Left$(DataZterminalu$,32)
IDg1$ = Right$(DataZterminalu$,8)

private pomocna$
private KR1_ID_G1$

private HashBuff$
call Sha256Start(HashBuff$)
call Sha256Append (HashBuff$,Kr1$)
call Sha256Append (HashBuff$,IDg1$)

KR1_ID_G1$ = Sha256End(HashBuff$)

call Sha256Start(pomocna$)
call Sha256Append(pomocna$,KR1_ID_G1$)
call Sha256Append(pomocna$,e$)
R2$ = Sha256End(pomocna$)

if R1$ <> R2$ then
SW1 = 55
SW2= 55
exit command
end if

If LibError <> 0 Then SW1SW2 = LibError : LibError = 0 : exit command

end command


