Get signature values from PDF (PHP+JS) - javascript

How I can get values (date, signing name etc.) from sign('s) inside PDF? At my application on Joomla and Fabrik component i can run PHP and JS code.
The code I am currently using from Stack is not working as expected. If I read on browser $content variable, i cannot see /ByteRange, but when i take it to txt file, there is. On my XAMPP instance i have installed Composer and ASN1 and X509 libraries.
For all, this is my code with some changes for take content form file (I thought maybe it would work, but it doesnt) :
<?php
require_once('C:\Windows\System32\vendor\autoload.php');
use Sop\ASN1\Type\Constructed\Sequence;
use Sop\ASN1\Element;
use Sop\X509\Certificate\Certificate;
$currentFile = 'C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\test.pdf';
$content = file_get_contents($currentFile);
file_put_contents('C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\text.txt',$content);
$txt='C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\text.txt';
$regexp = '/ByteRange\ \[\s*(\d+) (\d+) (\d+)/'; // subexpressions are used to extract b and c
//$regexp = '#ByteRange\s*\[(\d+) (\d+) (\d+)#';
$result = [];
$abc=preg_match_all($regexp, $txt, $result);
//$result[2][0] and $result[3][0] are b and c
if (isset($result[2]) && isset($result[3]) && isset($result[2][0]) && isset($result[3][0])) {
$start = $result[2][0];
$end = $result[3][0];
if ($stream = fopen($currentFile, 'rb')) {
$signature = stream_get_contents($stream, $end - $start - 2, $start + 1); // because we need to exclude < and > from start and end
fclose($stream);
}
$binaryData = hex2bin($signature);
$seq = Sequence::fromDER($binaryData);
$signed_data = $seq->getTagged(0)->asExplicit()->asSequence();
// ExtendedCertificatesAndCertificates: https://tools.ietf.org/html/rfc2315#section-6.6
$ecac = $signed_data->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet();
// ExtendedCertificateOrCertificate: https://tools.ietf.org/html/rfc2315#section-6.5
$ecoc = $ecac->at($ecac->count() - 1);
$cert = Certificate::fromASN1($ecoc->asSequence());
$commonNameValue = $cert->tbsCertificate()->subject()->toString();
$StatusMsg = $commonNameValue;
echo $commonNameValue;
}

Related

How to use correctly JSON.stringify with an PHP returned JS object

I have a php script which executes a python script and I got back an object like this:
{'data': [{'article title', 'article description', 'timestamp', 'weburl'}], 'status': 200, 'answers': [1]}
As I know I have to transform this into a javascript JSON from a javascript object type.
And I tried like
myjs = JSON.parse(JSON.stringify(answer))
and
JSON.stringify(answer)
or even just concatenate with "on the beginning and at the end. But neither got me a good result. So what is the correct way? or should I change something on php side?
The php part is simply this:
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
$output = json_encode(shell_exec($command));
header('Content-type: application/json');
echo $output;
}
This is in my python script:
#!/usr/bin/python
import requests
import json
import html
import sys
requestpost = requests.post('NewsSource')
response_data = requestpost.json()
data = []
status = 0
answers = 0
out = {"data":[], "status":[], "answers":[0]}
searchterm = sys.argv[1]
error = 0
if requestpost.status_code == 200:
out["status"] = 200
for news in response_data["news"]:
try:
currentNews = json.loads(news)
if ((html.unescape(currentNews["title"]) != "Array" and html.unescape(currentNews["title"]).lower().find(searchterm.lower()) != -1) or (html.unescape(currentNews["description"]).lower().find(searchterm.lower()) != -1)):
outnews = {html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])}
out["data"].append(outnews)
out["answers"][0] = out["answers"][0] +1
except:
error += 1
else:
out["status"] = 404
print (out)
Change the Python script so it prints JSON instead of Python format.
print(json.dumps(out))
However, sets aren't in JSON, so change outnews to a list.
outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
Then the PHP script can simply return that to the client.
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
header('Content-type: application/json');
passthru($command);
}
If passthru() isn't working, you can try with your original shell_exec(). You don't need to call json_encode() because it's already encoded.
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
$output = shell_exec($command);
header('Content-type: application/json');
echo $output;
}
Also If I want to get back all news than change out and return it back like this:
out = []
error = 0
status = 0
nrOfResults = 0
if requestpost.status_code == 200:
status = 200
for news in response_data["news"]:
try:
currentNews = json.loads(news)
if ((html.unescape(currentNews["title"]) != "Array" and html.unescape(currentNews["title"]).lower().find(searchterm.lower()) != -1) or (html.unescape(currentNews["description"]).lower().find(searchterm.lower()) != -1)):
outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
out.append(outnews)
nrOfResults = nrOfResults +1
except:
error += 1
else:
status = 404
out.append(status)
out.append(nrOfResults)
#outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
print(json.dumps(out))
than the last element of js array will be a the number of results and the before one will be the status of the source link.

AJAX returning a white space from PHP echo

This is a problem I been having several times, and I always ignore because I cant find a solution.
Basically every time I echoed a value back to Javascript using AJAX, the first value will contain a space (extra character) this is annoying because if I want to check if that value exist sometimes I cant due to the space.
Normally the values returned is something like this
Value1
Value2
Value3
Here is the code below. I suggest to ignore the function seperate_ajx_data as I dont think the problem is located there.
results[0] is giving a white space plus the value!
What could be the issue of having a space in the first value?
PHP code:
$machine = null;
$sql = mysqli_query($connection, "SELECT......");
while($row = mysqli_fetch_array($sql)){
$machine .= $row['MACHINE']."+";
$machine .= $row['COUNT(MACHINE)']."/";
}
echo $machine;
JavaScript code:
function get_machine_vals(id){
var ht = new XMLHttpRequest();
var url = "....";
var val = "....="+id;
ht.open("POST", url, true);
ht.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ht.onreadystatechange = function(){
if(ht.readyState == 4 && ht.status == 200){
var val = ht.responseText;
var results = seperate_ajx_data(["/","+"],val);
var el = document.getElementById("machine_dropdown");
var opts = el.options;
for(var i =0;i<results.length;i++){
var tmp = results[i];
alert(tmp + " " + tmp.length);
switch (results[i]){
case "Test":
opts[0].innerHTML = "Seko "+results[i+1];
break;
}
}
}
};
ht.send(val);
}
function seperate_ajx_data(symbols, val){
var tmp_storage = [];
var tmp_spliter = val.split(symbols[0]);
var results = [];
for(var x = 0;x<tmp_spliter.length;x++){
tmp_storage = tmp_spliter[x].split(symbols[1]);
for(var y = 0;y<tmp_storage.length;y++){
results.push(tmp_storage[y]);
}
}
return results;
}
This is unfortunately one of those "gotchas" when working with PHP. The errant character might come from a space after a closing PHP tag. A contrived example:
<?php
... do some work ...
?> <?php
... do some work, but note errant space between the tags
Possible fixes?
Don't close the PHP tag
Use a different transfer mechanism that is space-tolerant, for example JSON or XML.
Strip (or "trim") your values client side. In context of your code:
var val = (ht.responseText || '').trim();
Just check your opening <?php brackets, there might be a space (i've seen this before).
It happened with me today. And unlike other answers related to opening bracket, for me it was the space after the closing bracket.
<?php
.....
?>[space][space][space]
I removed the spaces. And solved the issue.

Retaining the value of a variable in Perl

I've a GUI front-end (HTML and JavaScript) a Perl back-end. On clicking a certain button on the home page of the front-end, the Perl back-end receives a specific argument. So this argument leads to change of value of a variable ($checkInfo) which is then given back to the GUI. The GUI now pops up a message which displays $checkInfo and on closing the pop-up, another page (say page 2) opens. On page 2 is a certain button which emails $checkInfo to a certain email address.
The problem I'm facing is that $checkInfo is equal to "" on page 2. On page 1, the back-end returns $checkInfo = something to the GUI but that value is lost when I go to page 2. I've tried declaring $value as state $checkInfo but that doesn't work either. I use $checkInfo only in the main() function.
In the code, all you need to know is that preSubmitCheck::autoSubmitCheck return the value such that $checkInfo->{rc} != 0 and in the first iteration $mode ne 'ticket' but $mode eq 'ticket' in the second iteration. In the second iteration, I need the value of $checkInfo to be the same as the first iteration value.
Perl code:
my $username = defined param("username") ? param("username") : undef;
my $action = defined param("run_type") ? param("run_type") : undef;
my $cit_suite = defined param("cit_suite") ? param("cit_suite") : undef;
my $buildroot = defined param("buildroot") ? param("buildroot") : undef;
my $site = defined param("site") ? lc(param("site")) : undef;
my $branch = defined param("branch") ? param("branch") : undef;
my $hw = defined param("hw") ? param("hw") : undef;
my $variant = defined param("variant") ? param("variant") : undef;
my $num_runs = defined param("num_runs") ? param("num_runs") : undef;
my $justification = defined param("justification") ? param("justification") : undef;
my $mode = defined param("userAction") ? param("userAction") : undef;
my $jobID = defined param("jobID") ? param("jobID") : undef;
my $cancel_type = defined param("canceltype") ? param("canceltype") : undef;
state $checkInfo;
my $error;
my %rtn = (
rc => 0,
message => "All is well."
);
if($mode ne "ticket") {
$checkInfo = preSubmitCheck::autoSubmitCheck($site,$username,$num_runs);
}
if(defined $checkInfo && $checkInfo->{rc} == 0){
my $target = 1;
}
else {
if($mode eq "ticket"){
$error = $checkInfo->{message};
my $rtnFromTicket = sendTicket(
username => $username,
cit_suite => $cit_suite,
action => $action,
buildroot => $buildroot,
site => $site,
branch => $branch,
hw => $hw,
variant => $variant,
num_runs => $original_num_runs,
justification => $justification,
errorMessage => $error
);
$rtn{rc} = 2;
$allMessage .= " Your job couldn't be automatically submitted: ". $error;
$allMessage .= " Email info: ". $rtnFromTicket -> {message};
$rtn{message} = $allMessage;
print "00delimiter00"; # use as a delimiter to split from useless print information, and make the front end got the json data.
print to_json(\%rtn);
exit $rtn{rc};
}
else{
$error = $checkInfo->{message};
$rtn{rc} = $checkInfo->{rc};
if($rtn{rc} == 6) {
$allMessage .= " Your job couldn't be automatically submitted: ". $error. " You can schedule your run or open a ticket with the SMOKES team.";
}
else {
$allMessage .= " Your job couldn't be automatically submitted: ". $error;
}
$rtn{message} = $allMessage;
print "00delimiter00"; # use as a delimiter to split from useless print information, and make the front end got the json data.
print to_json(\%rtn);
exit $rtn{rc};
}
}
GUI code:
var query = "username=<% $ARGS{username} %>";
if(Mode=="all"){
query += "&run_type=Presub_smoke";
}
else {
query += "&run_type=CIT" + "&cit_suite=" + document.getElementById("citsuite").value;
}
query += "&buildroot=" + encodeURIComponent(document.getElementById("buildroot").value);
query += "&site=" + encodeURIComponent(document.getElementById("remoteSite").value);
query += "&branch=" + encodeURIComponent(document.getElementById("branch").value);
query += "&hw=" + encodeURIComponent(document.getElementById("hwtype").value);
query += "&variant=" + encodeURIComponent(document.getElementById("variant").value);
query += "&num_runs=" + document.getElementById("num_runs").value;
query += "&justification=" + encodeURIComponent(document.getElementById("justification").value);
query += "&userAction=" + encodeURIComponent(action);
var submitFcts = new Array();
submitFcts[3] = "updateSubmitInfo";
submitFcts[4] = "return_request";
makeUserRequest2("<% $CGI_form_path %>", query, submitFcts, "");
I hope this suffices for answering my question. Thanks!
state only preserves the value of a variable within a single process. When running as CGI, there's a new process for each HTTP request.
If you want to store state across requests, you will need to persist it somewhere that survives across requests -- for instance, by storing it in a cookie, in a session, or in a database.

Using PHP string in SQL query works when typed in but not when generated via javascript

$query = "
select * from tablename where userid = :uid AND date = :date
";
$query_params = array(
':uid' => $_SESSION['user']['uid'],
':date' => $date
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
I am trying to run this simple SQL query via PHP. When I hard-code a string of a date like $date = '2016-07-29'; then I get the proper number of results. When I dynamically generate the same string using javascript like
$date = '<script> var currentdate = new Date();
document.write(currentdate.getFullYear()+"-"+
("0"+(currentdate.getMonth()+1)).slice(-2)+"-"+
("0"+currentdate.getDate()).slice(-2));
</script>';
then I get 0 results. Any ideas? Echoing $date in both instances produces the same result (type = string).

How to get the same result with PHP and CryptoJS using SHA256?

I'm trying to decode Firefox Sync data using javascript, porting one php library which does it (https://github.com/mikerowehl/firefox-sync-client-php). The idea is to decode sync data without sending sync key to the server. This is just context, the problem I have is much more specific.
One portion of code requires using sha256 to obtain certain key. I would like to replicate it in javascript. The approach I've tried, with CryptoJS, is this:
PHP code:
$key = hash_hmac("sha256",'OLA K ASE','CLAVE', false);
print $key;
Equivalent Javascript code (previously, I've included http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js):
var hash = CryptoJS.HmacSHA256("OLA K ASE", "CLAVE");
console.log(hash.toString());
This works fine. In each case, output is 9591d44df0c8e2d7a1f400f41117c536e10f58d7e28bdc1cad9d81e70290bc1b, which I suppose is correct.
But, when I'm trying to encode non-ascii strings, results differ. For example, with this PHP code:
function hexstring($str){
return preg_replace('/\\\\x([0-9a-f]{2})/e', 'chr(hexdec(\'$1\'))', $str);
}
$text = hexstring('\x00\x44\xb0\x2c\x0b');
$key = hexstring('\xd6\xf8\xb0\x2c\x0b');
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
I get 0697f5528c996006ffeb09b9130bf8e9056563245656d405e233bcafdbffb645. But with the 'equivalent' javascript code:
var text = "\x00\x44\xb0\x2c\x0b";
var key = "\xd6\xf8\xb0\x2c\x0b";
hash = CryptoJS.HmacSHA256(text,key);
console.log(hash.toString());
I get 13c983b69f82c277815c03d13e90b1ec1e9cbca2b6912ad1f8224f3de8b82130, a different value.
I thought it could be caused by non-ascii character, so I did a quick test:
$text = '';
for($i = 0;$i < 10; $i++){
$text .= chr($i);
}
$key = '';
for($i = 0;$i < 10; $i++){
$key .= chr($i*2);
}
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
And, javascript equivalent:
var text = '';
for(i = 0;i < 10; i++){
text += String.fromCharCode(i);
}
var key = '';
for(i = 0;i < 10; i++){
key += String.fromCharCode(i*2);
}
var hash = CryptoJS.HmacSHA256(text, key);
console.log(hash.toString());
In both cases, output is c5d7adbbabcec5416c6b7a1f01e17e42d95a529f5bcc805d9b04b93f33994c9d.
This is a big WTF? for me. Could somebody give me a piece of advice of how to continue with this?
Solved. It was a problem with character codes. Instead of this:
var text = "\x00\x44\xb0\x2c\x0b";
var key = "\xd6\xf8\xb0\x2c\x0b";
hash = CryptoJS.HmacSHA256(text,key);
I should indicate CryptoJS that they were Latin-1 encoded strings:
var text = CryptoJS.enc.Latin1.parse("\x00\x44\xb0\x2c\x0b");
var key = CryptoJS.enc.Latin1.parse("\xd6\xf8\xb0\x2c\x0b");
hash = CryptoJS.HmacSHA256(text,key);
I don't know clearly why is this happening, so if somebody could explain it with a little bit of detail it would be great.
Try that:
$text = "\x00\x44\xb0\x2c\x0b";
$key = "\xd6\xf8\xb0\x2c\x0b";
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
It's proabably because the preg_* functions have a problem with these special characters.
And PHP supports \x12 hex-encoding without any function.

Categories