views:

111

answers:

3

Hello,

I was attempting to encrypt de cookie data with md5, but I can not validate the hash back.

It has got to do, with the fact that cookie_data is a serialized array, because normal stringvalues work ok.

It's actually from a codeigniter class, but it does not work?? Does anyone know what the problem might be?

$hash    = substr($session, strlen($session)-32); 
$session= substr($session, 0, strlen($session)-32); 

if ($hash !==  md5($session.$this->encrypt_key))
{........

and the cookie value is encrypted like this

$cookie_data = $cookie_data.md5($cookie_data.$this->encrypt_key);

EDIT I found that the answer is to use urlencode en urldecode in the proces of creating and validate md5 hashes, because setcookie does urlencode automaticly, and thereby possibly changing the hash.

thanks, Richard

+4  A: 

You have a typo:

md5($sessie.$this->encrypt_key))

should be

md5($session.$this->encrypt_key))

If you develop with notices turned on you'll catch this kind of thing much more easily.

You're not encrypting your data, you're signing it.

Greg
sorry, it's actually my translation for this forum, excuse
Richard
+1  A: 

I was attempting to encrypt de cookie data with md5, but I can not decrypt it back for validation.

md5 isnt an encryption method. it creates a one-way hash that cant be turned back into the original data.

If you want to encrypt data try mcrypt

Galen
He uses MD5 only for message authentication.
Gumbo
+2  A: 

md5 is a oneway function. It is not a reversible one, so you can't decrypt the data.

The only thing you can do is encrypt the original data (if you saved it elsewhere) and check the result of this second computation.

If the value retrieved and the new value calculated are the same, the hash you received is valid (As you are doing in your code).

EDIT

You know, with just three lines of code I will guess some possible causes:

  1. $session doesn't contains at the beginning of your code the same value of cookie_data.
  2. you are using multibyte strings and strlen is not mb aware (use the idioms substr($session,0,-32) to get the payload part of the string.
  3. maybe substr doesn't cope with multibyte strings too, use explicitally mb_substr (or whatever it is called).

To me the first case is the more probable. For what I can see.

Eineki
ok, I used the wrong words, but it's from the CI framework,Why won't it work?
Richard
Added some other suggestion to the answer (too text for the comments)
Eineki
thanks, to me the first one does not seem obvious.It receives the cookiedata as a serialized array and concats it with the md5 hash.The next time the function is called, it reads the cookie and does the above. There is no tampering with the cookiedata inbetween.It is very simpel, if I use a strongvalue for the cookiedata it evaluates ok. That would make it clear to me that it has something to do with the serializing.
Richard
I edited my question
Richard