Re: Trying to create an encryption method

From: Date: Sun, 05 Nov 2006 12:46:18 +0000
Subject: Re: Trying to create an encryption method
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-244230@lists.php.net to get a copy of this message
$secret = "HalloWorld"; $encoded = ""; $a = $b = range("a","z"); shuffle($b); $c = array_combine($a, $b); foreach (str_split(strtolower($secret)) as $v) $encoded .= isset($c[ $v ]) ? $c[ $v ] : $v; var_dump($c, $secret, $encoded); Paul Novitski wrote: > At 11/4/2006 08:15 PM, John Meyer wrote: >> I'm trying to create this encryption method for puzzles (nothing super >> secret, just those cryptograms), but this seems to time out, can anybody >> point out what I'm doing wrong here: >> >> for ($i=1;$i<=26;$i++) { >> $normalAlphabet[$i] = chr($i); >> } >> //now, to shuffle >> >> for ($j=1;$j<=26;$j++) { >> do { >> $k = rand(1,26); >> } while ($k == $j || (strlen(trim($normalAlphabet[$k])) >> === 0)); >> $arEncryptedAlphabet[$j] = $normalAlphabet[$k]; >> $normalAlphabet[$k] = ""; >> } >> $arNormalString = str_split($normalzedString); >> $encryptedString = ""; >> for ($i=0;$i<count($arNormalString);$i++) { >> if (ord($arNormalString[$i])>=65 && >> ord($arNormalString[$i])<=90) { >> $encryptedString = $encryptedString . >> $arEncryptedAlphabet[ord($arNormalString[$i]) - 64]; >> } else { >> $encryptedString = $encryptedString . >> $arNormalString[$i]; >> } >> } >> return $encryptedString; >> } > > At 11/4/2006 08:43 PM, Stut wrote: >> Both the inner loop and the outer loop are using $i, meaning the outer >> loop will never end since it gets reset in the inner loop. > > > No, there is no loop nesting. The OP's indenting is misleading. Here's > a reformatted version: > ____________________________ > > for ($i=1;$i<=26;$i++) > { > $normalAlphabet[$i] = chr($i); > } > > //now, to shuffle > for ($j=1;$j<=26;$j++) > { > do > { > $k = rand(1,26); > } > while ($k == $j || (strlen(trim($normalAlphabet[$k])) === 0)); > > $arEncryptedAlphabet[$j] = $normalAlphabet[$k]; > $normalAlphabet[$k] = ""; > } > > $arNormalString = str_split($normalzedString); > $encryptedString = ""; > > for ($i=0;$i<count($arNormalString);$i++) > { > if (ord($arNormalString[$i])>=65 && > ord($arNormalString[$i])<=90) > { > $encryptedString = $encryptedString . > $arEncryptedAlphabet[ord($arNormalString[$i]) - 64]; > } > else > { > $encryptedString = $encryptedString . > $arNormalString[$i]; > } > } > return $encryptedString; > > } > ____________________________ > > The script spends eternity executing the do...while loop. John, display > your values at each loop while your code is running to see where your > problem lies. > > By the way, are you aware that chr(1) isn't 'A'? It's hex(01). > 'A' = > hex(40) = dec(64). Your array $normalAlphabet is not going to contain > the alphabet the way it's written now. > > Regards, > Paul >

« previous php.general (#244230) next »