Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling to store encrypted info in database field

I'm having huge problems storing encrypted info in a mysql database, engine mySam

I encrypt the info like this:

function in($plaintext) {
 $cipher = 'rijndael-256';
 $mode = 'cbc';
 $key = 'key';

    $td = mcrypt_module_open($cipher, '', $mode, '');
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $crypttext = mcrypt_generic($td, $plaintext);
    mcrypt_generic_deinit($td);
    return $iv.$crypttext;
}

The data is then stored in a blob. When i come to derypt the info it appears that around 10% of the time it has been corrupted due to storage in the database.

I can verify it the database is the problem as i have run scripts to mass encrypt and decrypt the data without issues.

Any ideas? Thanks in advance...

[edit decryption routine]

function decrypt($crypttext)
{   
 $cipher = 'rijndael-256';
 $mode = 'cbc';
 $key = '$key';

    $plaintext = ''; 
    $td        = mcrypt_module_open($cipher, '', $mode, '');
    $ivsize    = mcrypt_enc_get_iv_size($td);
    $iv        = substr($crypttext, 0, $ivsize);
    $crypttext = substr($crypttext, $ivsize);
    if ($iv)
    {   
        mcrypt_generic_init($td, $key, $iv);
        $plaintext = mdecrypt_generic($td, $crypttext);
    }   
    return $plaintext;
}
like image 543
rix Avatar asked May 16 '12 16:05

rix


1 Answers

i highly doubt you've come across a mysql database bug... "corrupted" how? Can we see your decryption routine and test script? It's not just block-size padding you've run into?

Padding: crypt algos generally work on blocks of data (aes using 128 bits) - input (and thus output!) data will be padded to this length, and you need to store the entire padded output string - and possibly the length of you non-padded input, if your input data is pf a form where padding can't be determined & removed automatically after decryption.

like image 65
snemarch Avatar answered Oct 29 '22 22:10

snemarch