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

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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号