PHP uses custom key to realize the method of data encryption and decryption

  • 2021-08-21 19:51:30
  • OfStack

In this paper, an example of PHP using custom key to achieve data encryption and decryption method. Share it for your reference, as follows:

When the client and server communicate, there is a common scenario, which is passed back and forth through an id as an url parameter. Assuming that there is only this id identity in the business now, it needs a slightly secure communication, encrypts and transmits this id, and then decrypts it to the server. Here, we need a server to keep key secret, and use this key to encrypt and decrypt.

Encryption and decryption methods are as follows: $str is a string to be encrypted and decrypted, and $key is a self-defined key


//  Encryption 
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);
}
//  Decryption 
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);
}

It is worth mentioning that:

If it is applied to this scenario of id in url, it is the encoding of base64 after encryption, so it is recommended to re-encode urlencode() Next, remove the influence of + sign.

PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:

Text online encryption and decryption tools (including AES, DES, RC4, etc.):
http://tools.ofstack.com/password/txt_encode

MD5 Online Encryption Tool:
http://tools.ofstack.com/password/CreateMD5Password

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption Tool:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1/sha224/sha256/sha384/sha512 Encryption Tool:
http://tools.ofstack.com/password/sha_encode

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of php Encryption Methods", "Summary of PHP Encoding and Transcoding Operation Skills", "Summary of PHP Mathematical Operation Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Tutorial on PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Summary of php Regular Expression Usage"

I hope this article is helpful to everyone's PHP programming.


Related articles: