php中的加密代码出错

时间:2017-06-22 00:15:13

标签: php

请问我的代码有什么问题?该代码用于加密给定的字符串。它加密非常好,但是当回显加密值时,它会为它添加数字。这是代码:

$keys = "Bb94tU1LSSLgPKNu";
$encrypt = array();

// this contains the key/value pair i used for the encryption
$arrayEncrypt = array("a"=>"g","b"=>"h","c"=>"i","d"=>"j","e"=>"k","f"=>"l","g"=>"m","h"=>"n","i"=>"o","j"=>"p","k"=>"q","l"=>"r", "m"=>"s","n"=>"t","o"=>"u","p"=>"v","q"=>"w","r"=>"x","s"=>"y","t"=>"z","u"=>"a","v"=>"b","w"=>"c","x"=>"d","y"=>"e","z"=>"f","A"=>"G","B"=>"H","C"=>"I","D"=>"J","E"=>"K","F"=>"L","G"=>"M","H"=>"N","I"=>"O","J"=>"P","K"=>"Q","L"=>"R","M"=>"S","N"=>"T","O"=>"U","P"=>"V","Q"=>"W","R"=>"X","S"=>"Y","T"=>"Z","U"=>"A","V"=>"B","W"=>"C","X"=>"D","Y"=>"E","Z"=>"F","0"=>"2","1"=>"4","2"=>"6","3"=>"8","4"=>"0","5"=>"9","6"=>"7","7"=>"5","8"=>"3","9"=>"1");

for ($i = 0; $i < strlen($keys); $i++) {
    if (array_key_exists($keys[$i], $arrayEncrypt)) {  
        foreach ($arrayEncrypt as $key => $letter) {
            if ($keys[$i] == $key) {
                // appends the values of each in $encrypt array
                array_push($encrypt, $letter);
            }
        }
    }
}

$encryptedValue = "";
foreach ($encrypt as $encrypted) {
    $encryptedValue .= $encrypted;
    echo $encryptedValue;
}

打印:

H2h210z2A24R2Y2Y2R2m2V2Q2T2a2

而不是:

Hh10zA4RYYRmVQTa

1 个答案:

答案 0 :(得分:0)

在任何情况下,你都试图使用$ i而不是仅使用名称来获取匹配值。 str_split()获取一个字符数组然后它只是$ arrayEncrypt [$ value]的问题。要撤消您可以使用array_flip()。

为您提供加密和解密功能。享受

<?php
// 1 to encrypt
// 2 to decrypt
function encdec($do, $keys){
    $arrayEncrypt = array("a"=>"g","b"=>"h","c"=>"i","d"=>"j","e"=>"k","f"=>"l","g"=>"m","h"=>"n","i"=>"o","j"=>"p","k"=>"q","l"=>"r", "m"=>"s","n"=>"t","o"=>"u","p"=>"v","q"=>"w","r"=>"x","s"=>"y","t"=>"z","u"=>"a","v"=>"b","w"=>"c","x"=>"d","y"=>"e","z"=>"f","A"=>"G","B"=>"H","C"=>"I","D"=>"J","E"=>"K","F"=>"L","G"=>"M","H"=>"N","I"=>"O","J"=>"P","K"=>"Q","L"=>"R","M"=>"S","N"=>"T","O"=>"U","P"=>"V","Q"=>"W","R"=>"X","S"=>"Y","T"=>"Z","U"=>"A","V"=>"B","W"=>"C","X"=>"D","Y"=>"E","Z"=>"F","0"=>"2","1"=>"4","2"=>"6","3"=>"8","4"=>"0","5"=>"9","6"=>"7","7"=>"5","8"=>"3","9"=>"1");

    if ($do==2){
        $arrayEncrypt=array_flip($arrayEncrypt);
    }

    $chars = str_split($keys);
    $encryptedValue="";

    foreach($chars as $char=>$value){
        $encryptedValue .= $arrayEncrypt[$value];
    }

    return $encryptedValue;
}

echo "Encrypted key: ".encdec(1,"Bb94tU1LSSLgPKNu")."<br />";
echo "Decrypted key: ".encdec(2,"Hh10zA4RYYRmVQTa")."<br />";

?>