Find & Replace inside a compiled .jar file. And then downloading it - java

So basically what I want: find and replace strings in a .jar file whatever length it is. It works for me fine except I need to have the same length of the replaced variable as the variable. I want that the length doesn't matter. Does anyone know how to help me?
PHP code:
<?php
$search1 = '%%__NONCE__%%';
$replace1 = 'ME_0000000001';
$search2 = '%%__USER__%%';
$replace2 = '000000000001';
$search3 = '%%__RESOURCE__%%';
$replace3 = '1';
function modifyzip($archive, $search, $replace) {
$zip = new ZipArchive();
$status = $zip->open($archive);
// echo $status;
if ($status == true) {
/* Get the count of files BEFORE the loop */
$filecount = $zip->numFiles;
// echo $filecount;
for ($i=0; $i < $filecount; $i++) {
$name = $zip->getNameIndex($i);
$content = $zip->getFromName($name);
$edited = str_replace($search, $replace, $content);
if ($edited != $content) {
// echo $edited;
// echo $edited . "\n\n";
}
$zip->deleteName($name);
$zip->addFromString($name, $edited);
}
}
$zip->close();
}
$templateFilename = 'zips/a.jar';
$inputFilename = 'zips/b.jar';
if (!copy($templateFilename, $inputFilename)) {
die("Could not copy '$templateFilename' to '$inputFilename'");
}
call_user_func('modifyzip', $inputFilename, $search1, $replace1);
call_user_func('modifyzip', $inputFilename, $search2, $replace2);
call_user_func('modifyzip', $inputFilename, $search3, $replace3);
//echo file_get_contents($templateFilename);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$inputFilename");
header("Content-Type: application/java-archive");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($inputFilename);
unlink($inputFilename);
Java Luyten error:
java.lang.IllegalArgumentException: Argument 'value' must be in the range [1, 18], but value was: 0.
at com.strobel.core.VerifyArgument.inRange(VerifyArgument.java:346)
at com.strobel.assembler.ir.ConstantPool$Tag.fromValue(ConstantPool.java:532)
at com.strobel.assembler.ir.ConstantPool.read(ConstantPool.java:362)
at com.strobel.assembler.metadata.JarTypeLoader.getInternalNameFromClassFile(JarTypeLoader.java:105)
at com.strobel.assembler.metadata.JarTypeLoader.tryLoadType(JarTypeLoader.java:78)
at us.deathmarine.luyten.LuytenTypeLoader.tryLoadType(LuytenTypeLoader.java:25)
at com.strobel.assembler.metadata.MetadataSystem.resolveType(MetadataSystem.java:120)
at com.strobel.assembler.metadata.MetadataSystem.lookupTypeCore(MetadataSystem.java:81)
at com.strobel.assembler.metadata.MetadataResolver.lookupType(MetadataResolver.java:46)
at us.deathmarine.luyten.Model.openEntryByTreePath(Model.java:338)
at us.deathmarine.luyten.Model$TreeListener$1.run(Model.java:266)

Related

java.nio.ByteBuffer wrap method partly working with sbt run

I have an issue where I read a bytestream from a big file ~ (100MB) and after some integers I get the value 0 (but only with sbt run ). When I hit the play button on IntelliJ I get the value I expected > 0.
My guess was that the environment is somehow different. But I could not spot the difference.
// DemoApp.scala
import java.nio.{ByteBuffer, ByteOrder}
object DemoApp extends App {
val inputStream = getClass.getResourceAsStream("/HandRanks.dat")
val handRanks = new Array[Byte](inputStream.available)
inputStream.read(handRanks)
inputStream.close()
def evalCard(value: Int) = {
val offset = value * 4
println("value: " + value)
println("offset: " + offset)
ByteBuffer.wrap(handRanks, offset, handRanks.length - offset).order(ByteOrder.LITTLE_ENDIAN).getInt
}
val cards: List[Int] = List(51, 45, 14, 2, 12, 28, 46)
def eval(cards: List[Int]): Unit = {
var p = 53
cards.foreach(card => {
println("p = " + evalCard(p))
p = evalCard(p + card)
})
println("result p: " + p);
}
eval(cards)
}
The HandRanks.dat can be found here: (I put it inside a directory called resources)
https://github.com/Robert-Nickel/scala-texas-holdem/blob/master/src/main/resources/HandRanks.dat
build.sbt is:
name := "LoadInts"
version := "0.1"
scalaVersion := "2.13.4"
On my windows machine I use sbt 1.4.6 with Oracle Java 11
You will see that the evalCard call will work 4 times but after the fifth time the return value is 0. It should be higher than 0, which it is when using IntelliJ's play button.
You are not reading a whole content. This
val handRanks = new Array[Byte](inputStream.available)
allocates only as much as InputStream buffer and then you read the amount in buffer with
inputStream.read(handRanks)
Depending of defaults you will process different amount but they will never be 100MB of data. For that you would have to read data into some structure in the loop (bad idea) or process it in chunks (with iterators, stream, etc).
import scala.util.Using
// Using will close the resource whether error happens or not
Using(getClass.getResourceAsStream("/HandRanks.dat")) { inputStream =>
def readChunk(): Option[Array[Byte]] = {
// can be done better, but that's not the point here
val buffer = new Array[Byte](inputStream.available)
val bytesRead = inputStream.read(buffer)
if (bytesRead >= 0) Some(buffer.take(bytesRead))
else None
}
#tailrec def process(): Unit = {
readChunk() match {
case Some(chunk) =>
// do something
process()
case None =>
// nothing to do - EOF reached
}
}
process()
}

Powershell running Java Script to Encrypt Password

We have a number of Lanier MFPs that use the scan-to-folder option to allow people to get their documents, and we are starting to implement more security measures on the AD passwords they use by forcing a password reset.
Unfortunately, the Laniers use a proprietary encryption for the passwords. I've managed to get a functional Java command that will encrypt passwords into this format. The problem I've been encountering is that I then have to get this encoded password into PowerShell to pass it to the scanner.
I can run the Java command through a command line, but can't pass the encrypted password back into PowerShell as a string that the printer will accept (it needs to be in Base64). If I do pass the encoded password back into PowerShell, then run it through PowerShell's Base64 creation process, it is, obviously, changed too much for the scanner to use it.
What I need to determine is whether there's a way for me to take the following command line command, and get it to run in PowerShell, then provide me its output so I can pass this to the printer.
java -cp ./commons-codec-1.10.jar;. cdm.GwpwesCharacterEncoding %pass% "gwpwes002"
The Java command outputs a Base64 string based on the following line:
return new String(Base64.encodeBase64((byte[])encrypt));
As an example, if I pass the text 'Test' into that, I get the string "HVhcmtla25meHVncHQ=="
This is useless to me, though, as I can't then get this back into PowerShell to pass through to the printer, and if I encode it as Base64 with PowerShell, it comes out as "MgBoAHMAWgBtADkAegBjADIAQgBxAGUAMABKAHgAWgBYAGgAbgBiAG0AMAB3AD0A".
Can anyone help?
Revised code after some assistance:
$pass1 = "test"
$path = "c:\Test\printercreds"
$encode = "gwpwes002"
cd $path
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pInfo.FileName = 'java'
$pInfo.Arguments = "-jar .\commons-codec-1.10.jar cdm.GwpwesCharacterEncoding $pass1 $encode"
$pInfo.UseShellExecute = $false
$pInfo.RedirectStandardOutput = $true
$pInfo.RedirectStandardError = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $pInfo
[void]$process.Start()
$passsec = $process.StandardOutput.ReadtoEnd()
$process.WaitforExit()
write-host $passsec
Please try this. Its the encoding for GWPWES002. I found a old java version here.
https://www.dropbox.com/s/3324g84x0l4bnon/GwpwesCharacterEncoding.java?dl=0
There is a weakness in this "encoding". The front part of the encoding is just random padding. the pack part is where the actual string is stored. Running the script on the same string just a few times points out this error.
encodeGwpwes002 -code "a"
generated this hashes
np6eWFieWJ6eWA==
np6eWJ5YWFieWA==
WFienlhYnlieWA==
nlhYnp5Ynp6eWA==
nlieWFieWJ6eWA==
everything up until eWA== is just random padding mean "eWA==" == "a"
same for "aaaaaaaa"
np5YWJ5YnlieWFhYWFhYWFg=
np5Ynp6eWJ6eWFhYWFhYWFg=
nlienp6eWJ6eWFhYWFhYWFg=
WJ5YWJ6enlieWFhYWFhYWFg=
Meaning that
"eWFhYWFhYWFg=" Is "aaaaaaaa".
the password you provided as "test", A example of manipulation would be :
HVhcmtla25meHVncHQ== IS "test" :: 29 88 92 154 217 90 219 153 158 29 89 220 29
HVhcmtla25meFVncHQ== IS "Test" :: 29 88 92 154 217 90 219 153 158 21 89 220 29
Here is the powershell I have translated below
#private static String encodeGwpwes002(String code, int codeSize) {
function encodeGwpwes002([string]$code, [int]$codeSize = 0){
#byte[] protectCode;
[byte]$protectCode | Out-Null
#try {
try{
#protectCode = code.getBytes("UTF-8");
$protectCode = [System.Text.Encoding]::UTF8.GetBytes($code)
#}catch (Throwable e) {
}catch{
#return null;
return $null
#}
}
#int encodeSize = codeSize;
[int]$encodeSize = $codeSize
#if (protectCode.length >= codeSize) {
if(($protectCode.length) -ge $codeSize){
#encodeSize = protectCode.length + 9;
$encodeSize = ($protectCode.length) + 9
#}
}
#byte[] simple = new byte[encodeSize];
[byte[]]$simple = New-Object byte[] $encodeSize
#int diffuseCnt = 0;
[int]$diffuseCnt = 0
#int simpleCnt = 0;
[int]$simpleCnt = 0
#if (protectCode.length < encodeSize - 1) {
if(($protectCode.length) -lt ($encodeSize - 1)){
#for (diffuseCnt = 0; diffuseCnt < encodeSize - 1 - protectCode.length; ++diffuseCnt) {
for($diffuseCnt = 0; $diffuseCnt -lt ($encodeSize - 1 - ($protectCode.length)); $diffuseCnt++){
#simple[diffuseCnt] = (byte)(Math.random() * 25.0 + 97.0);
$simple[$diffuseCnt] = [byte] (Get-Random -Maximum 0.9 -Minimum 0.1) * 25.0 + 97.0
#}
}
#}
}
#simple[diffuseCnt++] = 122;
$simple[$diffuseCnt++] = 122
#for (simpleCnt = diffuseCnt; simpleCnt < protectCode.length + diffuseCnt; ++simpleCnt) {
for($simpleCnt = $diffuseCnt; $simpleCnt -lt ($protectCode.length) + $diffuseCnt; $simpleCnt++){
#simple[simpleCnt] = protectCode[simpleCnt - diffuseCnt];
$simple[$simpleCnt] = $protectCode[$simpleCnt - $diffuseCnt];
#}
}
#byte[] encrypt = new byte[simpleCnt];
[byte[]] $encrypt = New-Object byte[] $simpleCnt
#for (int i = 0; i < simpleCnt; ++i) {
for([int]$i=0; $i -lt $simpleCnt; $i++) {
#byte work = 0;
[byte]$work = 0
#work = (byte)((simple[i] & 192) >>> 6 | (simple[i] & 63) << 2);
$work = [byte](($simple[$i] -band 192) -shr 6 -bor ($simple[$i] -band 63) -shl 2)
#encrypt[i] = (byte)((work & 240) >>> 4 | (work & 15) << 4);
$encrypt[$i] = [byte](($work -band 240) -shr 4 -bor ($work -band 15) -shl 4)
#}
}
#return new String(Base64.encodeBase64((byte[])encrypt));
return [string]([System.Convert]::ToBase64String([byte[]]$encrypt))
#}
}
encodeGwpwes002TEST -code "Test"

Number format exception in scala

I am trying to write a scala program to generate an output file omega0_Real.txt which contains pre-calculated values of the cosine function for inputs ranging from 0 to pi/2 radians. Each of these calculated values are 72 bit long and are stored in hex format. The code I have written so far is as follows:
import java.io._
import scala.math._
object omega0_Real {
def main (args: Array[String]) {
val arg = (0.0).to(2-pow(2, -10), pow(2, -10))
val cosArg = arg.map (i => cos(i))
val cosBit = cosArg.map (i => List.tabulate(72)(j = (BigDecimal((i*pow(2,j))).toBigInt % 2)))
val cosStr = cosBit.map (i => i mkString)
val cosBig = cosStr.map (i => BigInt(i, 2))
val cosBigStr = cosBig.map (i => i.toString(16))
val cosList = cosBigStr.toList
val file = "omega0_Real.txt"
val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))
for (x <- cosList) {
writer.write(x + "\n")
}
writer.close()
}
which gives the error: java.lang.NumberFormatException: Illegal embedded sign character followed by many others. Please help me debug this code.
PS: I ran this code line-by-line on sbt console but it did not give any error, although the values generated were erroneous.

How To integrate Aadhaar Card Authentication Api for Aadhaar number Verification in PHP?

I want to integrate the Aadhaar Card Authentication API for Aadhaar number Verification in PHP. I tried this and wrote code for API access.
How can I generate the XML encryption field data below in PHP? This sample code is written in Java.
<Auth uid="" tid="" ac="" sa="" ver="" txn="" lk="">
<Uses pi="" pa="" pfa="" bio="" bt="" pin="" otp=""/>
<Tkn type="" value=""/>
<Meta udc="" fdc="" idc="" pip="" lot=”G|P” lov=""/>
<Skey ci="" ki="">encrypted and encoded session key</Skey>
<Data type=”X|P”>encrypted PID block</Data>
<Hmac>SHA-256 Hash of Pid block, encrypted and then encoded</Hmac>
<Signature>Digital signature of AUA</Signature>
</Auth>
// Below is the running code to integrate Aadhaar Card Authentication Api for Aadhaar number Verification in PHP?
$path=$_SERVER['DOCUMENT_ROOT'];
$certpath=$path."/your .pfx file";
$publickeypath=$path."/your .cer file";
$certpassword="your cert password";
require_once('xmlsecurity.php'); // for creating this file use link : https://github.com/robrichards/xmlseclibs
$trn_id = "AuthDemoClient:public:". date('YmdHisU');
if (!$cert_store = file_get_contents($certpath)) {
echo "Error: Unable to read the cert file\n";
exit;
}
if (openssl_pkcs12_read($cert_store, $cert_info, $certpassword)) {
//print_r($cert_info["cert"]);
//print_r($cert_info["pkey"]);
} else {
echo "Error: Unable to read the cert store.\n";
exit;
}
define("UIDAI_PUBLIC_CERTIFICATE" , $publickeypath);
define("AUA_PRIVATE_CERTIFICATE" , $cert_info["pkey"]);
date_default_timezone_set("Asia/Calcutta");
$date2= gmdate("Y-m-d\TH:i:s");
$date1 = date('Y-m-d\TH:i:s', time());
$ts='"'.$date1.'"';//date('Y-m-d\TH:i:s');
$pid_1='<Pid ts='.$ts.' ver="1.0"><Pv otp="'.$otp.'"/></Pid>';
$randkey = generateRandomString();
$SESSION_ID = $randkey;
$skey1=encryptMcrypt($SESSION_ID);
$skey=base64_encode($skey1);
// generate ci code start
$ci=getExpiryDate(UIDAI_PUBLIC_CERTIFICATE);
// generate pid block code start
$pid=encryptPID($pid_1,$randkey);
//hmac creation code start
$hash=hash("SHA256",$pid_1,true);
$hmac=encryptPID($hash,$randkey);
$load_xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Auth xmlns=\"http://www.uidai.gov.in/authentication/uid-auth-request/1.0\" sa=\"public\" lk=\"your license key\" txn=\"$trn_id\" ver=\"1.6\" tid=\"public\" ac=\"your code from aadhaar\" uid=\"$aadhaarno\"><Uses pi=\"n\" pa=\"n\" pfa=\"n\" bio=\"n\" bt=\"\" pin=\"n\" otp=\"y\"/><Meta udc=\"UDC:001\" fdc=\"NC\" idc=\"NA\" pip=\"NA\" lot=\"P\" lov=\"$pincode\"/><Skey ci=\"$ci\">$skey</Skey><Data type=\"X\">$pid</Data><Hmac>$hmac</Hmac></Auth>";
$dom = new DOMDocument();
$dom->loadXML($load_xml); // the XML you specified above.
$objDSig = new XMLSecurityDSig();
$objDSig->setCanonicalMethod(XMLSecurityDSig::C14N_COMMENTS);
$objDSig->addReference($dom, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature'),array('force_uri'
=>'true'));
$objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));
$objKey->loadKey($cert_info["pkey"], False);
$objKey->passphrase = 'your certificate password';
$objDSig->sign($objKey, $dom->documentElement);
$objDSig->add509Cert($cert_info["cert"]);
$objDSig->appendSignature($dom->documentElement);
$xml_string = $dom->saveXML();
$xml_string1 = urlencode($xml_string);
$curl = curl_init();
$url=""; //aadhar service url
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,"eXml=A28".$xml_string1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
/* complete within 20 seconds */
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$result = curl_exec($curl);
curl_close($curl);
$xml = #simplexml_load_string($result);
$return_status=$xml['ret'];
if($return_status=="y"){
$res=1;
}
if($return_status!="y"){
$res=0;
}
}else
{
$res='Aadhaarno not exist';
}
return array('Message'=>$res);
}
function encryptMcrypt($data) {
$fp=fopen(UIDAI_PUBLIC_CERTIFICATE,"r");
$pub_key_string=fread($fp,8192);
openssl_public_encrypt($data, $encrypted_data, $pub_key_string, OPENSSL_PKCS1_PADDING);
return $encrypted_data;
}
function generateRandomString($length = 32) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function encryptPID($data,$skey) {
$result=openssl_encrypt ( $data , 'AES-256-ECB' , $skey );
return ($result);
}
function getExpiryDate($_CERTIFICATE){
$_CERT_DATA = openssl_x509_parse(file_get_contents($_CERTIFICATE));
return date('Ymd', $_CERT_DATA['validTo_time_t']);
}
To generate the XML, you could use this library to generate it quite easily:
https://github.com/iwyg/xmlbuilder
For the encryption; I could be wrong but it looks like (from this page) you can generate the encoded results in java one time and just paste in the results to your PHP variables.

Call Java from PHP with timeout handler

Problem: I am running java files via PHP that a user submits. It is possible for a java file to cause an infinite loop. How can I handle this in the php execution process?
Here is my code:
$proc = proc_open($javaCmd, array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w")), $pipes);
// Check status here logic ?
proc_close($proc);
It currently waits for the process to finish, but I want it to timeout after 30 seconds or a minute. I tried set_time_limit(x), but that does not terminate java.exe.
My question is, is it possible for me to check the status of java.exe process after X seconds, then terminate if it is still running? Or, do I need to use a timeout functionality in java (i.e. have a main class that executes the user's submitted classes on a thread)
Yes, it's possible. I don't think a java process is any different than any other process in this regard. See these links for unix exec with timeout and windows exec with timeout.
I didn't write this code, but here it is copy-pasted in case the original disappears from the Internet:
For unix:
<?php
function PsExecute($command, $timeout = 60, $sleep = 2) {
// First, execute the process, get the process ID
$pid = PsExec($command);
if( $pid === false )
return false;
$cur = 0;
// Second, loop for $timeout seconds checking if process is running
while( $cur < $timeout ) {
sleep($sleep);
$cur += $sleep;
// If process is no longer running, return true;
echo "\n ---- $cur ------ \n";
if( !PsExists($pid) )
return true; // Process must have exited, success!
}
// If process is still running after timeout, kill the process and return false
PsKill($pid);
return false;
}
function PsExec($commandJob) {
$command = $commandJob.' > /dev/null 2>&1 & echo $!';
exec($command ,$op);
$pid = (int)$op[0];
if($pid!="") return $pid;
return false;
}
function PsExists($pid) {
exec("ps ax | grep $pid 2>&1", $output);
while( list(,$row) = each($output) ) {
$row_array = explode(" ", $row);
$check_pid = $row_array[0];
if($pid == $check_pid) {
return true;
}
}
return false;
}
function PsKill($pid) {
exec("kill -9 $pid", $output);
}
For windows:
<?php
// pstools.inc.php
function PsExecute($command, $timeout = 60, $sleep = 2) {
// First, execute the process, get the process ID
$pid = PsExec($command);
if( $pid === false )
return false;
$cur = 0;
// Second, loop for $timeout seconds checking if process is running
while( $cur < $timeout ) {
sleep($sleep);
$cur += $sleep;
// If process is no longer running, return true;
if( !PsExists($pid) )
return true; // Process must have exited, success!
}
// If process is still running after timeout, kill the process and return false
PsKill($pid);
return false;
}
function PsExec($command) {
exec( dirname(__FILE__). "\\psexec.exe -s -d $command 2>&1", $output);
while( list(,$row) = each($output) ) {
$found = stripos($row, 'with process ID ');
if( $found )
return substr($row, $found, strlen($row)-$found-strlen('with process ID ')-1); // chop off last character '.' from line
}
return false;
}
function PsExists($pid) {
exec( dirname(__FILE__). "\\pslist.exe $pid 2>&1", $output);
while( list(,$row) = each($output) ) {
$found = stristr($row, "process $pid was not found");
if( $found !== false )
return false;
}
return true;
}
function PsKill($pid) {
exec( dirname(__FILE__). "\\pskill.exe $pid", $output);
}

Categories

Resources