base64_encode weird behavior - php

I'm doing something like the following:
SELECT * FROM table WHERE user='$user';
$myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R=
$somepass = base64_encode($_POST['password']);
if($myrow[1] != $somepass) echo 'error';
else echo 'welcome';
Im always getting error, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks

Try using var_dump instead of echo - maybe one of them has a space or newline at the start/end.
Edit:
You must be storing it as CHAR(40): A fixed-length string that is always right-padded with spaces to the specified length when stored
Use VARCHAR or trim()

If $myrow[1] is actually the correct password in base64-encoding, I don't see any errors.
Try this ind the end:
echo "<br />$myrow[1] != $somepass";
What does it say?
And by the way: I don't see any reason to base64-encode the passwords. What are you trying to accomplish?

I think somehow if I do a var_dump() I get:
string(40) "YWRraM2= "
string(8) "YWRraM2="
seems like somehow if I insert the data into the db using the console its adding an extra space to the pass field.
myplacedk: is there any reason why I should not be doing it? I thought it will add an extra leyer of security?

This encoding does two things:
It adds code, making it more complex and easier to make errors
If you view your database on your screen, and someone looks over your shoulder, the passwords may be a bit harder to remember.
So no, it doesn't really add any security. It's just an encoding, it's easy to decode.
Maybe you are mistaking it for md5-hashing or something like that.
Playing around is great, but when it comes to security, I really recommend not using something you don't understand. In the long run, it will do more damage than good.

Some issues:
From your comments elsewhere, I guess that the problem with the current code is that your database field is CHAR(40). A CHAR field always has a fixed size. Try changing the database field type to VARCHAR instead of CHAR.
Using base64_encode before storing in a database is nowhere near secure. Good practice is storing only a one-way hash of the password in the database -- typically md5 or (better) sha1. Then, when the user wants to log in, use the same hash-function on the provided password, and then compare the two hashes.
This has the added benefit of working with passwords longer than 40 characters too.
A sha1 or md5-hash always takes a fixed amount of space, so if you go this route, you don't have to switch your database column to VARCHAR :)

Related

PHP making a string useable but not readable

So I am not sure if this is possible,but here we go. I want to be able to create a string that functions as normal ,but is not readable. For example:
$password = "//312(!##()";
then I could go something like.
if($input == $password) {
}
Is there anyway I can possibly do this? I may be talking through a hole in my head, but any help on the subject would help.
You can hash the String:
$pw_hash = "098f6bcd4621d373cade4e832627b4f6" //is the hash of "test"
if ($pw_hash == md5($variable)){
//now you know, the variable is "test",
//without writing it plaintext in the sourcecode.
}
But search for hashes. There are better options than md5. Also google for "salt" and get aware of what's the difference between "hashing" and "encrypting".
From your comments, I believe that you want to hide your php source code when deploy the application. I see many developer usually use the base64_encode encode the original PHP code to be a single string and use eval(base64_decode($str)) in their deployed package.
However, that way can only useful with normal user, we can always use an online tool like http://perishablepress.com/tools/decoder/ (or write your own function) to get the original source :)

Storing PHP snippets in MySQL

I am storing PHP snippets in a MySQL database, I am using mysql_real_escape_string and all is well unless there is a & in the php code and then I get a MySQL error. Is there another why I should try and store this information?
Thanks
#Peter : unless you're building a website for helping developers, you have no reason to put php code into your database, it's a warning : this is gonna be a big nightmare to maintain/debug. Can't you link your pages to some parameters and then in your code use these parameters to build each request ?
it may seems a simple design solution at the beginning "how god I can do whatever I want in all my pages" but it might be the worse you're taking on your poject.
I don't know how to say this but you should really try to consider an other solution. And i'm not speaing about security : if you have an SQL Injection the guy can execute SQL AND php so he can really take all your system/server down, or even attack bigger site with yours (and then you'll be responsible).
I'm really surprised everyone is fine with it.
Use base64_encode when you save snippet into the database and base64_decode when you retreive it.
First, I am going to go on record and say I wholeheartedly agree with remi bourgarel. This is likely a bad idea.
But, from a technical standpoint here's how I'd do this IF I NEEDED TO:
$php_code = '
<?php
$var = "this is a string";
$var = strtoupper($var);
echo $var;
?>
';
$php_code = bin2hex($php_code);
$db->query("INSERT INTO php_code_snips (text_code) VALUES(x'{$php_code}')");
bin2hex will transform the string $php_code from a binary string to a hex string, and the x'{$php_code}' tells mysql to expect a hex string.
This means the string is stored as a string in the DB, and is fully searchable. But, since all chars are encoded as hex during the INSERT the special chars won't cause a problem.
Documentation:
bin2hex
Mysql Hex Values

What are the necessary and most important things, we should do at validation, if an web application gets the users input or parameters?

I am always thinking about validation in any kind on the webpage (PHP or ASP, it doesn't matter), but never find a good and accurate answer.
For example, a I have some GET-Parameter, which defines a SQL query like DESC oder ASC. (SQL-Injection?)
Or I have a comment-function for user, where the data is also saved in a database.
Is it enought to check for HTML-tags inside the data? Should the validation done before adding it to the database or showing it on the page?
I am searching for the ToDo's which should be always performed with any data given from "outside".
Thanks.
Have a good idea of what you want from the user.
You want them to specify ascending/descending order? That's an enumeration (or a boolean), not part of an SQL query:
$query = "SELECT [...] ORDER BY field " . escape($_GET['sortOrder']); //wrong
This is wrong no matter how much you escape and sanitize their string, because this is not the way to validate an enumeration. Compare:
if ($_GET['sortOrder'] == 'desc') {
$ascending = false;
} else {
$ascending = true;
}
if ($ascending) {
...
} else {
...
}
...which does not warrant a discussion of string escaping or SQL injection because all you want from the user is a yes/no (or ascending/descending) answer.
You want them to enter a comment? Why disallow HTML tags? What if the user wants to enter HTML code?
Again, what you want from them is, say, "a text... any text with a maximum length of 1024 characters*." What does this have to do with SQL or injection? Nothing:
$text = $_POST['commentText'];
if (mb_strlen($text, ENCODING) <= 1024) {
//valid!
}
The value in the database should reflect what the user entered verbatim; not translated, not escaped. Say you're stripping all HTML <tags> from the comment. What happens when you decide to send comments somewhere in JSON format? Do you strip JSON control characters as well? What about some other format? What happens if HTML introduces a tag called ":)"? Do you go around in your database stripping off smileys from all comments?
The answer is no, as you don't want HTML-safe, JSON-safe, some-weird-format-with-smileys-safe input from the user. You want text that is at maximum 1024 characters. Check for that. Store that.
Now, the displaying part is trickier. In order to display:
<b>I like HTML "tags"
in HTML, you need to write something like:
<b>I like HTML "tags"
In JSON, you would do:
{ "I like HTML \"tags\" }
That is why you should use your language facilities to escape the data when you're using it.
The same of course goes for SQL, which is why you should escape the data when using simple query functions like mysql_query() in PHP. (Parametrized queries, which you should really be using, on the other hand, need no escaping.)
Summary
Have a really good idea of what you want as the input, keeping in mind that you almost never need, say, "HTML-safe text." Validate against that. Escape when required, meaning escape HTML as you send to the browser, SQL as you send to the database, and so on.
*: You should also define what a "character" means here. UTF-8, for example, may use multiple bytes to encode a code point. Does "character" mean "byte" or "Unicode code point"?
If you're using PDO, be sure to use prepared statements - these clean the incoming data automatically.
If using the mysql_* functions, run each variable through mysql_real_escape_string first.
You can also do validation such as making sure the variable is one of an acceptable range:
$allowed_values = array('name', 'date', 'last_login')
if(in_array($v, $allowed_values)) {
// now we can use the variable
}
You are talking about two kinds of data sanitation. One is about putting user-generated data in your database and the other is about putting user-generated data on your webpage. For the former you should follow adam's suggestions. For the later you should look into htmlspecialchars.
Do not mix these two as they do two completely different things. For that purpose sanitation should only take place at the last moment. Use adam's suggestion just before updating the database. Use htmlspecialchars just before echoing data. Do not use htmlspecialchars on data before adding it to the database.
You might also want to look around Stackoverflow, because this sort of question has been asked and answered countless times in the past.

is there a way to compress a GET string so it won't be so long?

I need to compress a string so it is shorter for a GET method form. Is there any way to compress a string and it will be decrypted later? That way...
?error=LOTS OF STUFFLOTS OF STUFFLOTS OF STUFFLOTS OF STUFFLOTS OF STUFF
is shorter in some sort of key
?error=somekey
so I can get back the result later. Not using MySQL preferably.
Anyone know a good method for this?
Update: To clarify, I am using a GET because this is a cross site include and a POST will not be accepted into the variable scope of the HTTP included file.
If you're using PHP, the easiest way to send an error message is with the $_SESSION. Simply say session_start(); at the top of the pages, and say $_SESSION['error'] = "TEXT";. Then isset($_SESSION['error']);.
Of course, you could always use $_POST.
I'd use POST instead... Or, come up with your own key mapping (error=1 would map to a long wordy error - like Col. Shrapnel's example).
You could also use a hash table. http://en.wikipedia.org/wiki/Hash_function
Easiest way to make your GET string shorter. Use POST.
(Update: Again, if you control how the form is sent, use POST. Use it. Don't use GET. To be clear, if you can use POST.)
But perhpas you need to pass this data as a regular old link. In that case I guess you could try php's compression functions. Some of the operate directly on strings.
For example, gzcompress() and gzuncompress() could be used to compress/uncompress a string. From the php manual:
<?php
$compressed = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>
Of course you'll have to run it through urlencode() and urldecode() - which since I'm sure the compression algorithms will output binary data, may not really save you anything.
Or it may not work at all. Would be interesting to try.
Update: Tested, it's crazy, but it did make your example string smaller.
Not really 'on-the-fly', You might be able to Gzip and then base64 encode, (but base64 encoding increases the size, I just don't know how much)
But really, if you are exceeding the GET size, you should probably just switch to POST.

Converting an input text value to a decimal number

I'm trying to work with decimal data in my PHP and MySql practice and I'm not sure about how can I do for an acceptable level af accuracy.
I've wrote a simple function which recives my input text value and converts it to a decimal number ready to be stored in the database.
<?php
function unit ($value, $decimal_point = 2) {
return number_format (str_replace (",", ".", strip_tags (trim ($value))), $decimal_point);
}
?>
I've resolved something like AbdlBsF5%?nl with some jQuery code for replace and some regex to keep only numbers, dots and commas.
In some country, people uses the comma , to send decimal numbers, so a number like 72.08 is wrote like 72,08. I'd like avoid to forcing people to change their usual chars and I've decided to use a jQuery to keep this too.
Now every web developer knows the last validation must be handled by the dynamic page for security reasons.
So my answer is should I use something like unit (); function to store data or should I also check if users inserts invalid chars like letters or something else? If I try this and send letters, the query works without save the invalid data, I think this isn't bad, but I could easily be wrong because I'm a rookie.
What kind of method should I use for my query if I want a number like 99999.99?
don't forget to consider formatting also DATABASE values with something like FLOAT(10,2)
IMHO this is also very important!
then, of course use server side language for make real validation is the best practice!
you can read this:
http://php.net/manual/en/function.number-format.php
javascript can be fancy and handy but not secure although!

Categories