Implementing AES Encryption in PHP

Implementing AES Encryption in PHP

Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001. Also referenced as Rijndael, it is one of the most powerful encryption algorithms available today. Although there are some possible attacks (which will be discussed later), the algorithm was strong enough to become the first publicly accessible encryption algorithm that was approved by the National Security Agency (NSA) for encrypting top secret information. This tutorial will explain how AES encryption works and how to implement it in PHP.

How Does AES Work?

Technically speaking, AES can be described as an iterative, symmetric block cipher. It is iterative because the encryption process is done in multiple rounds, symmetric because it uses the same key for encryption and decryption and block cipher because it performs operations on blocks of data. Possible key lengths are 128, 192 and 256 bits (192 or 256-bit keys are required for top secret data). The number of iterations (rounds) is 10, 12 or 14, depending on the length of the key. Blocks of data are always 128 bits long.

Key expansions are the first step of the AES algorithm???deriving round keys from the cipher key using Rijndael key schedule. AES requires a separate 128-bit key for each round plus one more. After that, the algorithm starts performing operations on blocks of data. Each 128-bit block of data is copied into a two-dimensional array, creating a 4×4 matrix called the state matrix. The state matrix looks like this:

First AES iteration is called the initial round. The only operation performed in this round is AddRoundKey, where each byte of the state array is combined with a block of the round key using bitwise exclusive OR. The following rounds perform four different mathematical operations:

  • SubBytes – a non-linear substitution step where each byte is replaced with another according to an 8-bit substitution box, called the Rijndael S-box
  • ShiftRows – a transposition step where the last three rows of the state are shifted cyclically a certain number of steps
  • MixColumns – a mixing operation which operates on the columns of the state array, combining the four bytes in each column
  • AddRoundKey

The last round of processing is called the final round and it does not perform MixColumns operation. So, the final round performs only SubBytes, ShiftRows and AddRoundKey operations.

AES Implementation in PHP

There are many AES implementation in PHP. However, a lot of the code that can be seen on internet is very insecure and not to be used in production. PHP.net provides a good starting example, but their code uses Zero byte padding and is not protected against padding oracle attacks. Having that in mind, in this tutorial I will use a PHP AES encryption?class that has implemented all the necessary security measures and has been informally reviewed by the PHP community. That class implements AES-128 encryption (AES-256 can be used by changing the key size inside the class), PKCS7 padding and authenticates messages with HMAC-SHA256. It requires PHP 5.4 or newer and OpenSSL PHP extension.

After importing the class, the AES encryption code would look like this:

// Import the PHP AES Encryption classrequire_once('Crypto.php');  try {      // Create a random key      // This key is a random binary      // Use scrypt, bcrypt or PBKDF2 to convert string into a key      $key = Crypto::CreateNewRandomKey();      // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),      // they may leak the key to the attacker through side channels.  } catch (CryptoTestFailedException $ex) {      // Error handling      die('Cannot safely create a key');  } catch (CannotPerformOperationException $ex) {      // Error handling      die('Cannot safely create a key');  }  $message = "ATTACK AT DAWN";  try {      // Encrypt the message using the key generated above      $ciphertext = Crypto::Encrypt($message, $key);  } catch (CryptoTestFailedException $ex) {      // Error handling      die('Cannot safely perform encryption');  } catch (CannotPerformOperationException $ex) {      // Error handling      die('Cannot safely perform decryption'); 

}

The following code will decrypt AES encrypted messages:

try {      $decrypted = Crypto::Decrypt($ciphertext, $key);  } catch (InvalidCiphertextException $ex) { // VERY IMPORTANT      // Either:      //   1. The ciphertext was modified by the attacker,      //   2. The key is wrong, or      //   3. $ciphertext is not a valid ciphertext or was corrupted.      // Assume the worst.      die('DANGER! DANGER! The ciphertext has been tampered with!');  } catch (CryptoTestFailedException $ex) {      die('Cannot safely perform encryption');  } catch (CannotPerformOperationException $ex) {      die('Cannot safely perform decryption');  }

There is one more thing that is not mentioned here???key management. Since the same key is used for encryption and decryption, you will have to store the keys in a secure manner and implement key management strategies and best practices. Also, note that the code used in this tutorial is just for educational purposes and, in case you are developing an application with sensitive data, you should consult a security professional.

devx-admin

devx-admin

Share the Post:
Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to