Anyway, this site will be viewed and used by colleges throughout the US. It will be a place for students and teachers to
share files and collaborate on said project.
I thought I might need to include some security with this. Just a thought.
I needed a way to encrypt data for storage and then decrypt it for readability.
I looked at PHPs mcrypt, but I had a problem with it: It wasn't core. I had absolutely no idea what my or any other college was going to do with or where they were going to put it this once it was done, so I need the whole thing to be as flexible and ready-to-go as possible.
So I looked at base_64 - too easy to just rewash through the decode.
I finally found, on another forum, a set of functions that pretty much solved my problem. encrypt($string, $key) and decrypt($string, $key)
Well, I wanted one solid key for this, so I simply hard-coded it into another require()d page (this other page checks to see if the server's name is on a whitelist and connects to the DB if it is)
Still wasn't good enough. I'm going to potentially be dealing with everyone in the US (and I guarantee a whole bunch of security experts are going to run through my code before it goes live). I needed a salt, but I didn't want to have to type in a salt every single time I wanted to run the function. In essence, I wanted an encrypt($string) and a decrypt($string) which I pretty much achieved by having a "master" password. The point of this encryption is the encrypted data is stored in the database so in case the DB is compromised, all the attacker will get is a bunch of who knows what.
I edited and re-edited and finally came up with this:
Code: Select all
function encrypt($string, $key){
$result = "";
for($i=0; $i<strlen($string); $i++){
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
$salt_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxys0123456789~!@#$^&*()_+`-={}|:<>?[]\;',./";
$length = rand(1, 15);
$salt = "";
for($i=0; $i<=$length; $i++){
$salt .= substr($salt_string, rand(0, strlen($salt_string)), 1);
}
$salt_length = strlen($salt);
$end_length = strlen(strval($salt_length));
return base64_encode($result.$salt.$salt_length.$end_length);
}
function decrypt($string, $key){
$result = "";
$string = base64_decode($string);
$end_length = intval(substr($string, -1, 1));
$string = substr($string, 0, -1);
$salt_length = intval(substr($string, $end_length*-1, $end_length));
$string = substr($string, 0, $end_length*-1+$salt_length*-1);
for($i=0; $i<strlen($string); $i++){
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}So my question is this: Is this secure enough for a database? I will use this on top of an md5() for passwords