Replicating .Net encryption in PHP - php

I am attempting to replicate the encryption method that is already in existence for part of an application that was written in VB.Net, in PHP. The resulting encrypted values must be the same. I don't have much experience doing encryption and despite my best effort in scouring the web for information my encrypted values do not match. Could someone let me know where I am going wrong in my PHP code?
Here is the .Net process. Unfortunately this method cannot be changed at this time.
Public Class Encrypt
'8 bytes randomly selected for both the Key and the Initialization Vector
'the IV is used to encrypt the first block of text so that any repetitive
'patterns are not apparent
Private Shared KEY_64() As Byte = {42, 16, 93, 156, 78, 4, 218, 32}
Private Shared IV_64() As Byte = {55, 103, 246, 79, 36, 99, 167, 3}
Public Function EncryptPwd(ByVal value As String) As String
Try
Dim cryptoProvider As DESCryptoServiceProvider = _
New DESCryptoServiceProvider()
Dim ms As MemoryStream = New MemoryStream()
Dim cs As CryptoStream = _
New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), _
CryptoStreamMode.Write)
Dim sw As StreamWriter = New StreamWriter(cs)
sw.Write(value)
sw.Flush()
cs.FlushFinalBlock()
ms.Flush()
'convert back to a string
Return Convert.ToBase64String(ms.GetBuffer(), 0, CInt(ms.Length))
Finally
End Try
End Function
End Class
Here is my PHP.
<?php
function addpadding($string, $blocksize = 8)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
?>
<form id="form1" name="form1" method="post" action="">
enter text
<input name="data" type="text" />
<input type="hidden" value="op" name="op" />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
if(!isset($_POST['op'])) {
}else {
$buffer = $_POST['data'];
$keyArray=array( 42, 16, 93, 18, 156, 78, 4, 32 );
$key=null;
foreach ($keyArray as $element)
$key.=CHR($element);
$ivArray=array( 55, 103, 246, 79, 36, 99, 167, 3 );
$iv=null;
foreach ($ivArray as $element)
$iv.=CHR($element);
echo "Key: " .$key. "<br>";
echo "IV: " .$iv. "<br>";
echo "Result: " .base64_encode(mcrypt_cbc(MCRYPT_DES, $key, addpadding($buffer), MCRYPT_ENCRYPT, $iv));
}
?>

Looks like a typo
Private Shared KEY_64() As Byte = {42, 16, 93, 156, 78, 4, 218, 32}
$keyArray=array( 42, 16, 93, 18, 156, 78, 4, 32 );
try
$keyArray=array(42, 16, 93, 156, 78, 4, 218, 32);

I've had similar issues taking RSA-encrypted data from .Net to be decrypted in PHP. Typically it came down to a character set issue. If possible, make sure both systems are handling string values as UTF-8 strings.

Related

Am I decrypting this correctly?

Given the following inputs:
CLIENT RANDOM : 61fc160e0a6e96db43aebcca55da7fbccb97cc04d59fcc105490b4396a915ab9
SERVER RANDOM : f0ecb127db6e353a2985894c123532a8d092fafcf7cdce3a444f574e47524401
PREMASTER KEY : 0303ec4418e91f0abf9a012f524b61c0312008641ebce76d68b2417447e3d9a970d02fd65a20e5e3e98413dbd13b6536
First I use these input to calculate the following key buffers:
CLIENT MAC: 500c7c6e6101cb1693b4cee7db6fb0bc2725deca
SERVER MAC: 41e260280fe213bd5f2c0412c69389cac2e39e4f
CLIENT KEY: c17226212f6195c1515602a0c0864ec90e73e7bcd05ad90b196fd5a5cb2445f2
SERVER KEY: 6b07166b634a7e58e623b969eb0c024a1e866bc2719c054e1a05849b87ccf79b
CLIENT IV: dac71f7b3639cf4d4ec86ee51b9530f6
SERVER IV: c1212631365432c8d5a4c93f6f999a8e
I calculate these values using helper functions I found online:
function p_hash($algo, $secret, $seed, $size) {
$output = "";
$a = $seed;
while (strlen($output) < $size) {
$a = hash_hmac($algo, $a, $secret, true);
$output .= hash_hmac($algo, $a . $seed, $secret, true);
}
return substr($output, 0, $size);
}
function prf_tls12($secret, $label, $seed, $size) {
return p_hash("sha256", $secret, $label . $seed, $size);
}
function generate_master($pre_master_secret, $client_random, $server_random) {
return prf_tls12($pre_master_secret, 'master secret', $client_random . $server_random, 48);
}
$client_random = hex2bin('61fc160e0a6e96db43aebcca55da7fbccb97cc04d59fcc105490b4396a915ab9');
$server_random = hex2bin('f0ecb127db6e353a2985894c123532a8d092fafcf7cdce3a444f574e47524401');
$pre_master_secret = hex2bin('0303ec4418e91f0abf9a012f524b61c0312008641ebce76d68b2417447e3d9a970d02fd65a20e5e3e98413dbd13b6536');
$master_secret = generate_master($pre_master_secret, $client_random, $server_random);
$key_buffer = prf_tls12($master_secret, 'key expansion', $server_random . $client_random, 136);
$client_mac = substr($key_buffer, 0, 20);
$server_mac = substr($key_buffer, 20, 20);
$client_key = substr($key_buffer, 40, 32);
$server_key = substr($key_buffer, 72, 32);
$client_iv = substr($key_buffer, 104, 16);
$server_iv = substr($key_buffer, 120, 16);
Here I have an AES_256_CBC encrypted message sent from the CLIENT ---> SERVER in Hex format
$EncryptedMessage = 'f32da333a3416888d55c583c9796f8fc498895e386616a62aa364a41cd2bfc203c1f296b4afd9c4a9674c993bf0db558de0c0cb2b3dc4b083af3824e0b9a3327';
I run the following code using the PHPSECLIB v3.0 plugin:
$cipher = new AES('cbc');
$cipher->setIV($client_iv);
$cipher->setKey($client_key);
$cipher->disablePadding();
$DecryptedMessage = bin2hex($cipher->decrypt(hex2bin($EncryptedMessage)));
print($DecryptedMessage);
I get the following output in Hex:
f889ff0ce7cc744c2182363e7117ae74e34ccb0510099e7c11133c369f98468de9f20fa6e7207c8121484a9663929d1af4bffb5410da37029aa26b9298411e3b
Basically, I have no idea whether I'm doing this right or not. I dont seem to see anything in my decrypted message. Also, unless I specifically use the $cipher->disablePadding(); I will get a PHP Fatal Error saying that PHP Fatal error: Uncaught phpseclib3\Exception\BadDecryptionException: The ciphertext has an invalid padding length (81) compared to the block size (16)
Note: This is supposed to be an "Encrypted Handshake Message" sent as the first message from a client to server after the Key Exchange using TLS 1.2. I am unable to determine if my decryption is correct, since I cant find much on the structure of value anywhere. Any help is appreciated, thanks!

Which are the hashing technique in php other than openssl_pbkdf2, hash_pbkdf2?

Which hashing method is used to hash the word 'sb#123' to get the hash $pbkdf2-sha512$25000$iTGGMAbg3FsLgdD6X8u59w$LXi2AGKllnsYpfyR0M0aQZTvF2EwhwEI4elKXehjNzy2ZL8Q.w.wceJiIq45PFAjb9QWHmzeQzr3GdZr83qjMA
openssl_pbkdf2
hash_pbkdf2
openssl_pbkdf2('sb#123', 'iTGGMAbg3FsLgdD6X8u59w, 64, 25000, 'sha512');
hash_pbkdf2("sha512", 'sb#123', 'iTGGMAbg3FsLgdD6X8u59w, 25000, 64);
As this example shows, both those functions will produce the same output with identical inputs:
$salt = base64_decode("iTGGMAbg3FsLgdD6X8u59w");
$hash1_base64 = base64_encode(hash_pbkdf2("sha512", 'sb#123', $salt, 25000, 64, TRUE));
echo $hash1_base64 . "\n";
$hash2_base64 = base64_encode(openssl_pbkdf2('sb#123', $salt, 64, 25000, "sha512"));
echo $hash2_base64 . "\n";
produces output
LXi2AGKllnsYpfyR0M0aQZTvF2EwhwEI4elKXehjNzy2ZL8Q+w+wceJiIq45PFAjb9QWHmzeQzr3GdZr83qjMA==
LXi2AGKllnsYpfyR0M0aQZTvF2EwhwEI4elKXehjNzy2ZL8Q+w+wceJiIq45PFAjb9QWHmzeQzr3GdZr83qjMA==
which matches the output you have provided.

Replace String with Text

I have a website made by previous developed( Now he is not available ).
I have to access to CMS, payment backend everything, But old developer didnt left any records of database.
I am trying to rename or replace some of the text(company details) in receipt, but I dont know what am i doing wrong.
If I had an access to DB , it would be ease like butter.
Here is what I want to do :
You can see that I tried to include direct text "www.transit.com" , but it didnt show up on receipt .
Instead it showed blank.
I know its pointing to DB name like 'shop_name' and so on. But since I dont have any details on DB , I cant change it from DB.
function setShopData() {
// ショップ情報
$objDb = new SC_Helper_DB_Ex();
$arrInfo = $objDb->sfGetBasisData();
// ショップ名
$this->lfText(125, 60, $arrInfo['shop_name'], 8, 'B');
// URL
$this->lfText(125, 63, $arrInfo['www.transit.com'], 8);
// 会社名
$this->lfText(125, 68, $arrInfo['law_company'], 8);
// 郵便番号
$text = '〒 ' . $arrInfo['law_zip01'] . ' - ' . $arrInfo['law_zip02'];
$this->lfText(125, 71, $text, 8);
// 都道府県+所在地
$text = $this->arrPref[$arrInfo['law_pref']] . $arrInfo['law_addr01'];
$this->lfText(125, 74, $text, 8);
$this->lfText(125, 77, $arrInfo['law_addr02'], 8);
$text = 'TEL: '.$arrInfo['law_tel01'].'-'.$arrInfo['law_tel02'].'-'.$arrInfo['law_tel03'];
//FAX番号が存在する場合、表示する
if (strlen($arrInfo['law_fax01']) > 0) {
$text .= ' FAX: '.$arrInfo['law_fax01'].'-'.$arrInfo['law_fax02'].'-'.$arrInfo['law_fax03'];
}
$this->lfText(125, 80, $text, 8); //TEL・FAX
if (strlen($arrInfo['media-support.transit-grp.com']) > 0) {
$text = 'Email: '.'media-support.transit-grp.com';
$this->lfText(125, 83, $text, 8); //Email
}
So is there anyway I can replace these code, so that it would reflect on receipt?
Thank you
Try:
$this->lfText(125, 63, 'www.transit.com', 8);
You were referring to your array, but it didn't contain that key, you simply wanted to use a hardcoded string instead.
For the email (for instance) do:
$text = 'Email: mycompany#gmail.com';
$this->lfText(125, 83, $text, 8);
I suppose the best option is to replace the value in the array, that way any other places where this name is used will also be replaced.
function setShopData() {
// ショップ情報
// Here is the change:
$arrInfo['shop_name'] = "something else";
$objDb = new SC_Helper_DB_Ex();
$arrInfo = $objDb->sfGetBasisData();
// ショップ名
$this->lfText(125, 60, $arrInfo['shop_name'], 8, 'B');
// URL
$this->lfText(125, 63, $arrInfo['www.transit.com'], 8);
// 会社名
$this->lfText(125, 68, $arrInfo['law_company'], 8);
// 郵便番号
$text = '〒 ' . $arrInfo['law_zip01'] . ' - ' . $arrInfo['law_zip02'];
$this->lfText(125, 71, $text, 8);
// 都道府県+所在地
$text = $this->arrPref[$arrInfo['law_pref']] . $arrInfo['law_addr01'];
$this->lfText(125, 74, $text, 8);
$this->lfText(125, 77, $arrInfo['law_addr02'], 8);
$text = 'TEL: '.$arrInfo['law_tel01'].'-'.$arrInfo['law_tel02'].'-'.$arrInfo['law_tel03'];
//FAX番号が存在する場合、表示する
if (strlen($arrInfo['law_fax01']) > 0) {
$text .= ' FAX: '.$arrInfo['law_fax01'].'-'.$arrInfo['law_fax02'].'-'.$arrInfo['law_fax03'];
}
$this->lfText(125, 80, $text, 8); //TEL・FAX
if (strlen($arrInfo['law_email']) > 0) {
$text = 'Email: '.$arrInfo['law_email'];
$this->lfText(125, 83, $text, 8); //Email
}
One thing that I find odd is function setShopData() { that is usually function setShopData($arrInfo) {.
Since that is missing I assume the array is global and is set somewhere else.
At some point in the code there is a line like:
$arrInfo['shop_name'] =<database value>
If you place the line above in the code just below this any changes in the rest of the code will have the new shopname everywhere, not just on the receipt.

PHP - how to read recursive children of children from XML and display it correctly? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm connecting to a system that is providing me a list of users, the data is to be displayed in a 'tree format' so you can see the parent / child relationships, its almost like a reseller tree..
Cannot work out how to recursively go through the XML, retrieve Parent ID's and record the Child ID records. Problem is some Child IDs can be Parent IDs as well.
I also am not sure how I can directly access a certain UserID from the XML as each record only consists of attributes.
I've uploaded a sample copy of the XML to the following URL :
http://www.fluffyduck.com.au/sampleXML.txt
I'm trying to do this with SimpleXML, however I cannot work out how to loop down through children of children it almost seems like.
Any help appreciated! as this has me completely stumped.
This work and returns an array of 147 SimpleXMLElement (usable like arrays).
$content = file_get_contents('http://www.fluffyduck.com.au/sampleXML.txt');
$xml = new SimpleXMLElement($content);
$users = myUserReader($xml->user);
function myUserReader($node)
{
$users = array ();
$users[] = $node->attributes();
foreach ($node as $user)
{
$users[] = $user->attributes();
if (isset($user->user))
{
$users = array_merge($users, myUserReader($user->user));
}
}
return $users;
}
// displays 147 children
var_dump($users);
// displays 147
echo count($users);
To get an array of parents / children, you may use :
<?php
$content = file_get_contents('http://www.fluffyduck.com.au/sampleXML.txt');
$xml = new SimpleXMLElement($content);
$users = array ();
myUserReader($xml->user, $users);
function myUserReader($node, &$users)
{
if (array_key_exists("{$node['id']}", $users) === false)
{
$users["{$node['id']}"] = array ();
}
if (isset($node->user))
{
for ($key = 0; ($key < $node->user->count()); $key++)
{
$user = $node->user[$key];
if (!in_array("{$node['id']}", $users["{$node['id']}"]))
{
$users["{$node['id']}"][] = "{$user['id']}";
}
myUserReader($user, $users);
}
}
}
foreach ($users as $parent => $children)
{
echo "{$parent}: " . implode(", ", $children) . "\n";
}
?>
This will output :
41: 61, 62, 69, 89, 127, 204, 323, 340, 341
61:
62: 64, 78, 80, 116, 120
64: 66
66: 67
67: 68, 114, 161, 162, 166, 203
68: 70
70: 72, 77, 104, 118, 135, 138, 143, 154, 156, 171, 172, 173, 174
72: 73, 86, 163, 165, 167
73: 75
75:
86: 92, 103, 108, 112, 117, 119, 121, 124, 125, 137, 144
92: 107, 110, 111, 142
107:
110:
111:
142:
103:
108:
112:
117:
119:
121:
124:
125:
137:
144:
163:
165:
167:
77: 79, 113
79:
113:
104: 106
106:
118:
135:
138:
143:
154:
156:
171:
172:
173:
174:
114:
161:
162:
166: 169, 175, 176, 178, 179, 180, 183, 184, 205, 206
169:
175:
176:
178:
179:
180:
183:
184:
205:
206:
203:
78: 136
136:
80: 101
101:
116: 122, 126, 129, 130, 131, 133, 139, 140, 141
122:
126:
129:
130:
131:
133:
139:
140:
141:
120: 145, 146, 147, 148, 149, 150, 151, 157, 160, 168
145:
146:
147:
148:
149:
150: 152, 153, 155, 159
152:
153:
155:
159:
151:
157:
160:
168:
69:
89:
127:
204: 207
207: 208, 209, 210, 211, 212, 227, 254, 300
208: 213, 214, 215, 226, 228, 234, 255, 294, 295, 297, 299, 320
213:
214:
215:
226:
228:
234:
255: 274, 275
274:
275:
294:
295:
297:
299:
320:
209:
210: 217, 218, 222
217:
218:
222:
211:
212:
227:
254:
300:
323:
340:
341:
$xml = new SimpleXMLElement($xml_str);
$user = $xml->user;
while($curr_user = $curr_user->children('user'))
{
// do some code
$attr = array(
$curr_user['id'],
$curr_user['username'],
$curr_user['firstname'],
// ...etc
);
}
So it's only example of usage and finding child nodes. To walk through all array u can user recursive function like this code.
EDIT:
Sry for copying Ninsuo code, but it is perfect one :)
$content = file_get_contents('http://www.fluffyduck.com.au/sampleXML.txt');
$xml = new SimpleXMLElement($content);
$users = myUserReader($xml->user);
function myUserReader($node,$str)
{
$users = array ();
$users[] = $node->attributes();
foreach ($node as $user)
{
$users[] = $user->attributes();
if (isset($user->user))
{
$str .= '<ul>'.$user['fisrt_name'];
$users = array_merge($users, myUserReader($user->user));
$str .= '</ul>';
}
else $str .= '<li>'.$user['fisrt_name'].'</li>';
}
return $users,$str;
}

How to communicate between php and boost library IPC?

I have client and server in php communicating over shared memory, Now I would like to access this shred memory object using Boost.Interprocess how can I access it?
server.php:
function create_image($str){
// Create a blank image and add some text
$im = imagecreatetruecolor(300, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
$stringBanner=exec("date").$str;
imagestring($im, 1, 5, 5, $stringBanner , $text_color);
ob_start();
imagejpeg($im);
$i = ob_get_contents();
ob_get_clean();
imagedestroy($im);
return $i;
}
echo "\n".__FILE__."\n";
$shm_key = ftok(__FILE__, 't');
echo $shm_key."\n";
$shm_id = shmop_open($shm_key, "a", 0, 0);
if ($shm_id) {
//it is already created
shmop_delete($shm_id);
shmop_close($shm_id);
}
//you need to create it with shmop_open using "c" only
echo "try to create\n";
if(!$shm_id = shmop_open($shm_key, "c", 0777, 1024*4))exit(-1);
echo "ID ".$shm_id."\n";
$i=0;
for(;;){
sleep(1);
$s="i=".$i++;
$str=$i;
$im=serialize(create_image($str));
$data=serialize(strlen($im));
$shm_bytes_written = shmop_write($shm_id, $data, 0);
$shm_bytes_written = shmop_write($shm_id, $im, 32);
echo $shm_bytes_written." bytes is written: ".$s." ID = $shm_id\n";
}
client.php
<?php
$shm_key =1946222626;// ftok(__FILE__, 't');
$shm_id = shmop_open(
$shm_key, "a",
0644,1024*4
);
$s=shmop_size($shm_id);
$data = unserialize(
shmop_read( $shm_id, 0,
31)
);
$im = unserialize(
shmop_read( $shm_id, 32,
$data)
);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
echo $im;
What kind of key I should provide to Boost to get this memory region?
boost_client.cpp
#include <boost/interprocess/shared_memory_object.hpp>
#include <iostream>
#include "sys/msg.h"
int main()
{
int msqid;
key_t key;
char f[]="??????";
int mid;
//key = ftok(, 't');
//msqid = msgget(key, 0666 | IPC_CREAT);
std::cout<<msqid<<std::endl;
boost::interprocess::shared_memory_object
shdmem(boost::interprocess::open_or_create,
f,//"shmem_server",
boost::interprocess::read_write);
shdmem.truncate(1024);
std::cout << shdmem.get_name() << std::endl;
boost::interprocess::offset_t size;
if (shdmem.get_size(size))
std::cout << size << std::endl;
}
EDIT:
Well I found the solution in Boost IPC library Docs:
XSI_KEY based example from boost Docs
I'm not an expert in what you're doing, but from what I read in your question and my knowledge, I would drop that pure IPC thing and wrap it into ZMQ (you'll find wrapper in every language you need). It's meant to solve those kind of problems and provide a single API that could run over IPC or more common TCP socket.

Categories