var CryptoJS = require("crypto-js");
const a = {
name: "Burak",
surName: "Bayraktaroglu"
};
const aString = JSON.stringify(a);
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(
aString,
"XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM"
).toString();
console.log(ciphertext);
// Decrypt
var bytes = CryptoJS.AES.decrypt(
ciphertext,
"XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM"
);
var originalText = bytes.toString(CryptoJS.enc.Utf8);
const jsonObject = JSON.parse(originalText);
console.log(jsonObject);
i want to decrypt ciphertext in php
<?php
$plaintext = '{"phoneNumber":"+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}';
$password = 'XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM';
$method = 'aes-256-cbc';
// Must be exact 32 chars (256 bit)
$password = substr(hash('sha256', $password, true), 0, 32);
echo "Password:" . $password . "\n";
// IV must be exact 16 chars (128 bit)
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
// av3DYGLkwBsErphcyYp+imUW4QKs19hUnFyyYcXwURU=
$encrypted = base64_encode(openssl_encrypt($plaintext, $method, $password, OPENSSL_RAW_DATA, $iv));
$$encrypted = base64_encode("U2FsdGVkX1/ABCbXVG5iVcjZ+qVwLcXJ0Mbxfr8EEU+2JNVji7yiYQQGEjeWB4MgFWE89BTPXDdyBvjGCpfQ+BH5evxyS/Fj1OeijQr0RmhWliiazgX90gOLEBOBAw9FzyJn8m3CzjrJksx27q/a7izq4mAVRAitj4/1m0+uI8sBSqmC2HGxmol7MxQxODE/cYbmYYOrg+wFgg8J3+mYv2dDcHIIXknTyZsGx26CicZ//tWwGkdIhjDuWo5Rq5IqlFcqST9F3m5NicDSiy/hotQEFP9PrRveAtNnMnTuOWcSsNp63zfR2oPSy22Z7cz6+4fnu4eEjguyxeN38RRU5jbUFBQLxrth8tERI44O/fRMQiMheDUBUdCVIsh0vGHh7F17t/oBBTq5YrD8l+noMUE/M6kBa5Yr24NLw/PYDgPyO9jD5XMUhNXmFeLUe8SQ");
$iv = "a591cdd0d7bea71eae2eefe4c73f612f";
// My secret message 1234
$decrypted = openssl_decrypt(base64_decode($encrypted), $method, $password, OPENSSL_RAW_DATA, $iv);
echo 'plaintext=' . $plaintext . "\n";
echo 'cipher=' . $method . "\n";
echo 'encrypted to: ' . $encrypted . "\n";
echo 'decrypted to: ' . $decrypted . "\n\n";
result isn't match with plain text :
plaintext=
{"phoneNumber":"+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}
decrypted to:
IY ~ZG+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}
Related
Here's my PHP code:
$cipher = 'aes-256-cbc';
// 128-bit key
$key = md5('super secret', true);
// 128-bit IV
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($message, $cipher, $key, OPENSSL_RAW_DATA, $iv);
error_log(__FILE__ . __LINE__ . ' key: ' . bin2hex($key));
error_log(__FILE__ . __LINE__ . ' iv: ' . bin2hex($iv));
error_log(__FILE__ . __LINE__ . ' ciphertext: ' . bin2hex($ciphertext));
file_put_contents($courseOutlineFile, bin2hex($iv) . bin2hex($ciphertext));
And my Javascript code, where res is the text from the ajax response to read the file generated by PHP:
var k = CryptoJS.MD5('super secret');
var iv = CryptoJS.enc.Hex.parse(res.substring(0, 32));
var data = CryptoJS.enc.Hex.parse(res.substring(32));
console.log("key: ", CryptoJS.enc.Hex.stringify(k))
console.log("iv: ", CryptoJS.enc.Hex.stringify(iv))
console.log("ciphertext: ", CryptoJS.enc.Hex.stringify(data))
var cipher = CryptoJS.lib.CipherParams.create({
ciphertext: data
});
var dec = CryptoJS.AES.decrypt(cipher, k, {
iv: iv,
mode: CryptoJS.mode.CBC
});
console.log("decrypted:", dec.toString(CryptoJS.enc.Hex));
var json = dec.toString(CryptoJS.enc.Utf8);
console.log("json:", json)
I've verified with a compare tool that the hex values of the key, IV, and data are the same in PHP and what gets printed to the browser's console. It does successfully decrypt (something), but that last console.log statement generates an error: Error: "Malformed UTF-8 data". If I try Latin1 it results in a bunch of non-printable characters.
The $message variable that I'm encrypting is the output from json_encode on an array.
Does anyone know what I'm missing?
These are the first 80 hex digits of the decrypted result, the entire thing is a little under 28k hex digits.
20a290156abf2855f2c3344a2d9cf7dc84c5c02b1a48a03f18aa8a5054f650dd5517b25b6582c72d
Here's a complete example:
<?php
ini_set('display_errors', 1);
$jsonObj = [
'el1' => 'val1',
'ar1' => [
'el2' => 'val2',
'el3' => 'val3',
],
];
$message = json_encode($jsonObj);
echo $message . '<br>';
$cipher = 'aes-256-cbc';
// 128-bit key
$key = md5('super secret', true);
// 128-bit IV
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($message, $cipher, $key, OPENSSL_RAW_DATA, $iv);
echo ' key: ' . bin2hex($key) . '<br>';
echo ' iv: ' . bin2hex($iv) . '<br>';
echo ' ciphertext: ' . bin2hex($ciphertext) . '<br>';
echo bin2hex($iv) . bin2hex($ciphertext);
The output:
{"el1":"val1","ar1":{"el2":"val2","el3":"val3"}}
key: 5f1903f5f2cb32acb4c1dcae9e30d374
iv: bfdb765d1ca4734c5748ffb9883dd15c
ciphertext:
02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
bfdb765d1ca4734c5748ffb9883dd15c02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
And the Javascript:
res = 'bfdb765d1ca4734c5748ffb9883dd15c02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2';
var k = CryptoJS.MD5('super secret');
var iv = CryptoJS.enc.Hex.parse(res.substring(0, 32));
var data = CryptoJS.enc.Hex.parse(res.substring(32));
console.log("key: ", CryptoJS.enc.Hex.stringify(k))
console.log("iv: ", CryptoJS.enc.Hex.stringify(iv))
console.log("ciphertext: ", CryptoJS.enc.Hex.stringify(data))
var cipher = CryptoJS.lib.CipherParams.create({
ciphertext: data
});
var dec = CryptoJS.AES.decrypt(cipher, k, {
iv: iv,
mode: CryptoJS.mode.CBC
});
console.log("dec:", dec.toString());
console.log("decrypted:", dec.toString(CryptoJS.enc.Hex));
var json = dec.toString(CryptoJS.enc.Utf8);
console.log("json:", json)
// parse the JSON string to get the object
var obj = JSON.parse(json);
And the console output:
key: 5f1903f5f2cb32acb4c1dcae9e30d374
iv: bfdb765d1ca4734c5748ffb9883dd15c
ciphertext: 02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
dec: 50d411522f2d08b34d68f847fb78e0cfabf1144f933d83839431732a473079d9b3ed843e120d9ad6a239
decrypted: 50d411522f2d08b34d68f847fb78e0cfabf1144f933d83839431732a473079d9b3ed843e120d9ad6a239
Error during decryption: Error: "Malformed UTF-8 data"
I need to embed PHP into Javascript so that when the user selects Countries it would display the result from the query alphabatically and if he selects Numbers then list based on numbers in descending.
Having researched, I have applied this (echo concept into my code) but doesn't seem to work.
I have the following query written in PHP that output staffs' country of birth( no of staff born in number of countries) in ascending order:
$querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) ASC ";
Then, I have a dropdown in HTML:
<form>
<label for="sortorder">Sort by:</label>
<select id="sortByDropdown" onchange="sortBy(this);">
<option value="alphabatically">Countries</option>
<option value="numbers">Number</option>
</select>
</form>
Furthermore, I have a Javascript function sortBy()
function sortBy(){
var sortByDrpdownDiv = document.getElementById('sortByDropdown');
if (sortByDrpdownDiv[sortByDrpdownDiv.selectedIndex].value == 'numbers'){
alert("yo in if statement");
<?php $querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC ";
$result = mysql_query($querytest);
while ($row = mysql_fetch_assoc($result)) {
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}?>
document.getElementById('staffbirthplaces').innerHTML = <?php echo $row?>;
}
}
First I am going only for Numbersbecause the same logic will apply to the Countries. Any help will be appreciated
So, i finally did it! Used switch instead of IF statement. Below is the code:
function sortByAlphabetsOrNumbers(obj){
var selectedValue = obj.options[obj.selectedIndex].value
switch(selectedValue)
{
case "numberOfStaff":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$staffNumbersDesc = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC";
$result = mysql_query($staffNumbersDesc);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
case "countries":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$alphabaticalOrder = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x";
$result = mysql_query($alphabaticalOrder);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
}
};
Hope it helps someone
I would like to make use of Simple HTML DOM parser to search for mail-adresses in the content of a html-site and replace them.
The replacement contains a span element and a little bit JS (this should obfuscate the addresses.
At the moment this works as follows:
$pattern =
"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";
preg_match_all( $pattern, $content, $matches );
foreach ( $matches[ 0 ] as $email ) {
$content = $this->searchDOM(
$content,
$email,
$this->hide_email($email)
);
}
This is the searchDOM-method:
private function searchDOM( $content, $search, $replace, $excludedParents = [] )
{
$dom = HtmlDomParser::str_get_html(
$content,
true,
true,
DEFAULT_TARGET_CHARSET,
false,
DEFAULT_BR_TEXT,
DEFAULT_SPAN_TEXT
);
foreach ( $dom->find( 'text' ) as $element ) {
if ( !in_array( $element->parent()->tag, $excludedParents ) ) {
$element->innertext = preg_replace(
'/(?<!\w)' . preg_quote( $search, "/" ) . '(?!\w)/i',
$replace,
$element->innertext
);
}
}
return $dom->save();
}
and this is the hide_email-method:
function hide_email( $email )
{
$character_set = '+-.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle( $character_set );
$cipher_text = '';
$id = 'e' . rand( 1, 999999999 );
for ( $i = 0; $i < strlen( $email ); $i += 1 )
$cipher_text .= $key[ strpos( $character_set, $email[ $i ] ) ];
$script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
$script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script .= 'document.getElementById("' . $id . '").innerHTML=""+d+""';
$script = "eval(\"" . str_replace( [ "\\", '"' ], [ "\\\\", '\"' ], $script ) . "\")";
$script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
}
Well - this is not working as expected, because the rendered page shows only "[javascript protected email address]". If I have a look at the source, the a-tag is missing.
I have a PHP Object Array with several fields and I need to extract all the equal fields and store them into individual arrays, because I need to pass them to a bash script, and I prefer to have separate arrays, because bash is no object oriented right?
Here is what I'm trying to do:
<?php
$data = json_decode($_POST['data']);
$text_array = "'" . implode ("\n", $data->text) . "'";
$time_text = "'" . implode ("\n", $data->time_text) . "'";
$gender = "'" . implode ("\n", $data->gender) . "'";
$pitch = "'" . implode ("\n", $data->pitch) . "'";
$response = shell_exec("./test_bash.sh $pitch $gender $timetext $text_array 2>&1");
echo "$response";
?>
The data is passed from javascript to PHP through ajax. The original Object Array has this structure:
text
time_text
gender
pitch
and I create the Object Array in Javascript like:
function dataClass(text, time_txt, gender, pitch, mood) {
this.text = text;
this.time_text = time_txt;
this.gender = gender;
this.pitch = pitch;
this.mood = mood;
}
for(var i = 0; i < length - 1; i++){
data.push(new dataToSynth(subtitles_trans[i].text, subtitles_trans[i].end - subtitles_trans[i].start, genere, pitch));
}
How can I copy the object array fields to a individual arrays, in PHP?
You don't need to use json_decode. In your case "$_POST['data']" is an array, not an object. Try this code:
$data = $_POST['data'];
$text_array = "'" . implode ("\n", $data['text']) . "'";
$time_text = "'" . implode ("\n", $data['time_text']) . "'";
$gender = "'" . implode ("\n", $data['gender']) . "'";
$pitch = "'" . implode ("\n", $data['pitch']) . "'";
You can cast object values into array just you cast an string to int.
<?php
class a{
public $a="a";
public $b="b";
public $c="c";
}
$a= new a();
$b= (array)$a;
var_dump($a);
/*object(a)#1 (3) {
["a"]=>
string(1) "a"
["b"]=>
string(1) "b"
["c"]=>
string(1) "c"
}*/
var_dump($b);
/*array(3) {
["a"]=>
string(1) "a"
["b"]=>
string(1) "b"
["c"]=>
string(1) "c"
}*/
So it should be like this:
<?php
$data =(array) json_decode($_POST['data']);
$text_array = "'" . implode ("\n", $data['text']) . "'";
$time_text = "'" . implode ("\n", $data['time_text']) . "'";
$gender = "'" . implode ("\n", $data['gender']) . "'";
$pitch = "'" . implode ("\n", $data['pitch']) . "'";
$response = shell_exec("./test_bash.sh $pitch $gender $timetext $text_array 2>&1");
echo "$response";
?>
I can't retrieve json string data from my php script using ajax call.
Here is my ajax script :
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(data){
$("#app_panel").append(data.html);
$('.inv_date').hide();
}
});
and this is my php script:
<?php
//wall ===================================================
session_start();
include("../../dbinfo.inc.php");
$from = $_POST['from'];
$to = $_POST['to'];
$sel = $_POST['sel'];
// connect to the database
$client_id = $_SESSION['clientid'];
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
$results = array(
'html' => $html
);
$html = " ";
if($sel == "all"){
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
}else{
$query=" select * from tele_panel_call where (client='$client_id' AND date_time BETWEEN '$from' AND '$to') ORDER BY date_time DESC";
$result = $mysqli->query($query);
}
if ($result->num_rows > 0){
while ($row = $result->fetch_object())
{
$from = $row->from;
$to = $row->to;
$html .= '<div style="width:590px;height:15px;background: url(img/clientimg/wrap-white.png)repeat;padding: 5px 5px 5px 5px;margin-bottom:5px;">';
$query_from=" select * from tele_agent_dialer where (client='$client_id' AND (dialer='$from' OR dialer='$to'))";
$result_from = $mysqli->query($query_from);
$row_from = $result_from->fetch_assoc();
$dialer = $row_from['dialer'];
if($dialer == $from){
$image = 'outgoing';
$out = $out+1;
}
if($dialer == $to){
$image = 'incoming';
$in = $in+1;
}
if($dialer != $to & $dialer != $from){
$image = 'extension';
$ext = $ext+1;
}
$html .= '<img src="img/clientimg/'; $html .= $image; $html .= '.png" style="float:left;margin-right:10px;height:15px">';
$html .= '<div style="float:left;margin-right:5px;width:135px;height:30px;overflow:hidden;"><b>From: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $from, $matches ) )
{
$from = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $from;
$html .= '</div>
<div style="float:left;margin-right:5px;width:125px;height:30px;overflow:hidden;">
<b>To: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $to, $matches ) )
{
$to = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $to;
$html .= '</div>
<div style="float:left;width:160px;margin-right:5px;height:30px;overflow:hidden;">
<b>Date/Time: </b>'; $html .= $row->date_time;
$html .= '</div>
<div style="float:left;width:100px;margin-right:5px;height:30px;overflow:hidden;">
<b>Duration: </b>';
$duration = $row->duration;
preg_match("#(\d+):(\d+)#", $duration, $matches );
$min = $min + $matches[1];
$sec = $sec + $matches[2];
$html .= $duration;
$html .= '</div>';
$html .= '</div>';
}
}else{
echo "No results to display!";
}
$jsonString = json_encode($results);
echo $jsonString;
$mysqli->close();
?>
Can someone please tell me what I'm doing wrong here? My php script doesn't have any errors when I check the page itself.
Also it's good to add proper header for json data output (at the begining of the script for example).
header("Content-Type: application/json");
As for query results, you should debug it. Try to print the query and run it in Phpmyadmin (or other database administration tool)