通过替换字符在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?
我是PHP新手。 p>
我想做一个简单的事情 PHP中的加密函数,通过更改字符将字符串更改为新字符串。 p>
为此,我创建了两个字符数组。 p>
在 第一个数组我分配所有字符并将它们排序为: p>
$ true_chars = array('a','b','c','d','e') ;
code> pre>
在另一个数组中,我改变了字符的位置。 p>
$ fake_chars = array(' c','d','a','e','b');
code> pre>
我的目标是,当函数获得正确的字符串时,更改 替换第二个数组的字符串字符。 p>
例如,我的字符串是 acdc code>,加密函数比较 acdc code>字符 第一个数组获取真正的索引(如果需要)然后替换为第二个数组索引并将其更改为 caea code>。 p>
我实际上该怎么做? p>
div>
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