How do you Encrypt and Decrypt a PHP String?

后端 未结 10 1546
梦毁少年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:35

    In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt.

    openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.

    Syntax is as follows :

    string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 )

    Parameters are as follows :

    $data: It holds the string or data which need to be encrypted.

    $method: The cipher method is adopted using openssl_get_cipher_methods() function.

    $key: It holds the encryption key.

    $options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

    $iv: It holds the initialization vector which is not NULL.

    $tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM).

    $aad: It holds the additional authentication data.

    $tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode.

    Return Value: It returns the encrypted string on success or FALSE on failure.

    openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data.

    Syntax is as follows :

    string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad)

    Parameters are as follows :

    $data: It holds the string or data which need to be encrypted.

    $method: The cipher method is adopted using openssl_get_cipher_methods() function.

    $key: It holds the encryption key.

    $options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

    $iv: It holds the initialization vector which is not NULL.

    $tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE.

    $aad: It holds the additional authentication data.

    Return Value: It returns the decrypted string on success or FALSE on failure.

    Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string.

    You can find the examples at : https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/

提交回复
热议问题