PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sat Dec 14, 2019 10:50 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 6 posts ] 
Author Message
PostPosted: Sun Mar 04, 2012 11:05 am 
Offline
Forum Contributor
User avatar

Joined: Mon Jul 26, 2010 1:30 pm
Posts: 174
Location: Florida
Hi All,

I want to include some AES encryption in my self-teaching website, but have run into a problem I can't figure out. The problem is I want to encrypt a text input field (Full Name), have it stored in the db encrypted, but show UN-encrypted on the client side (in the same input field) when I'm looking at the page/entries. In other words, I just wanted it encrypted in the database, but see it in plain text.

The problem is (I believe) that I have an array of inputs and I'm probably not accounting for that. This page I'm learning on is called FRIENDS. I have a dynamic table system that allows me to add a row for every friend I want to store to include address, email, and telephone. I'm just trying to learn with encrypting the name. So far, I can encrypt to the database, but I'm not seeing the output in plain text.

One last thing... I'm not entirely sure I'm encrypting the value entered into each input field separately. I looked at the encrypted entries in the db and they all look the same, which I don't think should be the case. Would be grateful for any help, but please keep in mind I'm just a beginner.

Thank you in advance for any help.

Syntax: [ Download ] [ Hide ]

<?php

if(!isset($_SESSION))
{
session_start();
}

include_once ("../_includes/dbconnect.php");

include('../_classes/padCrypt.php');
include('../_classes/AES_Encryption.php');
include('../_config/key.php');

$AES            = new AES_Encryption($key, $iv);
$encrypted      = $AES->encrypt($txtbox);
$decrypted      = $AES->decrypt($encrypted);

$last_update = date('m-d-Y') ;

if ($_POST['submit'])

{

// ----------------------------------------------------------------------------------------------------------
// Retrieve userid, account, and usertype from user's table and add to friends table
// ----------------------------------------------------------------------------------------------------------

$query =  "SELECT userid, account, usertype, user FROM users WHERE username = '".$requestor."' " ;

$result = mysql_query($query);

if (!$result) die(mysql_error());

        else

{
                       
        $row = mysql_fetch_object($result);

        $userid = $row->userid;
        $account = $row->account;
        $usertype = $row->usertype;
        $user = $row->user;
               
}

// ----------------------------------------------------------------------------------------------------------
// Delete previous entries and submit new ones.
// ----------------------------------------------------------------------------------------------------------

        $q = "Delete FROM friends WHERE username = '".$requestor."' " ;
        $result = mysql_query($q) or die("query: $query<br>" . mysql_error());

        foreach ($_POST['txt'] as $key => $val)
        {              
                if (!empty($val))
                {

                        $txtbox                 = mysql_real_escape_string($_POST['txt']                [$key]);
                        $address                = mysql_real_escape_string($_POST['address']            [$key]);
                        $email          = mysql_real_escape_string($_POST['email']              [$key]);
                        $phone          = mysql_real_escape_string($_POST['phone']              [$key]);
       
                     $fields = "                userid          =       '$userid',
                                                account         =       '$account',
                                                usertype                =       '$usertype',
                                                user                    =       '$user',
                                                name            =       '$encrypted',
                                                address         =       '$address',
                                                email           =       '$email',
                                                phone           =       '$phone',
                                                last_update     =       '$last_update' "
;
                       
                        $sql = "INSERT friends SET ".$fields.", username = '".$requestor."' " ;
                        mysql_query($sql,$con) or die("query: $query<br>" . mysql_error());
                }
        }
}

$txtbox = $address = $email = $phone = array();

// Default number of empty dynamic table Rows on the form & set variables

for ($i = 0; $i < 6; $i++)
               
        {
                $txtbox[$i]     = "";
                $address[$i]    = "";
                $email[$i]      = "";
                $phone[$i]      = "";
        }

$query =  "SELECT name, address, email, phone, last_update FROM friends WHERE username = '".$requestor."' " ;

$result = mysql_query($query);

if (!$result) die(mysql_error());

else

{

$i = 0;

        while ($row = mysql_fetch_object($result))

        {
        $txtbox[$i]     = $row->name;
        $address[$i]    = $row->address;
        $email[$i]              = $row->email;
        $phone[$i]              = $row->phone;
        $last_update    = $row->last_update;
        $i++;
        }
        mysql_free_result($result);
}
       
?>

 


Top
 Profile  
 
PostPosted: Fri Mar 23, 2012 4:42 pm 
Offline
Forum Contributor
User avatar

Joined: Wed Apr 14, 2010 4:45 pm
Posts: 375
Location: UK
Hi,

If possible, you should use the mcrypt library to do this - I had a problem a while ago whereby a server I was working on didn't (and couldn't) have mcrypt installed on it, so I had to find an open source library that implemented the AES specification. I found two different libraries but the results from one of them didn't match the other, which meant that one of the developers hadn't designed their encryption/decryption routines correctly. I later compared the outputs to the mcrypt library, which confirmed my suspicions about one of them.

You're better off encrypting/decryption everything at the script level and just using the database to store the data (in BINARY field format). I originally tried using MySQL to encrypt data and mcrypt to decrypt it but ran into more problems - which isn't much fun when you have a deadline approaching! :mrgreen:

To give you a very quick overview:

1. Save the values from your form into a variable.
2. Encrypt this value using mcrypt. At this point the value that gets returned is in binary format.
3. Use mysql_real_escape_string to encode the value so that it's ready to use in a database query.
4. Run your INSERT query to store the encrypted text in the database.

When you want to retrieve this you then need to do as follows:

1. Retrieve your value from the database.
2. Decrypt it using mcrypt. At this point the value is in plain text format again and viewable.

To answer one of your other questions, encrypted data will look different provided that the information and/or the key is different.

If you need any more help please say so. You can also use the openssl functions in PHP as well if you want - you can use phpinfo() to check what you have installed on your server, but mcrypt is the one to use for AES encryption/decryption.

Mecha Godzilla


Top
 Profile  
 
PostPosted: Sat Mar 24, 2012 7:36 am 
Offline
Forum Contributor
User avatar

Joined: Mon Jul 26, 2010 1:30 pm
Posts: 174
Location: Florida
Thank you very much for the detailed reply. I wish you had seen my posting a lot sooner, but better late than never! :) I ultimately came up with a solution after a lot of search and testing, which I'm going to post here in hopes it might help someone else with a quick fix. Just remember, security is a complicated subject and I'm only a beginner, so this code - although working - might not be the best solution for everyone depending on their security requirement.

Syntax: [ Download ] [ Hide ]
<?
function encrypt($skey, $plain_text) {
       
  $skey = "$3cr3tk3yw0rd3$p3ci4lly4u";  //
 
  $plain_text = trim($plain_text);
 
  $iv = substr(md5($skey), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  $c_t = mcrypt_cfb (MCRYPT_CAST_256, $skey, $plain_text, MCRYPT_ENCRYPT, $iv);
 
  return trim(chop(base64_encode($c_t)));

}

function decrypt($skey, $c_t) {

  $skey = "$3cr3tk3yw0rd3$p3ci4lly4u";  //
 
  $c_t =  trim(chop(base64_decode($c_t)));
 
  $iv = substr(md5($skey), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  $p_t = mcrypt_cfb (MCRYPT_CAST_256, $skey, $c_t, MCRYPT_DECRYPT, $iv);
 
  return trim(chop($p_t));
}
?>
 


I saved this code above in my _includes/_skey.php file and made sure I had: include_once ("../_includes/_skey.php"); at the top of the page. For noobs like myself, you can change the location and name of this file, but be sure to account for it in the next bit of code I'm going to give you.

Syntax: [ Download ] [ Hide ]
$encrypted = encrypt($skey,$account_number);
 


Above is how to encrypt 1 variable that's being inserted into the database. In my case, I was encrypting the $account_number being stored in db. If you were encrypting more fields, you could add a line for each variable and just replace $account_number with the next variable you're wanting to encrypt.

Syntax: [ Download ] [ Hide ]
$fields = "userid                       =       '$userid',
               account          =       '$account',
               usertype         =       '$usertype',
               user                     =       '$user',
               name                     =       '$name',
               asset                    =       '$asset',
               address          =       '$address',
               account_number   =       '$encrypted',
               phone                    =       '$phone',
               bill_date                =       '$bill_date' "
;
       
                        $sql = "INSERT creditors SET ".$fields.", username = '".$requestor."' " ;
                        mysql_query($sql,$con) or die("query: $query<br>" . mysql_error());
 


Above is NOT part of the encryption code, but I did want to show you how I added $encrypted with/for account_number to my INSERT command. Don't forget to do that, so the entry is encrypted when being stored to the database.

Syntax: [ Download ] [ Hide ]
while ($row = mysql_fetch_object($result))

        {
                $decrypted=decrypt($skey,$row->account_number);
               
                $name[$i]               = $row->name;
                $asset[$i]                      = $row->asset;
                $address[$i]            = $row->address;
                $account_number[$i]     = $decrypted;
                $phone[$i]                      = $row->phone;
                $bill_date[$i]          = $row->bill_date;
                $i++;
        }
                mysql_free_result($result);
 


Finally, above is how how I first put the decrypt code at the top and then told it what to decrypt and where to put the decrypted text in my query. I left some of the query code out, but only because it was just a standard query I was using. In my case, I placed the initial decrypt code where I did because I was running a loop. Your placement may vary.

Hope it helps.


Top
 Profile  
 
PostPosted: Mon Mar 26, 2012 7:38 am 
Offline
DevNet Resident
User avatar

Joined: Sun Sep 03, 2006 5:19 am
Posts: 1579
Location: Sofia, Bulgaria
The IV is supposed to be a cryptograpically random block, not dependent on the key.

It also looks like you have SQL injection problems during insert (and I don't see where $requestor comes from, but it should be escaped as well)


Top
 Profile  
 
PostPosted: Mon Mar 26, 2012 4:50 pm 
Offline
Forum Contributor
User avatar

Joined: Wed Apr 14, 2010 4:45 pm
Posts: 375
Location: UK
You might want to look at generating a PBKDF2 key for the initialisation vector - some example code can be found here:



In my scripts I generate random values for the password and salt as well - I'm not sure whether this is necessarily correct, but I use the following code to do this:

Syntax: [ Download ] [ Hide ]
function generate_pseudorandom_value() {
    $pseudorandom_file_hander = @fopen('/dev/urandom','rb');
    if ($pseudorandom_file_hander !== FALSE) {
        $pseudorandom_value = @fread($pseudorandom_file_hander,16);
        @fclose($pseudorandom_file_hander);
    }
    return $pseudorandom_value;
}


Note that this only works on Un*x/Linux systems - if you don't understand what this code is supposed to do please say so.

With regard to the other poster's comments about SQL injection - if you're receiving $_GET or $_POST values from the user then you should use mysql_real_escape_string() before inserting these values into your database query strings. There is lots of information about this on this forum and the 'Net generally, but if you have any questions please say so.

HTH,

M_G


Top
 Profile  
 
PostPosted: Tue Mar 27, 2012 1:46 am 
Offline
DevNet Resident
User avatar

Joined: Sun Sep 03, 2006 5:19 am
Posts: 1579
Location: Sofia, Bulgaria


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 6 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group