How do you Encrypt and Decrypt a PHP String?

后端 未结 10 1541
梦毁少年i
梦毁少年i 2020-11-22 01:21

What I mean is:

Original String + Salt or Key --> Encrypted String
Encrypted String + Salt or Key --> Decrypted (Original String)

May

10条回答
  •  北海茫月
    2020-11-22 01:50

    I'm late to the party, but searching for the correct way to do it I came across this page it was one of the top Google search returns, so I will like to share my view on the problem, which I consider it to be up to date at the time of writing this post (beginning of 2017). From PHP 7.1.0 the mcrypt_decrypt and mcrypt_encrypt is going to be deprecated, so building future proof code should use openssl_encrypt and openssl_decrypt

    You can do something like:

    $string_to_encrypt="Test";
    $password="password";
    $encrypted_string=openssl_encrypt($string_to_encrypt,"AES-128-ECB",$password);
    $decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$password);
    

    Important: This uses ECB mode, which isn't secure. If you want a simple solution without taking a crash course in cryptography engineering, don't write it yourself, just use a library.

    You can use any other chipper methods as well, depending on your security need. To find out the available chipper methods please see the openssl_get_cipher_methods function.

提交回复
热议问题