I am trying to convert the following shell commands into php but I ma not getting correct results
$key = 'my_key';
$cmd = "echo -n $plaintext| openssl enc -e -aes-256-cbc -a -k $key -md md5";
$exec = exec($cmd, $output, $status);
return $status == 0 ? $output[0] : null;
the above works in php7.4. I have tried the following
$key = "my_key";
echo "key: $key\n";
//$key = password_hash($key, PASSWORD_BCRYPT, ['cost' => 12]);
//echo "key: $key\n";
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, null, 'UqA8Z5ztUYnWhnUE');
echo "ciphertext: $ciphertext\n";
echo "merged: $key$ciphertext\n";
return $key . $ciphertext;
This is not working. The key is supplied by 3rd party
UPDATE
I have tried the following
create a key and iv
# openssl enc -nosalt -aes-256-cbc -k hello-aes -P -md md5 *** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.
key=C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4
iv =D09A4D2C5DC39843FE075313A7EF2F4C
on cli I can use the key to encrypt and decrypt
encrypt
# echo -n email#gmail.com | openssl enc -e -aes-256-cbc -a -k C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4 -md md5
*** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.
U2FsdGVkX1+GpDPQ5uLeXlZL9CEgKaBDgDuwvf00m9U=
decrypt
# echo U2FsdGVkX1+GpDPQ5uLeXlZL9CEgKaBDgDuwvf00m9U= | openssl enc -d -aes-256-cbc -a -k C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4 -md md5
*** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.
email#gmail.com
In PhP
I use the key and iv I created from cli. the key is provided to me i do not get to generate this
function encryptAES256CBC(string $plaintext): string
{
$key = 'C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4';
//echo "key hex2bin ". md5($key) . "\n\n";
$iv = hex2bin('D09A4D2C5DC39843FE075313A7EF2F4C');
echo "key: $key\n";
$cipher="aes-256-cbc";
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);//, null, 'UqA8Z5ztUYnWhnUE');
echo "ciphertext_raw: $ciphertext_raw\n";
echo "base64_encode: ".base64_encode($ciphertext_raw)."\n";
echo "base64_encode md5: ".md5(base64_encode($ciphertext_raw))."\n";
echo "md5: ".md5($ciphertext_raw)."\n";
return md5($ciphertext_raw);
return $key . $ciphertext_raw;
}
I tried to decode the above output on cli to check it works but it does not. i get error bad magic number
output
key: C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4
ciphertext_raw: y▒▒yV▒ύ2▒G▒▒▒¤▒!▒▒▒%▒"ҋ~▒
base64_encode: B3n1+XlWtM+NMrlHue8R28KkmiG8tpUl/Iwi0ot+vg4=
base64_encode md5: f65b8e0ed4fc86d4b405d37a57bcd6e5
md5: 14e9f14ee94a2c34e52ad80e3f300d40
DECRYPT 14e9f14ee94a2c34e52ad80e3f300d40
[12:27:43] Destructor
root#0ea89b7ad9df:/# echo 14e9f14ee94a2c34e52ad80e3f300d40 | openssl enc -d -aes-256-cbc -a -k C639A572E14D5075C526FDDD43E4ECF6B095EA17783D32EF3D2710AF9F359DD4 -md md5
bad magic number
UPDATE
I have managed to get decypt working but encrypt not working
this is what I have
$passphrase = 'random';
$salt = openssl_random_pseudo_bytes(8);
$keyData = self::evpBytesToKey($salt, $passphrase);
$key = substr($keyData, 0, 32);
$iv = substr($keyData, 32, 16);
$method = 'AES-256-CBC';
$ciphertext_raw = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
echo "ciphertext_raw: $ciphertext_raw\n";
echo "base64_encode: ".base64_encode($ciphertext_raw)."\n";
echo "base64_encode md5: ".md5(base64_encode($ciphertext_raw))."\n";
echo "md5: ".md5($ciphertext_raw)."\n";
echo "merged: ".base64_encode($iv.$ciphertext_raw)."\n";
return md5($ciphertext_raw);
return base64_encode("Salted__" . $salt . $ciphertext_raw);
The following code is a full running example that uses the "EVP_BytesToKey" key derivation as commented by #Topaco.
Kindly note that this kind of key derivation is UNSECURE as it uses the broken MD5 algorithm and an iteration count of only 1. Please use the code only for migration purpose, thanks.
This is a possible output [as there are random elements your output will differ]:
AES CBC 256 String encryption with passphrase
# # # SECURITY WARNING: This code is provided for achieve # # #
# # # compatibility between different programming languages. # # #
# # # It is not necessarily fully secure. # # #
# # # Its security depends on the complexity and length # # #
# # # of the password, because of only one iteration and # # #
# # # the use of MD5. # # #
# # # DO NOT USE THIS CODE IN PRODUCTION # # #
passphrase: my secret passphrase
* * * Encryption * * *
ciphertext: U2FsdGVkX1/+hqfCdNaZ36kZzPzwvFXkr4nEySMEgdVdPnPrGUj2Gi1t2pspAH2WHVEVgKHKWfR2Gc0sKnTlLg==
output is (Base64) ciphertext
* * * Decryption * * *
passphrase: my secret passphrase
ciphertext (Base64): U2FsdGVkX19rV+JOoeF72K54jlyJ47tNEsMjih7gDnFUysZFaw+WnYTB5L/hc2+rssFj1hXw3N8kkikHwClB2w==
input is (Base64) ciphertext
plaintext: The quick brown fox jumps over the lazy dog
code:
<?php
// source: https://github.com/blocktrail/cryptojs-aes-php/blob/master/src/CryptoJSAES.php
// author: BlockTrail
function aesCbcPassphraseEncryptToBase64($passphrase, $data, $salt = null) {
$salt = $salt ?: openssl_random_pseudo_bytes(8);
list($key, $iv) = evpkdf($passphrase, $salt);
$ct = openssl_encrypt($data, 'aes-256-cbc', $key, true, $iv);
return encode($ct, $salt);
}
function aesCbcPassphraseDecryptFromBase64($passphrase, $base64) {
list($ct, $salt) = decode($base64);
list($key, $iv) = evpkdf($passphrase, $salt);
$data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
return $data;
}
function evpkdf($passphrase, $salt) {
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
return [$key, $iv];
}
function decode($base64) {
$data = base64_decode($base64);
if (substr($data, 0, 8) !== "Salted__") {
return "";
}
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
return [$ct, $salt];
}
function encode($ct, $salt) {
return base64_encode("Salted__" . $salt . $ct);
}
echo 'AES CBC 256 String encryption with passphrase' . PHP_EOL;
echo PHP_EOL . '# # # SECURITY WARNING: This code is provided for achieve # # #' . PHP_EOL;
echo '# # # compatibility between different programming languages. # # #' . PHP_EOL;
echo '# # # It is not necessarily fully secure. # # #' . PHP_EOL;
echo '# # # Its security depends on the complexity and length # # #' . PHP_EOL;
echo '# # # of the password, because of only one iteration and # # #' . PHP_EOL;
echo '# # # the use of MD5. # # #' . PHP_EOL;
echo '# # # DO NOT USE THIS CODE IN PRODUCTION # # #' . PHP_EOL;
$plaintext = 'The quick brown fox jumps over the lazy dog';
$passphrase = 'my secret passphrase';
echo PHP_EOL . 'passphrase: ' . $passphrase . PHP_EOL;
echo PHP_EOL . '* * * Encryption * * *' . PHP_EOL;
$ciphertextBase64 = aesCbcPassphraseEncryptToBase64($passphrase, $plaintext);
echo 'ciphertext (Base64): ' . $ciphertextBase64 . PHP_EOL;
echo 'output is (Base64) ciphertext' . PHP_EOL;
echo PHP_EOL . '* * * Decryption * * *' . PHP_EOL;
$decryptionPassphrase = $passphrase;
$ciphertextDecryptionBase64 = $ciphertextBase64;
echo 'decryptionPassphrase: ' . $decryptionPassphrase . PHP_EOL;
echo 'ciphertext (Base64): ' . $ciphertextDecryptionBase64 . PHP_EOL;
echo 'input is (Base64) ciphertext' . PHP_EOL;
$decryptedtext = aesCbcPassphraseDecryptFromBase64($decryptionPassphrase, $ciphertextDecryptionBase64);
echo 'plaintext: ' . $decryptedtext . PHP_EOL;
?>
Related
I have this code to display field order total amount on the order edit page:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta($order){
$method = get_post_meta( $order->id, '_payment_method', true );
if($method != 'pec_gateway_check')
return;
echo date('Y/m/d', strtotime("+40 days")) . " تاریخ چک صیادی";
}
I want add below code to show total amount in this page:
How to do that?
global $woocommerce;
$carttotal = $woocommerce->cart->total;
$total35 = $carttotal*0.35;
$total65 = $carttotal*0.65;
echo number_format($total35) . " ریال پرداخت شده";
echo number_format($total65) . " ریال مبلغ چک پرداختی";
From your question, it sounds like you just need to add the code you've written to the function you already have. So something like this:
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta($order){
global $woocommerce;
$method = get_post_meta( $order->id, '_payment_method', true );
if($method != 'pec_gateway_check')
return;
echo date('Y/m/d', strtotime("+40 days")) . " تاریخ چک صیادی";
$carttotal = $woocommerce->cart->total;
$total35 = $carttotal*0.35;
$total65 = $carttotal*0.65;
echo number_format($total35) . " ریال پرداخت شده";
echo number_format($total65) . " ریال مبلغ چک پرداختی";
}
Hi I have no idea if this is a legitimate question for SO.
But I have a script i made for sorting photos into folders based on tags. It uses the exifr package to do this.
However, it's running very slow. I've tried to improve it using guides but what I ever I make ends up not working. Is there someone with understanding of vectorization and or optimization that could give point to some suggestions.
Thanks!
#----- Imports ----
library(exifr)
# ---------- Functions ----------
'%!in%' <- function(x,y)!('%in%'(x,y))
tagcatcher <- function(dat){
tags <- c()
for (tagNameTry in keywords_names ) {
if (tagNameTry %in% names(dat)) {
xs <- dat[tagNameTry]
if (typeof(xs) == "list") {
xs <- xs[[1]]
l <- length(xs[[1]])
x <- c()
for (i in 1:l) {
x <- c(x,xs[[1]][i])
}
} else {
x <- xs
}
tags <- c(tags,x)
}
}
tags <- unique(tags)
return(tags)
}
# ----------- Settings ----------
ss <- "/"
haystacks <- c("H:MyPhotos")
organizedMediaPhotos <- "V:/Photos"
all_files <- list.files(haystacks,recursive = TRUE, full.names = TRUE)
keywords_names <- c("Category","XPKeywords","Keywords")
ctags <- list.dirs(organizedMediaPhotos)[list.dirs(organizedMediaPhotos) %!in% organizedMediaPhotos]
current_tags <- c()
for (ctag in ctags) {
x <- strsplit(ctag,"/")
x <- x[[1]]
x <- x[length(x)]
current_tags <- c(current_tags,x)
}
# Main Loop - That Needs to be faster
for (cur_file in all_files) {
print(cur_file)
cur_dat <- read_exif(cur_file,tags=keywords_names)
tags <- tagcatcher(cur_dat)
for (tag in tags) {
tag_folder <- paste(organizedMediaPhotos,ss,tag,sep="")
if (tag %!in% current_tags) {
dir.create(tag_folder)
print(paste("creating tag folder: ",tag_folder))
}
pic_path <- paste(tag_folder,ss,basename(cur_file),sep="")
if (!file.exists(pic_path)) {
file.copy(cur_file,pic_path)
print(paste("moved file from ",cur_file, " to ", pic_path))
}
}
}
You can give this a try
for x in *.jpg; do
d=$(date -r "$x" +%Y-%m-%d)
mkdir -p "$d"
mv -- "$x" "$d/"
done
For powershell:
Param(
[string]$source,
[string]$dest,
[string]$format = "yyyy/yyyy_MM/yyyy_MM_dd"
)
$shell = New-Object -ComObject Shell.Application
function Get-File-Date {
[CmdletBinding()]
Param (
$object
)
$dir = $shell.NameSpace( $object.Directory.FullName )
$file = $dir.ParseName( $object.Name )
# First see if we have Date Taken, which is at index 12
$date = Get-Date-Property-Value $dir $file 12
if ($null -eq $date) {
# If we don't have Date Taken, then find the oldest date from all date properties
0..287 | ForEach-Object {
$name = $dir.GetDetailsof($dir.items, $_)
if ( $name -match '(date)|(created)') {
# Only get value if date field because the GetDetailsOf call is expensive
$tmp = Get-Date-Property-Value $dir $file $_
if ( ($null -ne $tmp) -and (($null -eq $date) -or ($tmp -lt $date))) {
$date = $tmp
}
}
}
}
return $date
}
function Get-Date-Property-Value {
[CmdletBinding()]
Param (
$dir,
$file,
$index
)
$value = ($dir.GetDetailsof($file, $index) -replace "`u{200e}") -replace "`u{200f}"
if ($value -and $value -ne '') {
return [DateTime]::ParseExact($value, "g", $null)
}
return $null
}
Get-ChildItem -Attributes !Directory $source -Recurse |
Foreach-Object {
Write-Host "Processing $_"
$date = Get-File-Date $_
if ($date) {
$destinationFolder = Get-Date -Date $date -Format $format
$destinationPath = Join-Path -Path $dest -ChildPath $destinationFolder
# See if the destination file exists and rename until we get a unique name
$newFullName = Join-Path -Path $destinationPath -ChildPath $_.Name
if ($_.FullName -eq $newFullName) {
Write-Host "Skipping: Source file and destination files are at the same location. $_"
return
}
$newNameIndex = 1
$newName = $_.Name
while (Test-Path -Path $newFullName) {
$newName = ($_.BaseName + "_$newNameIndex" + $_.Extension)
$newFullName = Join-Path -Path $destinationPath -ChildPath $newName
$newNameIndex += 1
}
# If we have a new name, then we need to rename in current location before moving it.
if ($newNameIndex -gt 1) {
Rename-Item -Path $_.FullName -NewName $newName
}
Write-Host "Moving $_ to $newFullName"
# Create the destination directory if it doesn't exist
if (!(Test-Path $destinationPath)) {
New-Item -ItemType Directory -Force -Path $destinationPath
}
robocopy $_.DirectoryName $destinationPath $newName /mo
PS: I had tried this a few years back and it worked like a charm
You can change your if command to something like this:
if [[ "$t" =~ IMG_+[0-9]{8}[a-zA-Z]*$ ]]
The =~ is a regular expression comparison operator which is introduced in bash version 3 and above.
By using this if statement you can catch names like IMG_11111111alphabets.ext. You can play with it and customize it according to your needs. For more information have a look at this: Bash's regular expression
I have a problem with getting shortcode values into variables, you advise please?
This is the code:
class virtual_cheshire_ring
{
public $start_date = '';
public $end_date = '';
public $db_table_participants = '';
public $db_table_log = '';
public function __construct()
{
add_shortcode('virtual_crr', array($this, 'virtual_crr') );
}
public function virtual_crr($atts)
{
//******************************
//** Get shortcode parameters **
//******************************
global $post;
$shortcode_defaults = [ 'start_date' => '2020-01-01',
'end_date' => '2050-00-01',
'db_table_participants' => 'db_table_participants',
'db_table_log' => 'db_table_log',
];
$attributes = array_merge($shortcode_defaults,$atts);
$this->$start_date = $attributes['start_date'];
$this->$end_date = $attributes['end_date'];
$this->$db_table_participants = $attributes['db_table_participants'];
$this->$db_table_log = $attributes['db_table_log'];
var_dump($attributes);
$html = 'start_date = ' . $this->$start_date . ' / ' . $attributes['start_date'] . '<br>';
$html .= 'end_date = ' . $this->$end_date . ' / ' . $attributes['end_date'] . '<br>';
$html .= 'db_table_participants = ' . $this->$db_table_participants . ' / ' . $attributes['db_table_participants'] . "<br>";
$html .= 'db_table_log = ' . $this->$db_table_log . ' / ' . $attributes['db_table_log'] . '<br>';
return $html;
}
}
The shortcode on the webpage is:
[virtual_crr start_date="2020-06-02" end_date="2020-06-30"]
The var_dump($attributes) returns:
array (size=4)
'start_date' => string '2020-06-02' (length=10)
'end_date' => string '2020-06-30' (length=10)
'db_table_participants' => string 'db_table_participants' (length=21)
'db_table_log' => string 'db_table_log' (length=12)
The output on the webpage is:
start_date = db_table_log / 2020-06-02
end_date = db_table_log / 2020-06-30
db_table_participants = db_table_log / db_table_participants
db_table_log = db_table_log / db_table_log
So clearly I'm not understanding something fundamental as the '$this->$xxxx values differ from the $attributes array values, can you advise please?
Many thanks in advance
Alan
I think you need to remove the $ from your param when you access them with $this.
So it would look more like:
<?php
public function virtual_crr($atts)
{
//******************************
//** Get shortcode parameters **
//******************************
global $post;
$shortcode_defaults = [
'start_date' => '2020-01-01',
'end_date' => '2050-00-01',
'db_table_participants' => 'db_table_participants',
'db_table_log' => 'db_table_log',
];
$attributes = array_merge($shortcode_defaults,$atts);
$this->start_date = $attributes['start_date'];
$this->end_date = $attributes['end_date'];
$this->db_table_participants = $attributes['db_table_participants'];
$this->db_table_log = $attributes['db_table_log'];
var_dump($attributes);
$html = 'start_date = ' . $this->start_date . ' / ' . $attributes['start_date'] . '<br>';
$html .= 'end_date = ' . $this->end_date . ' / ' . $attributes['end_date'] . '<br>';
$html .= 'db_table_participants = ' . $this->db_table_participants . ' / ' . $attributes['db_table_participants'] . "<br>";
$html .= 'db_table_log = ' . $this->db_table_log . ' / ' . $attributes['db_table_log'] . '<br>';
return $html;
}
?>
How to make a line break? For example:
line1
line2
line3
after decoding, look like -> line1 line2 line3
$key = $_POST['key']; $input = $_POST['text'];
$algo = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
$iv_size = mcrypt_get_iv_size($algo, $mode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
switch($_POST['do']){
default: die;
case 'encode':
$ciphertext = mcrypt_encrypt($algo, $key, $input, $mode, $iv);
$ciphertext = $iv . $ciphertext;
echo base64_encode($ciphertext);
break;
case 'decode':
$ciphertext_dec = base64_decode($input);
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
echo htmlspecialchars(mcrypt_decrypt($algo, $key, $ciphertext_dec, $mode, $iv_dec));
break;
}
Solved. I use nl2br
echo nl2br(htmlspecialchars(mcrypt_decrypt($algo, $key, $ciphertext_dec, $mode, $iv_dec)));
Kindly help on the code below. What happens is that I get the latitude and longitude of the name of a place when I click on a button. However, of late, it is not working. It prints that "Address x failed to Geocode. Received status " Note that x is a given address and no status code is given.
$id=$_REQUEST['id'];
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "xxxxxxx");
$query = "SELECT * FROM markers WHERE mid = $id LIMIT 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
// Initialize delay in geocode speed
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?address=";
if($row = #mysql_fetch_assoc($result)){
$geocode_pending = true;
$address = $row["address"];
while ($geocode_pending) {
$request_url = $base_url . urlencode($address) . "&sensor=false&key=" . KEY;
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
//$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
//$lat = $coordinatesSplit[1];
//$lng = $coordinatesSplit[0];
list($lat,$lng) = explode(",",$coordinates);
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE mid = '%s' LIMIT 1;",
mysql_real_escape_string($lng),
mysql_real_escape_string($lat),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}else{
echo "$lat;$lng";
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 100000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
I'm not sure on which API your code is based on, but the response of the current API will not work with these lines:
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
There are no elements Response,Status or code, furthermore the response will not contain a numeric status-code.
use this instead:
$status = $xml->status;
if (strcmp($status, "OK") == 0) {
To fix the rest of the code please take a look at the structure of the returned XML, there are also no elements Placemark,Point and coordinates.
it should be:
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;