简体   繁体   中英

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;
}

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.

Securing plaintext passwords in MySQL is not a good idea...also why not use SHA1, or MD5 hash...you are going to get more consice responses, then change the algo as you see fit.

Basically

SELECT SHA1("SecretPassword") will = 08cd923367890009657eab812753379bdb321eeb or blabityboo

SHA1 will store to 40 characterse, which means you should probably change your data type from BLOB to varchar, or nvarchar() <---probably varchar...

without the construction of your algorithm we cannot tell how long the field is going to be, hence the remark about padding.

When you select the pass using SELECT CHARACTER_LENGTH("SecretPassword") you will get the length of the encrypted field. and then you can create the appropriate constraints.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM