views:

64

answers:

1

I've been stuck trying to arrive at a best solution for this for a while. I know that an initialization vector has to be unique for each item being encrypted. So if I'm encrypting an address and I have it stored all in a single field, I need a single iv for this. But if I have the address spread over multiple fields, I need several ivs, one for each field. This is a problem.

Is there a way to encrypt multiple fields (all in the same row/record) with a single iv, while maintaining the individuality of the fields? The goal is to have a single iv per record.

What I was thinking about doing was something like this

//get input for fields 1-5

//encrypt them, so that each one has its iv appended to it
$field1_enc = encr($field1);
$field2_enc = encr($field2);
$field3_enc = encr($field3);
$field4_enc = encr($field4);
$field5_enc = encr($field5);

//then store them individually in the database

How do I encrypt all fields with a single key? Then what happens when I want to edit any of those fields? (my guess is I'd have to un-ecrypt, then re-encrypt with a new iv). But the main question is aside from the concept, I don't understand how to programmatically get this done, i.e. encrypting all fields with a single iv

+2  A: 

IV needs to be unique but doesn't have to unpredictable or secret. Why don't you create a random number as base of IV for each record. Adding 1 to the base and use it as IV for field 1, adding 2 for field 2 ...

EDIT: Here are some implementation details,

Create a column for iv_base, which is simply a random number,

$iv_base = random();

When you encryt or decrypt the fields, use this function to create IV,

function get_iv($base, $size, $seq) {
    $remaining = $size;
    $round = 0;
    $iv = '';
    while ($remaining != 0) {
        $d = md5($base . $seq . $round, true);
        $len = min($remaining, 16);
        $iv .= substr($d, 0, $len);
        $remaining -= $len;
        $round++;
    }
    return $iv;
}

$base is the random number you stored in the database. $size is the IV size. $seq is the number you assigned for each field. You can use field name also.

ZZ Coder
Good point. But what do you mean by adding 1, 2, 3, etc.? The iv generated is a base64 encoded string. It was initially generated from MCRYPT_DEV_RANDOM, then passed to `mcrypt_enc_get_iv_size` to get the right size for this cipher, then passed to `mcrypt_create_iv`, then the base64 encoding that yielded something like this `Vi6emRmemexY=` So if I consider that my base, how am I supposed to **add** 1,2,3,etc. I don't suppose you mean simple concatenation, because that won't produce a matching `mcrypt_enc_get_iv_size` when decoded. Please clarify :)
Chris
See my edits ........................
ZZ Coder
I saw it now, will give it a try and get back
Chris