CakePHP rijndael cipher puts an empty string in the database - php

I have a string I want to save into my DB in an encrypted format. I am using the security utility provided by cake so this is the code I use to encrypt my sensitive data:
// get my encryption key
$encrypt_key = Configure::read('Secret.encrypt_key');
// encrpyt this string to be stored in the database
$this->request->data['User']['message'] = Security::rijndael($this->request->data['User']['message'], $encrypt_key, 'encrypt');
// save this user data
$user_saved = $this->User->save( $this->request->data[ 'User' ] );
This looks like ever guide I have seen for how to do this, but in my case all of the other fields will save and I will get an empty field for message
My question is why is this blank database save happening and how do I fix it. Thank you.

The problem ended up being that the rjindeal function returns a raw binary string 010100100010100101111101010010101 that my database cannot handle. By simply converting the result to hex code via bin2hex($encrypted_message) the data is transformed into a form that my database can handle.

Related

How to view a tinyblob object

I'm currently working with an existing database that is Mysql, and the system is built in php.
For whatever reason the builder of this system chose to store some parts of the data in blobs. One of them is a tiny blob.
In the database one of the records appears like this:
a:2:{i:0;s:3:"130";i:1;s:3:"182";}
This is viewable from the sql client I'm using. It says it's a TINYBLOB(255).
I need to be able to figure out the correct structure used to set this up so that I could build my part.
It appears to me as if I'm not seeing a "true" representation of what the data structure is.
I ran this on the php side:
public function types_get() {
$returnedTypes = $this->api->getReportTypes();
echo($returnedTypes);
$this->response($returnedTypes,REST_Controller::HTTP_OK);
}
It also produced this on the echo and response: a:2:{i:0;s:3:"130";i:1;s:3:"182";}
How would I be able to make it so I can see the true data as if it was a json string?
This data string has been created with the serialize() function. You can convert it back to a native array with the matching unserialize() function:
$string = 'a:2:{i:0;s:3:"130";i:1;s:3:"182";}';
$data = unserialize($string);
print_r($data);
Output:
Array(
[0] = 130
[1] = 182
)

php unserialize returns false

I have the following problem. I am retrieving a mysql text field that is a serialized text of a invoice. I am working in 2 different projects. Both have the same version of PHP. The data was exported & imported from db to db. If i var_dump the data from db1 it tells me it's length is x. When I do the same in from db2 i get x+2
string(595)
"a:3:{s:11:"userdetails";a:20:{s:4:"name";s:3:"bas";s:8:"lastname";s:7:"schmitz";s:5:"email";s:17:"email#test.de";s:6:"street";s:11:"f�rstenwall";s:7:"street2";s:0:"";s:7:"company";s:0:"";s:3:"zip";s:5:"40215";s:9:"residence";s:10:"d�sseldorf";s:7:"country";s:7:"Germany";s:5:"phone";s:7:"3033185";s:3:"fax";s:0:"";s:10:"customerID";i:202771;s:2:"nr";s:3:"228";s:6:"region";s:3:"nrw";s:10:"phone_code";s:3:"211";s:8:"fax_code";s:0:"";s:10:"salutation";s:2:"Mr";s:5:"sales";s:0:"";s:12:"country_code";s:0:"";s:10:"vat_number";s:0:"";}s:6:"domain";s:15:"bas-schmitz2.de";s:10:"has_domain";b:1;}"
string(597)
"a:3:{s:11:"userdetails";a:20:{s:4:"name";s:3:"bas";s:8:"lastname";s:7:"schmitz";s:5:"email";s:17:"email#test.de";s:6:"street";s:11:"fürstenwall";s:7:"street2";s:0:"";s:7:"company";s:0:"";s:3:"zip";s:5:"40215";s:9:"residence";s:10:"düsseldorf";s:7:"country";s:7:"Germany";s:5:"phone";s:7:"3033185";s:3:"fax";s:0:"";s:10:"customerID";i:202771;s:2:"nr";s:3:"228";s:6:"region";s:3:"nrw";s:10:"phone_code";s:3:"211";s:8:"fax_code";s:0:"";s:10:"salutation";s:2:"Mr";s:5:"sales";s:0:"";s:12:"country_code";s:0:"";s:10:"vat_number";s:0:"";}s:6:"domain";s:15:"bas-schmitz2.de";s:10:"has_domain";b:1;}"
As I am pasting these I can see that there is a difference when displaying germanic characters
Any idea to why this is happening?
The output of serialize() cannot be handled as plain text:
Return Values
Returns a string containing a byte-stream representation of value that
can be stored anywhere.
Note that this is a binary string which may include null bytes, and
needs to be stored and handled as such. For example, serialize()
output should generally be stored in a BLOB field in a database,
rather than a CHAR or TEXT field.
Thus your data is corrupted in the first place.
If you're unable to change the database design (which would be the proper fix), you need to re-encode serialised data in a plain text encoding such as Base64:
$encoded = base64_encode(serialize($foo));
$decoded = unserialize(base64_decode($encoded));

Laravel - using a postgre bytea blob field

I am using PostgreSQL on a Laravel installation. A table has a bytea type field which is being used to store binary data (base64_encoded file contents).
When I use Eloquent to retrieve the table I get a resource type variable being returned in this field.
How can I rather retrieve this as a string?
$raw = Media::where('id','=',$id)->first();
$raw->file_data = base64_decode($raw->file_data); // doesn't work
As the author of this question did not post the details to the answer, I will post my findings here.
As the returned field is a handle to a stream you can use the stream_get_contents function to read the value into a string, you can then use pg_unescape_bytea to get the actual value of the bytea data. Finally use the htmlspecialchars function if you wish to display the bytea data in HTML.
Example code:
$my_bytea = stream_get_contents($resource);
$my_string = pg_unescape_bytea($my_bytea);
$html_data = htmlspecialchars($my_string);
The answer was to use stream_get_contents on the stream. duh.

Reverse obfuscating plain text string urls in PHP

I'm trying to figure out a way to program a function that will de-obfuscate a plain text url.
Something like this:
<input type="hidden" value="kjgajkwe##jktGAkjgWjkajskd" name="obsfucatedString" />
Then in the processing of that form I want to De-Obsfucate it:
$url = deObfuscate($_POST['obsfucatedString']);
so $url would become something like:
$url = 'http://domain.com/filename.zip';
Is something like that even possible?
I'm trying to hide the url from plain programmer sight.
I guess I would need to write something that would obsfucate the string as well
so
$obsfucatedStringURL = obsfucate('http://domain.com/filename.zip');
Encrypt the URL with a password stored on the server (a good algorithm to use is AES), then decrypt it when you need to obtain the value. A problem with this is that the encrypted string will not be composed of printable characters. To get around this, use base64_encode() to convert the binary encoded string to printable characters that can be added as a value in the <input> field, then use base64_decode() to get back the original value on the server.
There are many ways of encoding and reversing a plain text string. An simple way to obfuscate your string is by using the str_rot13 function once to encode and once again to decode (note: this will not give you any cryptographic security). I'd suggest encrypting using AES using a secret stored on the server to encrypt and decrypt. The following thread's answer defines functions for encrypting/decrypting that you can use.
PHP AES encrypt / decrypt
Another approach that might be worth considering vs. obfuscation is to store the URL server side as part of the user's session or persisted in a database. Then instead of sending an obfuscated string down, use a key that performs a lookup to retrieve the URL.

PHP MYSQL file contents escape problem

I am attempting to upload a .pdf file into a mysql database using php.
It is all good except for the contents of the file. No matter how I seem try to escape special characters, the query always fails, mostly with "Unknown Command \n".
I have used addslashes, mysql_real_escape_string, removeslashes etc.
Does anyone have any ideas on how to escape file contents?
Many Thanks,
I don't see why you would want to store a file in a database, but I suggest you take a look at prepared statements.
I've used the following sequence before, which seems to work nicely, and will store any data into the db, including images, pdfs, arrays of data, etc... :)
Storing the data (can be a string, array, object, etc.);
First, turn the data into a base64 encoded string
$strData = strtr(
base64_encode(
addslashes(
gzcompress( serialize($dataToStore) , 9)
)
) , '+/=', '-_,');
Then store that string data in the db...
Retrieving the data;
Extract the string data from the db
decode the data back to what you want (you may need to perform an extra step after this depending on the input data, array, image, etc.)
$returnData = unserialize(
gzuncompress(
stripslashes(
base64_decode(
strtr($strDataFromDb, '-_,', '+/=')
)
)
)
);
This certainly helped me to store what I needed to store in a mySQL db!
Guess: You may be encountering errors due to the incompatibility between character sets. PDF is probably a binary file so you need to make sure that db column is set up to handle it that.
Beside the escaping problem you might run into "packet too large" errors if the (MySQL) system variable max_allowed_packet is set to a "small" value.
Using the mysqli extension, prepared statements and mysqli_stmt::send_long_data you can avoid both problems.

Categories