<?php 
		require_once("config/connect.php");
		$aesKey=false;
		$kassaId=false;
		$getSigCard=mysql_query("SELECT * FROM konfiguration_sitpos");
		while($sigData=mysql_fetch_array($getSigCard)){
			if($sigData['name'] == 'AES_KEY')$aesKey=$sigData['wert'];
			if($sigData['name'] == 'KASSA_ID')$kassaId=$sigData['wert'];
		
		}
		
		$revDecoded=false;
		date_default_timezone_set('Europe/Vienna');
		
		if(isset($_POST['runKarte']) ){
			initialisiere_com();

		
		}
		if(isset($_POST['runKarteShort']) ){
			initialisiere_com_short();

		
		}
		if(isset($_POST['decodeRev']) ){
			$lastDepRev=mysql_fetch_array(mysql_query("SELECT umsatz_zaehler_aes, beleg_nr FROM  dep where beleg_nr = (SELECT max(beleg_nr) FROM  dep)"));
			if($_POST['umsatzCodiert'] == true && strlen($_POST['umsatzCodiert']) > 5 ){
				$revenueCoded=$_POST['umsatzCodiert'];
				if($_POST['bonNr'] == true && $_POST['bonNr'] > 0 )$bon_id=$_POST['bonNr'];
				else $bon_id = 1;
			}
			else{
				$revenueCoded=$lastDepRev['umsatz_zaehler_aes'];
				$bon_id = $lastDepRev['beleg_nr'];
			}
			#else $revenueCoded="";
			
			if($_POST['aesKey'] == true && count($_POST['aesKey']) > 5 )$aesKey=$_POST['aesKey'];
	
			$Umsatz2="";
			$umsatzZaehler="12355588";
			
			
			$karte= new COM('ATrustRegistrierkasseCom.AesIcm');
			$aesCrypt = new COM('ATrustRegistrierkasseCom.AesIcm');
			
			#$retVal = $aesCrypt->Encrypt($aesKey, $umsatzZaehler, $kassaId, $bon_id, $revenueCoded);
			#echo "-".$aesKey."-".$umsatzZaehler."-".$kassaId."-".$bon_id."-####".$revenueCoded."##<br />";
			#echo $revenueCoded."<br />";
			
			#echo "<hr />retourrechnen<hr />";
			#echo "<br />".$aesKey."<br />Umsatz Codiert: ".$revenueCoded."<br />kassa Id: ".$kassaId."bon nr: ".$bon_id." / ".$Umsatz2."<br />";
			$retVal = $aesCrypt->Decrypt($aesKey, $revenueCoded, $kassaId, $bon_id, $Umsatz2);
			$revDecoded="<br />ausgangswert: ".$revenueCoded.", ".$aesKey.", ".$bon_id." Ergebnis:".$Umsatz2;
			#echo "<br />Ergebnis: <br />Aes Key: ".$aesKey."<br />".$retVal."<br />Umsatz: ".$Umsatz2."<br />";
			
			
			
		}
		
		echo "<form action='atrustcom.php' method='post'>
				<input type='hidden' name='runKarte' value='zuz' />
				<input type='submit' value='Run Karte Funktion' />
			</form>";
		
		echo "<form action='atrustcom.php' method='post'>
				<input type='hidden' name='runKarteShort' value='zuz' />
				<input type='submit' value='Run Karte Funktion Check Karte Only' />
			</form>";
			
		echo "<form action='atrustcom.php' method='post'>
				<p>Wenn keine ins Feld umsatz und beleg nr eingegeben werden, wird die höchste bon nur aus der DB genommen</p>
				<input type='hidden' name='decodeRev' value='zuz' />
				verschlüsselter Umsatzzähler:<input type='text' name='umsatzCodiert' /> bon Nr:<input type='text' name='bonNr' />
				aes key:<input type='text' name='aesKey' /><br />
				<input type='submit' value='Umsatzzähler decodieren' />
				<br />".$revDecoded."
			</form>";
			
		function initialisiere_com_short(){
			$karte = new COM('ATrustRegistrierkasseCom.Registrierkasse');
			 $retIni=$karte->Initialize;
			 echo "Ergebnis Initialize Card: ".$retIni."<br />";
			$retCheck=$karte->CheckCard;
            echo "Ergebnis Check Card: ".$retCheck."<br />";
			
		}

		function initialisiere_com(){
                               $karte = new COM('ATrustRegistrierkasseCom.Registrierkasse');
                            #   echo "----".$karte."<br />";
                               $ret=$karte->CheckSoftware;
                               echo "Ergebnis Check Software: ".$ret."<br />";
                               $ret=$karte->Initialize;
                               echo "Ergebnis Initialize: ".$ret."<br />";
                               
                               $ret=$karte->CheckCard;
                               echo "Ergebnis Check Card: ".$ret."<br />";

                               $ret=$karte->LoadInfo;
							   echo "Ergebnis Load Info: ".$ret."<br/>";
							   echo "<br />-----------------------------------<br />";
									#  echo "<b>".$ret."</b>";
                               echo "Karten Informationen : \n<br />";
                               echo "<b>".$karte->ZdaId . "</b><br />";
							   echo "Karten Seriennummer : \n<br />";
                               echo "<b>".$karte->CertificateSerial."</b><br />";
							#   $xZ="";
							#   $zuz=$karte->Certificate($xZ);
							#   echo "<br />----------------".$xZ."<br />";
					/*		
							 echo "<h4 style='margin:5px 0; padding:2px 0;'>AES Prüdsumme berechenen</h4>";
	 
								$aesKey="5N/s/o9r+aU+fF2fHWBdfh5AQNOvxYkoO8huskSSO08=";
								

							echo "<p>".$aesKey."</p>";
							
							
							$hashResult = hash('sha256', $aesKey);	
							echo "<p>sha256: ".$hashResult." / ".strlen($hashResult)."</p>";
							


							$nN=3;
							$cH1=substr($hashResult, 0, 2);		# lt AES_Pruefsummenberechnung_200716_3.pdf werden die ersten 3bytes, das sind 6 hexstellen genommen		
							$cH2=substr($hashResult, 2, 2);
							$cH3=substr($hashResult, 4, 2);
							
		
						#	echo "<p>".$cuttedHash1."- ".$cuttedHash2."- ".$cuttedHash3."</p>";
							
						#	$cH1='0x'.$cuttedHash1;
						#	$cH2='0x'.$cuttedHash2;
						#	$cH3='0x'.$cuttedHash3;
							

							$xStr=chr('0x'.$cH1).chr('0x'.$cH2).chr('0x'.$cH3);
							echo "<p>:::::::::::::::".$xStr."</p>";
							echo "<p>".base64_encode($xStr)."</p>";
							
							$str=chr(0x1c).chr(0x73).chr(0xd8);
							echo "<p>".$str."</p>";
							echo ("reini Base64:".base64_encode($str));

							
							
							echo "<p>ersten ".$nN." Zeichen vom sha256: ".$cuttedHash."</p>";
							
							$cuttedHashBase64=base64_encode($cuttedHash);	
							
							echo "<p>Base64 Encode: ".$cuttedHashBase64." / ".strlen($cuttedHashBase64)."</p>";
								$valSumCalc=preg_replace('/=/', '', $cuttedHashBase64);
								
							echo "<p>Base64 Encode (repalaced =): ".$valSumCalc." / ".strlen($valSumCalc)."</p>";
								
								echo "<br />Ausgabe Prüfsumme:<br >";
								echo "<b>".$valSumCalc."</b>";
							   
							   echo "<b>Das Certificate !!!<br />".$karte->Certificate."</b><br />";
							   
							   echo "<b>Das IssuerCertificate !!!<br />".$karte->IssuerCertificate."</b><br />";
							   $cardInfo="";
							 #  $retInfo=$karte->LoadInfo($cardInfo);
							#   echo "<br />###########################################<br />".$cardInfo."<br />###################################<br />";
							
								echo "<br />##############################################################################<br />";
								$aesClass = new COM('ATrustRegistrierkasseCom.AesIcm');
								$aesKey="";
								$retAes=$aesClass->GenerateKey($aesKey);
								
								echo "<br />".$aesKey."<br />";
								
								echo "<br />##############################################################################<br />";
							   
							   $shaClass = new COM('ATrustRegistrierkasseCom.Sha256');
							   echo "##########################+++++++++++++++++++++++++++++++++###################";
							   $sigVorigerBeleg="";
							   $lastSignJwsData="eyJhbGciOiJFUzI1NiJ9.X1IxLUFUMV9zSVRQT1M1MzcxXzE5NzJfMjAxNi0wOS0yNlQxNToyODozNV8zLDIwXzMsMDBfMCwwMF8wLDAwXzAsMDBfYy9lMExBU0lEa0xYVW5hekFRTU11QT09XzFiNzI2MV9rMys5cTZLa253az0.Ry0JPsQ5hZDMqcriD4b4crZW2rAitBLsX_TmcFbWX-Tlex2OXsNNE-H3keBYYFGCtjRbU0SFy7-NSD8kLuQHdw";
							 $lastSignJwsData="sITPOS9619";
							 $retVal=$shaClass->HashSigVorigerBeleg($lastSignJwsData, 8, $sigVorigerBeleg);
							 
							  
							  echo "Ergebn has sign voriger belegggggg: <br /><b>".$sigVorigerBeleg."</b><br />";
							   $strToSign="fdfghjkjhgfdfghjhgfrfggftftgghzghzhghggfdsertfvgztghzghghtgfgtfggfgtfgh";
							   $signature="";
							   $retVal=$karte->SignJWS($strToSign, $signature);
							    echo "Signieren!!!!: <br /><b>".$signature." / ".$retVal."</b><br /><hr />";
								
								
                               
							echo "<br />#####################################<br />";   
							
							  $base64Cl= new COM("ATrustRegistrierkasseCom.Base64");
							  
							  
							  $strToSign="_R1-AT1_sITPOS5371_2001_2016-09-27T10:26:58_0,00_15,00_85,00_2,09_0,00_SRleqQ9MHG/X2UfdTtn1HQ==_1b7261_Zcmb+fbdx/M=";
							  $reencodeOp="";
							  $jwsPayLoad="";
							  $jwsSigAusgef="";
							  $retVal=$base64Cl->EncodeUrl($strToSign, 0, $jwsPayLoad);
							  $retVal2=$base64Cl->EncodeUrl("Sicherheitseinrichtung ausgefallen", 0, $jwsSigAusgef);
							  
							  echo "jwsPayLoad:<br />".$jwsPayLoad."<br />";
							   echo "jwsSign Ausgefallen:<br />".$jwsSigAusgef."<br />";
								
							echo "<br />#####################################<br />";
								$jwsHeader=base64_encode('{"alg":"ES256"}');
								
								$signString=$jwsHeader.".".$jwsPayLoad.".".$jwsSigAusgef;
								
								$signString="eyJhbGciOiJFUzI1NiJ9.X1IxLUFUMV9zSVRQT1M1MzcxXzIwMTdfMjAxNi0wOS0yN1QxMjowNDo1N18xLDYwXzAsMDBfMCwwMF8wLDAwXzAsMDBfYllNenFIQU50WjZWdDJ4L1VLTGFyQT09XzFiNzI2MV9sY1VlZHRpejlXOD0.bWOPE9fjy7XlWZnzPtXZDZAdJ_hnSh_0UD9Q0ztS80ApjF6yrkmxpZdnn0IxokUPkcOv7o5ZHp_PAUEYhm3Hfg";
								
								$getQrData=explode(".", $signString);
								
								$commandReQ3="C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --base64_url_to_normal_reencode ".$getQrData[2];
								exec($commandReQ3, $outputReQ3, $error_code);
								$qr_3=$outputReQ3[0];
								
								$commandReQ2="C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --base64_url_to_normal_reencode ".$getQrData[1];
								exec($commandReQ2, $outputReQ2, $error_code);
								$qr_2=$outputReQ2[0];
								
								$qrString=base64_decode($qr_2)."_".$qr_3;
								
								echo "test mit qr final string: <br />Row String:<br />".$signString."<br />String Splited:
										<br />".$getQrData[0]."<br />".$getQrData[1]."<br />".$getQrData[2]."<br />";
								echo "-------------------------------------------------------!<br />";
								echo "QR-Code Result mit Exe:<br />".$qrString."<br /><br />";
								
								
								$base64Class= new COM("ATrustRegistrierkasseCom.Base64");
								$qr_3="";
								$retVal=$base64Class->ReencodeNormalToUrl($getQrData[2], 0, $qr_3);
								
								$qr_2="";
								$retVal=$base64Class->ReencodeNormalToUrl($getQrData[1], 0, $qr_2);
								
							#	$qrString=base64_decode($qr_2)."_".$qr_3;
								$qrString=base64_decode($qr_2)."_".$getQrData[2];
								
								
								
								echo "QR-Code Result mit Com:<br />".$qrString;
								
								$headerStr='{"alg":"ES256"}';
								
								$headerCoded="";
								$retVal=$base64Class->EncodeUrl($headerStr, 0, $headerCoded);
								
								$refHeaderDetailDoc="eyJhbGciOiJFUzI1NiJ9";
								if($refHeaderDetailDoc == $headerCoded) $checkH="<b>Header Result = gleich.</b><br />";
								else $checkH="<b>Header Result passt NICHT !!!!!</b><br />";
								
								echo "<br />-------------------------------------------------<br />Aufebreitung Maschienlesbarer Code, Ablage vom Header u Paylod in Base64 Url<br />";
								echo 'Ausgangs Daten<br />Header String: '.$headerStr.', Header Base64 Url: '.$headerCoded.', '.$checkH.'<br />';
								echo "Signieren: <br />";
								
							#	$karte = new COM('ATrustRegistrierkasseCom.Registrierkasse');
							#	$retVal=$karte->Initialize;					weiter oben schon passiert ????
							
							#_R1-AT0_DEMO-CASH-BOX524_366588_2015-12-17T11:23:44_0,00_0,00_0,00_26,05_0,00_m8LGyyY4UAA=_20f2ed172daa09e5_5HjRCx+XIz4=
							
								$paylRow="_R1-AT75_DEMO-CASH-BOX524_366585AB_2015-12-17T11:23:43_0,00_0,00_0,00_0,00_0,00_5/4fWv5/uhI=_245abcde_lDUkNhEeJKY=";
								$paylRow2="_R1-AT0_DEMO-CASH-BOX524_366596_2015-12-17T11:23:44_0,00_0,00_3,64_-2,60_1,79_VFJB_47be737cb1f6d1f1_ZvNxJw6a1A4=";
								$refPayl2="eyJhbGciOiJFUzI1NiJ9.X1IxLUFUMF9ERU1PLUNBU0gtQk9YNTI0XzM2NjU5Nl8yMDE1LTEyLTE3VDExOjIzOjQ0XzAsMDBfMCwwMF8zLDY0Xy0yLDYwXzEsNzlfVkZKQl80N2JlNzM3Y2IxZjZkMWYxX1p2TnhKdzZhMUE0PQ.J7YC28zquHfHzMpx02TqElbXOTSgXQu5JAA9Xu1Xzzu5p8eUYT-sgmyhzRps5nYyEp5Yh8ATIa9130zmuiACHw";
								
								
								$signature="";
								$retVal=$karte->SignJWS($paylRow2, $signature);
								
								echo "#######################<br />".$signature."<br />########################";
								
								if($signature == $refPayl2) $checkSign="<b>Signieren Result = gleich.</b><br />";
								else{
									$checkSign="<b>Signieren Result NICHT gleich !!!!!!!</b><br />";
									echo "Result Signatur:<br />".$signature."<br />";
									echo "Reference:<br />".$refPayl2."<br />";
									
								}
								
								echo $checkSign;
								
								echo "<br />Reencode (bas64) beispiel aus Docu:<br />";
								
								echo base64_decode("X1IxLUFUMF9ERU1PLUNBU0gtQk9YNTI0XzM2NjU5Nl8yMDE1LTEyLTE3VDExOjIzOjQ0XzAsMDBfMCwwMF8zLDY0Xy0yLDYwXzEsNzlfVkZKQl80N2JlNzM3Y2IxZjZkMWYxX1p2TnhKdzZhMUE0PQ");
							
							
							
							
							echo "<br /><span style='color:red'>#####################################</span><br />";
							echo "QRCode Aufbereiten, 3ter wert aus signatur String";
								$qrSigTeil=explode(".", $signature);
								$qr_3="";
								$retVal=$base64Class->ReencodeUrlToNormal($qrSigTeil[2], $qr_3);
								
							echo "<br />base64 Qr Sig Teil: <br />".$qr_3."<br />";
							
							echo "<br />Qr Test AUS<br />";
							   
							   
                               
							$start=microtime(true);

                               $signature="";
                               $karte->Sign("eyJhbGciOiJFUzI1NiJ9.UjEtQVQxX0RFTU8tQ0FTSC1CT1...A6MjNfMA==", $signature);
                               echo $signature ."\n<br />";
                              $time_elapsed_secs = microtime(true) - $start;

                               echo "<br />Run Time: ".$time_elapsed_secs . "<br /><hr />";
							   
							   echo "<hr /><br /><hr />";
							   
							   $strToSign="_R1-AT1_sITPOS5371_1979_2016-09-26T17:16:14_2,20_0,00_0,00_0,00_0,00_Cv8l5z7IqhDdMDd6Kau0KA==_1b7261_IBJLx/RQlCA=";
							   
							   $commandBase64UrlCodierenPayload="C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --base64url_encode ".$strToSign;
								exec($commandBase64UrlCodierenPayload, $outputCodingP, $error_code);
								$jwsPayLoad=$outputCodingP[0];
								
								$encodeOp="";
								$tmp="";
							#	$retVal=$base64Class->Encode($strToSign, $tmp);
								$retVal=$base64Class->EncodeUrl($strToSign, 0, $encodeOp);
								
								echo "jwsPayLoad from com<br /><b>".$encodeOp."</b><br />";
								echo "jwsPayLoad from exe<br />".$jwsPayLoad."<br /><br /><hr />";
								
			*/
							   
                }

		


	function aesFuntions(){
		echo "<hr />da kommen dann die aes ...<br >";		
	
		 $aesX = new COM('ATrustRegistrierkasseCom.AesIcm') or die("Cannot start AesIcm");
		$start=microtime(true);
		$aesKey="1u3M2/8xAap/3STHbwUHSrLI8suZWnTkhJbKhH4+Uic=";
		$umsatzZaehler=10457;
		$kassaId="sITPOS5371";
		$bon_id=1055;
		
		//$ret=$aesX->Initialize;
		$key="";
		$ret=$aesX->GenerateKey($key);
		
		echo $key."<hr />";
		
		
		
		
		echo"<hr />ab hier kommt das Exe !!!!<br />";
		
		
		$command='C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --aes_encrypt --aes_key '.$aesKey.'  --umsatz '.$umsatzZaehler.' --kassenid '.$kassaId.' --belegnummer '.$bon_id.' ';
		
		exec($command, $output, $error_code);
		
		echo "<br />".$output[0]."<br />";
		
		$revenueCoded=$output[0];
		
		echo "<br />umsatz Null von schlögel<br />";
		$revenueCoded="91w+4op3jBgJZwXJTuWSqQ==";
		$aesKey='eJcwvKV7Qh/mfp3etN/y+mJoLKwGzMGVt6mzYGSdEuQ=';
		$kassaId='sITPOS9619';
			
		$commandCheck='C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --aes_decrypt --aes_key '.$aesKey.'  --encrypted_data '.$revenueCoded.' --kassenid '.$kassaId.' --belegnummer '.$bon_id.' ';
		exec($commandCheck, $outputCheck, $error_code);
		
		echo "<br />".$outputCheck[0]."<br />";
		
		$time_elapsed_secs = microtime(true) - $start;

        echo "<br />Run Time: ".$time_elapsed_secs . "<br /><hr />";
		
		echo "hash voriger beleg:<br />";
		
	#	$commandSigVorig="C:\sitpos\_rkExe\ATrustRegistrierkasseExe.exe --hash_sig_voriger_beleg ".$lastSignJwsData."";
	#	exec($commandSigVorig, $outputSigVorig, $error_code_sigVorig);
		
	#	echo "<br />".$outputSigVorig[0]."<br />";
		$time_elapsed_secs = microtime(true) - $start;

        echo "<br />Run Time: ".$time_elapsed_secs . "<br /><hr />";
		 
		# echo $aesX->GenerateKey;
		 
		 #$checkOpbj=serialize($aesX);
		 
		# echo $checkOpbj."<br />";
		
	#	print_r(get_object_vars($aesX->GenerateKey));
	#	 echo $aesX->GenerateKey;
	
	
	}

	# aesFuntions();
	 

	































		
?>