Sometimes we encounter data that needs to be encrypted in the project, but we have to decrypt it ourselves, so we can only find some symmetric encryption algorithms, and then decrypt it when we want to see it. This article introduces the implementation of a simple symmetric encryption algorithm in PHP. I hope it will be helpful to everyone.
Preface
I found a good symmetric encryption algorithm for PHP on the Internet; in the PHP syntax environment, there are urlencode and urldecode , base64_encode and base64_decode come with their own symmetric algorithms, but these built-in algorithms cannot be called encryption algorithms, they can only be said to be encoding methods. But we can use these to perform some processing to implement simple encryption and decryption algorithms.
This time the encryption and decryption algorithms are adapted using base64. Usually we use the string generated by base64_encode($str)
without any processing, base64_decode()
can convert back to our previous string; but if we # How many characters are inserted into the string after ##base64_encode()? Then it cannot be converted back. Even if it is converted, it is not our own string.
The sample code is as follows:
<?php $content = "大家好,我是中国人,你是谁"; /** * 简单对称加密算法之加密 * @param String $string 需要加密的字串 * @param String $skey 加密EKY * @return String */ function encode($string = '', $skey = 'wenzi') { $strArr = str_split(base64_encode($string)); $strCount = count($strArr); foreach (str_split($skey) as $key => $value) $key < $strCount && $strArr[$key].=$value; return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr)); } /** * 简单对称加密算法之解密 * @param String $string 需要解密的字串 * @param String $skey 解密KEY * @return String */ function decode($string = '', $skey = 'wenzi') { $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2); $strCount = count($strArr); foreach (str_split($skey) as $key => $value) $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0]; return base64_decode(join('', $strArr)); } echo '<pre class="brush:php;toolbar:false">'; echo "string : " . $content . " <br />"; echo "encode : " . ($enstring = encode($content)) . '<br />'; echo "decode : " . decode($enstring); exit();
base64_encode() Insert the key we set in advance into the characters, and then replace the special characters inside. Even if others see such a string, they will not know what it is. Of course, we can make slight improvements here, such as inserting the key into the string backwards, base64 the key and then insert it, etc. After inserting the key, base64 it again.
Related recommendations:
PHP How to better encrypt passwords
php method to obtain flash detailed data
The above is the detailed content of PHP implements simple symmetric encryption. For more information, please follow other related articles on the PHP Chinese website!