Orinoco
Orinoco

Reputation: 177

Encrypted data not being inserted into mysql table

I'm trying to upgrade my encryption routines from des to blowfish. I have this function for en/decryption:

function NewCryptStr($EncryptOrDecrypt,$Str)
{
  $Key='test';

  $IVSize=mcrypt_get_iv_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
  $IV=mcrypt_create_iv($IVSize,MCRYPT_RAND);

  if($EncryptOrDecrypt==='Encrypt')
    {
      $Str=mcrypt_encrypt(MCRYPT_BLOWFISH,$Key,$Str,MCRYPT_MODE_ECB,$IV);
      $Str=mysql_real_escape_string($Str);
    }

  if($EncryptOrDecrypt==='Decrypt')
    $Str=mcrypt_decrypt(MCRYPT_BLOWFISH,$Key,$Str,MCRYPT_MODE_ECB,$IV);

  return $Str;
}

This works fine:

$Str='test string to be encrypted then decrypted';
print "<p>Original $Str</p>\n";
$Str=NewCryptStr('Encrypt',$Str);
print "<p>Encrypted $Str</p>\n";
$Str=NewCryptStr('Decrypt',$Str);
print "<p>Decrypted $Str</p>\n";

Then I'm running the following php script on a table of email addresses to convert a column of plain text & update another column with the encrypted result:

$sql="select UID,Str from testdata order by UID";
$result=mysql_query($sql,$Link);

while($row=mysql_fetch_array($result))
  {
    $Encrypted=NewCryptStr('Encrypt',$row[Str]);

    $sql="update testdata set Str2='$Encrypted' where UID=$row[UID]";
    print "<p>$row[Str] > $Encrypted</p>\n";
    print "<p>$sql</p>\n";
    mysql_query($sql,$Link) or die("failed $sql ".mysql_error());
  }

It runs without error & prints out a load of encrypted strings as I'd expect but when I view the data in the table none of the records have been updated with the same data that was printed by the php above. Instead most of the values in Str2 are blank some have 1 or 2 characters in them.

All the sql statements printed look fine, & running them individually updates the record correctly.

The sql tables & the mysql connection are both using utf8 encoding, Str & Str2 columns are varchar datatypes.

Why isn't my table being updated with the correct data?

Edit I have solved (skirted round!) the issue using base encoding/decoding the output/input of NewCryptStr function. I'm still curious to know why my loop through the table wasn't working when the sql statements happily worked when executed individually.

Upvotes: 2

Views: 612

Answers (1)

Tam&#225;s Pap
Tam&#225;s Pap

Reputation: 18303

You have in your code: $row[UID], which is not defined, so no records will be updated.

Change $row[UID] to $row['UID'];

Use:

$sql="UPDATE testdata SET Str2='".$Encrypted."' WHERE UID=".$row['UID'];

Upvotes: 1

Related Questions