note 85831 modified in function.base64-encode by danbrown

From: Date: Fri, 19 Sep 2008 21:41:41 +0000
Subject: note 85831 modified in function.base64-encode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-144562@lists.php.net to get a copy of this message
I have another solution that is simple and elegant. Create a pseudorandom string of characters. Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding. When you want to de-obfuscate, convert back from base64. If the prefix is not in your pseudorandom source, then the value is forged. Otherwise, strip the prefix and recover your original key. The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast. Here's an example: <?php // Call makeCksum once upon landing on the homepage function makeCksum() { $str = ""; for ($i=0;$i<32;++$i) $str .= chr(rand(32,126)); $_SESSION['Cksum'] = $str; } function encode($x) { return base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x); } function decode($x) { $y = base64_decode($x); if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false; return substr($y,4-strlen($y)); } ?> --was-- I have another solution that is simple and elegant. Create a pseudorandom string of characters. Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding. When you want to de-obfuscate, convert back from base64. If the prefix is not in your pseudorandom source, then the value is forged. Otherwise, strip the prefix and recover your original key. The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast. Here's an example: <?php // Call makeCksum once upon landing on the homepage function makeCksum() { for ($i=0;$i<32;++$i) $str .= chr(rand(32,126)); $_SESSION['Cksum'] = $str; } function encode($x) { return base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x); } function decode($x) { $y = base64_decode($x); if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false; return substr($y,4-strlen($y)); } ?> http://php.net/manual/en/function.base64-encode.php

« previous php.notes (#144562) next »