douhuiyan2772 2018-10-03 20:37
浏览 113
已采纳

通过替换字符在PHP中创建简单的加密代码

I'm new in PHP.

I want to make a simple encryption function in PHP that change a string to new string by changing characters.

For doing this, I create two arrays of characters.

In the first array I assign all characters and sorting them like :

$true_chars = array('a','b','c','d','e');

In another array, I change the position of the characters.

$fake_chars = array('c','d','a','e','b');

My goal is, when the function gets the right string, change the string characters by Replacing the second array.

For example, my string is acdc , the encryption function compares acdc characters by the first array to get true index's (if need) and then replace by second array index and change it to caea.

how actually can I do that?

  • 写回答

1条回答 默认 最新

  • drz73366 2018-10-03 20:56
    关注

    Start by creating an array that maps the original character to the encoded character:

    $chars = [
        'a' => 'c',
        'b' => 'd',
        'c' => 'a',
        'd' => 'e',
        'e' => 'b',
    ];
    

    Then you loop through the string and replace the characters:

    $original  = 'acdc';
    
    // Encrypt
    $encrypted = '';
    
    for ($i = 0; $i < strlen($original); $i++) {
        // If we find the character in our mapping array, use the mapped character.
        // If not, let's use the original character.
        $encrypted .= array_key_exists($original[$i], $chars) 
            ? $chars[$original[$i]]
            : $original[$i];
    }
    
    print_r($encrypted);
    // caea
    

    To decrypt it, we just needs to check if the character exists in the array and use the key instead:

    // Decrypt
    $decrypted = '';
    for ($i = 0; $i < strlen($encrypted); $i++) {
        // Find the correct key
        $key = array_search($encrypted[$i], $chars);
    
        // If the character existed, use the key.
        // If not, use the original character.
        $decrypted .= $key !== false 
            ? $key
            : $encrypted[$i];
    }
    
    print_r($decrypted);
    // acdc
    

    Demo: https://3v4l.org/vQAZj

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?