1

I am using mcrypt_encrypt/decrypt to create a coupon whose code is passed through the URL.

public function getReservationIdFromHash($hash) {
    $base64Hash = pack('H*',$hash);
    $encrypted = base64_decode($base64Hash);
    $key = pack("H*", '0123456789abcdef0123456789abcdef');
    $iv =  pack("H*", "abcdef9876543210abcdef9876543210");
    $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
    return $str;    
}

public function encodeCode($code) {

    $key = pack("H*", '0123456789abcdef0123456789abcdef');
    $iv =  pack("H*", "abcdef9876543210abcdef9876543210");
    $cypherText = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $code, MCRYPT_MODE_CBC, $iv);
    $base64 = base64_encode($cypherText);
    $arr = unpack('H*',$base64);
    $dev = array_pop($arr);
    return $dev;       
}

But I am experiencing a weird problem because this encrypted code (which is the result of my function):

785738496771754c66595869566d73446970667444413d3d

and this:

785738496771754c66595869566d73446970667444413d3d44

always are decode to: "XXXXXXXXXXX" (the string I am using to testing), but my common sense says me that they shouldn't be decoded to the exact equal string.

I think I am doing something wrong but I can't imagine what is.

Thanks

1 Answer 1

1

Display $encrypted, you will probably see the same thing.

In short: if you supply the same (and valid) input to encryption/decryption function you will get the same output. In this case the two inputs must not be the same.

Both look like a hexadecimal display of Base64 encoded data.

The first output is 24 ASCII characters
xW8IgquLfYXiVmsDipftDA==,
the second output is 25 ASCII characters
xW8IgquLfYXiVmsDipftDA==D.

The first ends in ASCII == which can only occur at the end of a Base64 encoding. The second ends in ASCII ==D. My guess is that the Base64 decoding is stopping at the == and ignoring additional characters since that can only occur at the end of a Base64 encoded value.

Also the length of the second is not a valid Base64 length, Base64 encoding are always a multiple of 4-bytes with end padding with 0, 1 or 2 = characters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.