The Wayback Machine - https://web.archive.org/web/20240816044853/https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/
Open In App

How to Encrypt and Decrypt a PHP String ?

Last Updated : 05 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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

Parameters:

  • $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:

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

Parameters:

  • $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. Example 1: This example illustrates the encryption and decryption of string. 

php




<?php
 
// Store a string into the variable which
// need to be Encrypted
$simple_string = "Welcome to GeeksforGeeks\n";
 
// Display the original string
echo "Original String: " . $simple_string;
 
// Store the cipher method
$ciphering = "AES-128-CTR";
 
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
 
// Non-NULL Initialization Vector for encryption
$encryption_iv = '1234567891011121';
 
// Store the encryption key
$encryption_key = "GeeksforGeeks";
 
// Use openssl_encrypt() function to encrypt the data
$encryption = openssl_encrypt($simple_string, $ciphering,
            $encryption_key, $options, $encryption_iv);
 
// Display the encrypted string
echo "Encrypted String: " . $encryption . "\n";
 
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
 
// Store the decryption key
$decryption_key = "GeeksforGeeks";
 
// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt ($encryption, $ciphering,
        $decryption_key, $options, $decryption_iv);
 
// Display the decrypted string
echo "Decrypted String: " . $decryption;
 
?>


Output:

Original String: Welcome to GeeksforGeeks
Encrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA==
Decrypted String: Welcome to GeeksforGeeks

Example 2: Below example illustrate the encryption and decryption of string. Here string to be encrypted and decrypted string will be same but the encrypted string is randomly changed respectively. 

php




<?php
 
// Store a string into the variable which
// needs to be encrypted
$simple_string = "Welcome to GeeksforGeeks";
 
// Display the original string
echo "Original String: " . $simple_string . "\n";
 
// Store cipher method
$ciphering = "BF-CBC";
 
// Use OpenSSL encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
 
// Use random_bytes() function to generate a random initialization vector (iv)
$encryption_iv = random_bytes($iv_length);
 
// Alternatively, you can use a fixed iv if needed
// $encryption_iv = openssl_random_pseudo_bytes($iv_length);
 
// Use php_uname() as the encryption key
$encryption_key = openssl_digest(php_uname(), 'MD5', TRUE);
 
// Encryption process
$encryption = openssl_encrypt($simple_string, $ciphering,
    $encryption_key, $options, $encryption_iv);
 
// Display the encrypted string
echo "Encrypted String: " . $encryption . "\n";
 
// Decryption process
$decryption = openssl_decrypt($encryption, $ciphering,
    $encryption_key, $options, $encryption_iv);
 
// Display the decrypted string
echo "Decrypted String: " . $decryption;
 
?>


Output

Original String: Welcome to GeeksforGeeks
Encrypted String: czY0b71f1vAD9EyyLP4wOke+C8i9QkbbPCrA0se0bjc=
Decrypted String: Welcome to GeeksforGeeks

References:

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Previous Article
Next Article

Similar Reads

How to encrypt and decrypt passwords using PHP ?
The best way to encrypt and decrypt passwords is to use a standard library in PHP because the method of properly encrypting and decrypting passwords from scratch is complex and involves multiple possibilities of security vulnerabilities. Using the standard library ensures that the hashing implementation is verified and trusted. Note: This uses the
2 min read
How to Encrypt MongoDB Data?
In today’s digital world, keeping your sensitive data safe is crucial. MongoDB, a top player in modern data management, offers various ways to encrypt your data. This guide will help you understand MongoDB’s encryption methods, giving you clear instructions, useful tips, and real-world examples to ensure your data stays secure. Table of Content Dec
5 min read
Check if a given String is Binary String or Not using PHP
Given a String, the task is to check whether the given string is a binary string or not in PHP. A binary string is a string that should only contain the '0' and '1' characters. Examples: Input: str = "10111001"Output: The string is binary.Input: str = "123456"Output: The string is not binary.Table of Content Using Regular ExpressionUsing strspn( )
5 min read
How to Replace Part of a string with Another String in PHP?
Given a String, the task is to replace the part of a string with another string in PHP. There are several methods to replace part of a string with another string. This operation is useful when you need to modify a string, such as replacing certain characters or substrings. Table of Content Using str_replace() FunctionUsing substr_replace() Function
2 min read
PHP Program to check a string is a rotation of another string
Given the two strings we have to check if one string is a rotation of another string. Examples: Input : $string1 = "WayToCrack", $string2 = "CrackWayTo"; Output : Yes Input : $string1 = "WillPower" $string2 = "lliW"; Output : No. The above problem can be easily solved in other languages by concatenating the two strings and then would check if the r
3 min read
How to check a string starts/ends with a specific string in PHP ?
In this article, we are going to learn how to check that a given string is starting or ending with a given specific string in PHP. We require the use of XAMPP, Netbeans to run this code. Input: "Geeks For Geeks"Starting with: "G"Output: "Geeks For Geeks Starts with String G"In PHP version 8+, there are str_starts_with(), str_ends_with() functions w
2 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
PHP php.ini File Configuration
At the time of PHP installation, php.ini is a special file provided as a default configuration file. It's a very essential configuration file that controls, what a user can or cannot do with the website. Each time PHP is initialized, the php.ini file is read by the system. Sometimes you need to change the behavior of PHP at runtime, then this confi
5 min read
three90RightbarBannerImg