Home  >  Article  >  Backend Development  >  How does PHP use a custom key to encrypt and decrypt data?

How does PHP use a custom key to encrypt and decrypt data?

小云云
小云云Original
2017-12-11 09:55:132513browse

When the client and server communicate, there is a very common scenario where an id is passed back and forth as a url parameter. Assuming that the current business only has this ID identifier, then slightly more secure communication is needed to encrypt and transmit this ID, and then decrypt it to the server. A server-side secret key is needed here, and this key is used for encryption and decryption. This article mainly introduces how PHP uses custom keys to encrypt and decrypt data. It involves PHP's techniques for implementing encryption and decryption functions for string conversion, interception and other operations. Friends who need it can refer to it. I hope it can help everyone.

The encryption and decryption methods are as follows: $str is the string that needs to be encrypted and decrypted, $key is a key defined by yourself

// 加密
function encryptStr($str, $key){
  $block = mcrypt_get_block_size('des', 'ecb');
  $pad = $block - (strlen($str) % $block);
  $str .= str_repeat(chr($pad), $pad);
  $enc_str = mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
  return base64_encode($enc_str);
}
// 解密
function decryptStr($str, $key){
  $str = base64_decode($str);
  $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
  $block = mcrypt_get_block_size('des', 'ecb');
  $pad = ord($str[($len = strlen($str)) - 1]);
  return substr($str, 0, strlen($str) - $pad);
}

Worth it One thing to mention is:

If it is applied to the scenario of id in the URL, then after encryption, it is base64 encoding. It is recommended to urlencode() to remove the influence of the + sign.

Related recommendations:

php string encryption and decryption implementation process sharing

mysql functions about encryption and decryption

Tutorial on the use of several methods of php encryption and decryption

The above is the detailed content of How does PHP use a custom key to encrypt and decrypt data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn