AES 256 GCM with php 5.6 - aes-gcm

I have taken reference of code from this post :
Trying to decrypt with aes-256-gcm with php
Code :
< ?php
$textToEncrypt = "demo text";
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$tag_length = 16;
$iv = openssl_random_pseudo_bytes($iv_len);
$ciphertext = openssl_encrypt($textToEncrypt, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv.$ciphertext);
$textToDecrypt = $encrypted;
$encrypted = base64_decode($textToDecrypt);
$password = '3sc3RLrpd17';
$key = substr(hash('sha256', $password, true), 0, 32);
$cipher = 'aes-256-gcm';
$iv_len = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted, 0, $iv_len);
$ciphertext = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
var_dump (openssl_error_string());
var_dump($decrypted);
echo $decrypted;
?>
Running this code on PHP 5.6
Now the issue is I am always getting false as decrypted text.
What is wrong?

Related

How to get the Gross Sales from the Square Order API?

Qn1) I have tried getting the gross sales from the Order API. However, I could only be able to get each lineitem gross value concatenating with one and another ...
Gross value that is concatenating
Qn2) I tried to echo all the item name, qty and etc to insert it into my database although it works but I am getting an error message shown below
Error message
Here is my code: (Have replaced the access token and the location_id to 'XXXX')
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
echo (array_sum($grossSales)/100); //Qn1
echo($orderid. " ". $lineItemsID ." ".$catalogObjID." ".$itemName ." ".$itemQty." <br/>"); //Qn2
}
}
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
$grossSales = array();
if (is_array($orders) || is_object($orders)) {
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
if (is_array($lineItems) || is_object($lineItems)){
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
}
}
}
}
$sum = 0;
foreach($grossSales as $key=>$value)
{
$sum+= $value;
}
echo ($sum/100);
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>

How to use SHA256 With salt?

I have a hash function on sa-mp
new MyHash[256];
SHA256_PassHash(inputtext, "78sdjs86d2h", MyHash, sizeof(MyHash));
if(!strcmp(MyHash, PlayerInfo[playerid][pKey]))
I assume 78sdjs86d2h is the salt, but how do I set the salt in PHP?
I am using this code, and it hashes but not with my salt.
if(isset($_POST['username']) && isset($_POST['password'])){
mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
$username = mysql_real_escape_string($_POST['username']);
$parola = mysql_real_escape_string($_POST['password']);
$hash = hash('sha256', $parola);
$check = get_row("SELECT ID FROM players WHERE Name='$username' && password='$hash' LIMIT 1");
if(isset($check['ID']))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$id = $check['ID'];
header("location: index.php");
}
else
{
printf("%s", $hash);
$err = 'Username sau parola incorecte';
}
}
How do I make it hash with my own salt?
UPDATE: Tried this way
$username = mysqli_real_escape_string($DB_H, addslashes($_POST['username']));
$password1 = $_POST['password'];
$salt = '78sdjs86d2h';
$parola = hash('sha256', $password1 . $salt);
The result: 33ca067dc70ef75fc1a1107f4345f3a819ecca657d3d9646d26822fd691cd10c
The original: BFD2832240F5FC1FD12004634EBE9FDE97BD0D4690695DFAC1350D0AE037398F

How to grab contacts from gmail using google API's and contact grabber in PHP?

In my project i want to grab the contacts from gmail using google API's. I provide three keys such as client id, client secret and signature key. When i trying to get contacts the pop-up window is showing error message "Signature key must be formatted". What i have done wrong? Thanks in advance.
Here is my code
keyConfig.php
<?php
$apiRequestUrl = "https://stescodes.com/api/contactsapi.aspx"; // StesCodes contact grabber API request url
$originalsignaturekey = "lxFWDA5ng36sdvlFGukof75vyi";//replace with your signature key
$gmailConsumerKey = "1009516162377-n5s7lo5b4dvlt8e7s3rt12f8i02lpk1f.apps.googleusercontent.com";
$gmailConsumerSecret = "raCUba1smsZCzrVNjqFIqiqC";
$YahooConsumerKey = "your yahoo api key";
$YahooConsumerSecret = "your yahoo api key";
$LiveConsumerKey = "your live api key";
$LiveConsumerSecret = "your live api key";
$fbConsumerKey = "your facebook api key";
$fbConsumerSecret = "your facebook api key";
$callbackurl = "http://localhost/grab/oauth.php";// eg: return url after user authentication http://yourdomain/oauth.php
$currentdirpath = "http://dev.stescodes.com/";//your current web directory path eg:http://yourdomain/
?>
oauth.php
<?php
session_start();
?>
<?php include 'keyConfig.php'; ?>
<html>
<head><title></title>
<script>
function redirectrequest(a)
{
window.location = a;
}
function closepopup(a,b,c,d) {
window.opener.startGrabbingContactsOauth(a,b,c,d);
window.self.close();
}
</script>
</head>
<body>
<?php
$servicename = "gmail";
$token = "";
$ConsumerKey = "";
$ConsumerSecret="";
$tokensecret="";
$tokenverifier="";
$flag=0;
$parameters="";
if($_GET['currpage']!=null)
$_SESSION['currpage']=$_GET['currpage'];
if($_SESSION['currpage']=="gmail")
{
$servicename = "gmail";
$ConsumerKey = $gmailConsumerKey;
$ConsumerSecret = $gmailConsumerSecret;
if ($_GET['code'] != null)
{
$token = $_GET['code'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="yahoo")
{
$servicename = "yahoo";
$ConsumerKey = $YahooConsumerKey;
$ConsumerSecret = $YahooConsumerSecret;
if (($_GET['oauth_token'] != null) && ($_GET['oauth_verifier'] != null))
{
$token = $_GET['oauth_token'];
$tokenverifier = $_GET['oauth_verifier'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="facebook")
{
$servicename = "facebook";
$ConsumerKey = $fbConsumerKey;
$ConsumerSecret = $fbConsumerSecret;
if (($_GET['code'] != null))
{
$token = $_GET['code'];
$tokenverifier = "";
$tokensecret = "";
$flag = 1;
}
}
else if(($_SESSION['currpage']=="msn") || ($_SESSION['currpage']=="hotmail") || ($_SESSION['currpage']=="msnmessenger"))
{
$servicename = $_SESSION['currpage'];
$ConsumerKey = $LiveConsumerKey;
$ConsumerSecret = $LiveConsumerSecret;
//Live settings
if ($_GET["code"] != null)
{
$token = $_GET["code"];
$flag = 1;
}
}
if ($flag == 1)
{
$parameters = "type=accesstoken&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) . "&Token=" . urlencode($token) . "&TokenSecret=" . urlencode($tokensecret) . "&TokenVerifier=" . urlencode($tokenverifier);
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $_SESSION['tokenverifier'];
$_SESSION["consumerkey"] = $ConsumerKey;
$_SESSION["consumersecret"] = $ConsumerSecret;
echo "<SCRIPT LANGUAGE=\"javascript\"> closepopup('".$servicename."',". $result .",'".$ConsumerKey."','".$ConsumerSecret."');</SCRIPT>";
}
else
{
$parameters = "type=authenticationurl&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) ;
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $tokenverifier;
echo "<SCRIPT LANGUAGE=\"javascript\"> redirectrequest('".$authdetails[details][authUrl]."'); </SCRIPT>";
}
?>

WHMCS License Addon not working

I have just authored a WHMCS addon module that works great on my server; however, others that have tried to use it are not having success. There are 2 issues...
1) I use the WHMCS License Addon; however, it does not appear that their remote machines are making a successful connection to my machine to validate the license. I use the WHMCS supplied code to handle the connection and validation. No idea on what else to check... Any ideas?
2) I have a database that my script checks to see if the user has the most current version of the script. Access to the database works great from my local machine and RemoteSQL is enabled with a % wildcard so anyone should be able to connect but yet the remote machines do not seem to be able to connect. Here is my info...
$link = mysql_connect('gjinternetsolutions.com', 'gj_Guest', 'Password1');
mysql_select_db("gj_Software", $link);
$query = "SELECT * FROM `VersionCheck` where `Software`='RedemptionFee'";
... additional code to display the results
Is anyone able to successfully make a remote connection to the above database?
=========== UPDATE ===========
The second issue above has been resolved. We are still having an issue with the licensing code.... Here is what we have....
# Values obtained from our database...
$localkey=$row['LocalKey'];
$licensekey=$vars['License'];
$results = RedemptionFee_check_gj_license($licensekey,$localkey);
function RedemptionFee_check_gj_license($licensekey,$localkey="")
{
$whmcsurl = "http://gjinternetsolutions.com/home/";
$licensing_secret_key = "####-VALUE REMOVED FOR THIS POST-####"; # Unique value, should match what is set in the product configuration for MD5 Hash Verification
$check_token = time().md5(mt_rand(1000000000,9999999999).$licensekey);
$checkdate = date("Ymd"); # Current date
$usersip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];
$localkeydays = 1; # How long the local key is valid for in between remote checks
$allowcheckfaildays = 5; # How many days to allow after local key expiry before blocking access if connection cannot be made
$localkeyvalid = false;
if ($localkey) {
$localkey = str_replace("\n",'',$localkey); # Remove the line breaks
$localdata = substr($localkey,0,strlen($localkey)-32); # Extract License Data
$md5hash = substr($localkey,strlen($localkey)-32); # Extract MD5 Hash
if ($md5hash==md5($localdata.$licensing_secret_key)) {
$localdata = strrev($localdata); # Reverse the string
$md5hash = substr($localdata,0,32); # Extract MD5 Hash
$localdata = substr($localdata,32); # Extract License Data
$localdata = base64_decode($localdata);
$localkeyresults = unserialize($localdata);
$originalcheckdate = $localkeyresults["checkdate"];
if ($md5hash==md5($originalcheckdate.$licensing_secret_key)) {
$localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-$localkeydays,date("Y")));
if ($originalcheckdate>$localexpiry) {
$localkeyvalid = true;
$results = $localkeyresults;
$validdomains = explode(",",$results["validdomain"]);
if (!in_array($_SERVER['SERVER_NAME'], $validdomains)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
$validips = explode(",",$results["validip"]);
if (!in_array($usersip, $validips)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
if ($results["validdirectory"]!=dirname(__FILE__)) {
$localkeyvalid = false;
$localkeyresults["status"] = "Invalid";
$results = array();
}
}
}
}
}
if (!$localkeyvalid) {
$postfields["licensekey"] = $licensekey;
$postfields["domain"] = $_SERVER['SERVER_NAME'];
$postfields["ip"] = $usersip;
$postfields["dir"] = dirname(__FILE__);
if ($check_token) $postfields["check_token"] = $check_token;
if (function_exists("curl_exec")) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsurl."modules/servers/licensing/verify.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
} else {
$fp = fsockopen($whmcsurl, 80, $errno, $errstr, 5);
if ($fp) {
$querystring = "";
foreach ($postfields AS $k=>$v) {
$querystring .= "$k=".urlencode($v)."&";
}
$header="POST ".$whmcsurl."modules/servers/licensing/verify.php HTTP/1.0\r\n";
$header.="Host: ".$whmcsurl."\r\n";
$header.="Content-type: application/x-www-form-urlencoded\r\n";
$header.="Content-length: ".#strlen($querystring)."\r\n";
$header.="Connection: close\r\n\r\n";
$header.=$querystring;
$data="";
#stream_set_timeout($fp, 20);
#fputs($fp, $header);
$status = #socket_get_status($fp);
while (!#feof($fp)&&$status) {
$data .= #fgets($fp, 1024);
$status = #socket_get_status($fp);
}
#fclose ($fp);
}
}
if (!$data) {
$localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-($localkeydays+$allowcheckfaildays),date("Y")));
if ($originalcheckdate>$localexpiry) {
$results = $localkeyresults;
} else {
$results["status"] = "Invalid";
$results["description"] = "Remote Check Failed";
return $results;
}
} else {
preg_match_all('/<(.*?)>([^<]+)<\/\\1>/i', $data, $matches);
$results = array();
foreach ($matches[1] AS $k=>$v) {
$results[$v] = $matches[2][$k];
}
}
if ($results["md5hash"]) {
if ($results["md5hash"]!=md5($licensing_secret_key.$check_token)) {
$results["status"] = "Invalid";
$results["description"] = "MD5 Checksum Verification Failed";
return $results;
}
}
if ($results["status"]=="Active") {
$results["checkdate"] = $checkdate;
$data_encoded = serialize($results);
$data_encoded = base64_encode($data_encoded);
$data_encoded = md5($checkdate.$licensing_secret_key).$data_encoded;
$data_encoded = strrev($data_encoded);
$data_encoded = $data_encoded.md5($data_encoded.$licensing_secret_key);
$data_encoded = wordwrap($data_encoded,80,"\n",true);
$results["localkey"] = $data_encoded;
}
$results["remotecheck"] = true;
}
unset($postfields,$data,$matches,$whmcsurl,$licensing_secret_key,$checkdate,$usersip,$localkeydays,$allowcheckfaildays,$md5hash);
return $results;
}
Yes, I can connect using the details above.
Query run:
SELECT * FROM `gj_Software`.`VersionCheck` where `Software`='RedemptionFee'
Result:
# Software, Version, URL
'RedemptionFee', '1.0', 'http://GJinternetSolutions.com/home/upgrade.php?type=package&id=660'
Hope this helps.
Ash

DB drivers not specified

I have perl script which on running gives me this error.What could be the error ? because i just changed the host and DB connection setings. Earlier the script worked fine.
I get below error
"dbi:Oracle:host=localhost;sid=nms", 'user', 'password', no database driver specified and DBI_DSN env var not set at ./test.pl line 9..
And here's the code:
sub connect{
my $self = shift;
$logger->debug("Connecting to: " . $self->{config}->{connection}->{host});
$self->{db} = DBI->connect("$self->{config}->{connection}->{host}",
"$self->{config}->{login}->{user}",
"$self->{config}->{login}->{password}")
or ($logger->fatal("Connection Failed : " . $DBI::errstr . " : " . $self->{config}->{login}->{user} . ":" . $self->{config}->{login}->{password} )
and return 0);
return 1; }–
You're missing "dbi:Oracle:", and when connecting to Oracle you don't use host but refer to name from Tnsnames.ora, ie. ORA11 or using complete string instead:
$CFG->{TNS_NAME} = "(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = ORA11)
)
)";
# ..
$CFG->{TNS_NAME} = "ORA11";
my $DB = DBI->connect(
"dbi:Oracle:",
"$CFG->{USER}/$CFG->{PASSWORD}#". $CFG->{TNS_NAME},
"",
{
ChopBlanks => 1,
AutoCommit => 0,
RaiseError => 1,
},
);
Are you sure your dns var is correct ?
it should be formatted like that : "dbi:<driver>:<database>:<host>:<port>";
use DBI;
$database = 'your_db_name';
$host = 'test.com';
$port = '1521';
$user = 'your_user';
$password = 'your_password';
$dsn = 'dbi:Oracle:'.$database.':'.$host.':'.$port;
$db = DBI->connect($dsn, $user, $password, { 'RaiseError' => 1, 'PrintError' => 0, 'AutoCommit' => 0 })
or die "Unable to connect: $DBI::errstr";
You can also try to set your ORACLE_HOME and ORACLE_OWNER env variable before your DBI->connect():
$ENV{'ORACLE_HOME'} = '...' # path to your oracle lib
$ENV{'ORACLE_OWNER'} = 'oracle'; # Owner