Skip to content

How to PHP encrypt and decrypt a string safely

How to PHP encrypt and decrypt a string safely

When an application must protect a value and later read it back, you need reversible encryption rather than a one-way hash. This guide explains how to PHP encrypt and decrypt a string with a modern OpenSSL-based approach, how to store the encrypted result, and which older techniques should not be copied into a new project.

Encryption is only one part of a secure design. The key must remain secret, the initialization value must be handled correctly, and the decrypted data must be authenticated before your application trusts it. A working example that produces ciphertext is not automatically a safe example.

The original version of this article uses Mcrypt and fixed values for the key and IV. Treat that code as historical material only. The examples below use authenticated encryption concepts, explicit error handling, and separate advice for passwords, tokens, database values, and user-controlled input.


1. Encryption and Hashing Are Different

1.1 Reversible encryption

Encryption transforms readable plaintext into ciphertext with a secret key. Someone who has the correct key can decrypt the ciphertext and recover the original value. This is useful for data that the application must read later, such as a stored integration credential or a private configuration value.

1.2 One-way hashing

A hash is designed to be difficult to reverse. Passwords should normally be stored with a password-hashing function, not with reversible encryption. During login, the submitted password is verified against the stored hash instead of being decrypted.

1.3 Do not use MD5 for password storage

MD5 is a message-digest algorithm, not a password-storage solution. It is also not a substitute for encryption. Use password_hash() and password_verify() for passwords, and reserve encryption for data that must be recovered by an authorized part of the application.

Comparison of PHP encryption and password hashing
PHP Encryption or Hashing?

2. Why the Mcrypt Example Is Outdated

2.1 Historical code is not production guidance

The old Mcrypt example uses low-level functions, hard-coded key material, a fixed IV, and a CBC-style construction without an authentication tag. Even if it returns the original string in a small demonstration, it does not provide a complete modern security design.

2.2 Fixed keys and IVs cause predictable results

A key must be protected, and the initialization value should normally be fresh for each encryption operation. Reusing a fixed IV can reveal relationships between encrypted messages and can weaken the security properties of the chosen cipher mode.

2.3 Prefer OpenSSL or a maintained cryptographic library

OpenSSL functions are available in supported PHP environments and expose modern cipher modes. For a larger application, a reviewed library can reduce the chance of mishandling encoding, authentication, key storage, and error paths. Do not copy a cryptography snippet without understanding its format and failure behavior.

3. How Symmetric Encryption Works in PHP

3.1 The key

The key is secret material used by both encryption and decryption. It should be generated with a cryptographically secure random source or supplied by a proper secret-management system. It should not be a short human password, a username, or a value committed to a public repository.

3.2 The initialization vector or nonce

Many cipher modes need a public per-message value in addition to the secret key. This value is stored with the ciphertext and is not a replacement for the key. It must have the correct length for the selected cipher and should be generated according to that cipher's requirements.

3.3 Ciphertext and encoding

Encrypted output is binary data. Base64 encoding turns it into text suitable for a database field, JSON document, or transport layer, but Base64 provides no secrecy. The format must preserve every part needed for decryption, such as the version, nonce, authentication tag, and ciphertext.

4. Choose an OpenSSL Encryption Method

4.1 Prefer authenticated encryption

Confidentiality prevents casual reading, while authentication helps detect modification. An authenticated mode such as AES-GCM returns an authentication tag that must be stored and checked during decryption. If the tag does not verify, the application should reject the value.

4.2 Ask PHP which cipher is available

Do not assume that every server has identical OpenSSL capabilities. Check the configured environment and select a documented cipher that is available on the deployment platform. Keep the cipher name in one place so encryption and decryption cannot silently use different algorithms.

4.3 Use a versioned format

Prefix or wrap the encoded value with a format version. A version makes future migrations possible when the application changes its cipher, encoding, or key-management strategy. Never guess which format a legacy value uses based only on its length.

5. Generate and Store Secure Keys

5.1 Generate key material safely

Use a cryptographically secure random generator appropriate for the PHP version and deployment. The key length and representation must match the selected cipher. If the key is represented as Base64 or hexadecimal text, decode it consistently before passing it to the encryption function.

5.2 Keep secrets outside source code

Store encryption keys in a protected environment variable, secret manager, or deployment configuration that is not committed to source control. Limit which processes and administrators can read them. Rotating a key also requires a plan for decrypting existing records during migration.

5.3 Do not confuse a passphrase parameter with key derivation

Passing a short phrase to an encryption function does not automatically create a strong key with a carefully tuned password-based derivation function. Generate a real key for application encryption or use an appropriate key-derivation design when a human password is unavoidable.

6. Encrypt a PHP String

6.1 Prepare the plaintext

Decide exactly what is being encrypted and normalize its format before encryption. If the value is structured data, encode it consistently, such as with JSON, and validate it after decryption. Avoid encrypting unbounded input without limits because ciphertext storage and processing still consume resources.

6.2 Store all required encryption parts

A complete record usually contains the algorithm or format version, the nonce or IV, the authentication tag when the mode provides one, and the ciphertext. The nonce and tag are not passwords; they are required inputs to successful verification and decryption.

A practical encrypted package should preserve the format version, cipher identifier, IV or nonce, authentication tag, and ciphertext. Keeping these fields together makes decryption and later migration predictable.

6.3 Example design

A production implementation should generate a fresh IV of the length returned by the selected cipher, encrypt with raw binary output, capture the authentication tag, concatenate the public components in a documented order, and Base64-encode the complete package. The encryption key stays outside the package.

Keep the routine small and return a clear failure result if the cipher is unavailable or encryption fails. Do not print keys, plaintext secrets, or complete ciphertext values into logs.

7. Decrypt and Validate a PHP String

7.1 Decode and validate the package

Before calling the decryption function, Base64-decode the stored value strictly and verify that each component has the expected length. A malformed value should be treated as invalid input rather than passed through a series of guesses.

7.2 Verify before trusting the result

For an authenticated cipher, supply the stored tag during decryption. A failed verification means that the value may have been altered, truncated, created with another key, or generated in another format. Return a controlled error and do not use the resulting data.

7.3 Handle failure without leaking details

Users generally need a simple message such as “the protected value is unavailable.” Detailed diagnostics can go to an access-controlled log without exposing the key or sensitive plaintext. Distinguish operational monitoring from information shown to an attacker.

8. Why Authentication Matters

8.1 Encryption alone is not enough

If an attacker can change ciphertext and the application accepts the decrypted output, encrypted data may become an input-manipulation opportunity. Authentication binds the encrypted value to a verification tag so tampering can be detected.

8.2 Additional authenticated data

Some designs authenticate associated information that is not encrypted, such as a record identifier or format version. If you use this feature, provide exactly the same associated data during decryption. A mismatch should cause verification to fail.

8.3 Compare and validate consistently

Use the verification behavior provided by the authenticated cipher or a constant-time comparison for a separately calculated MAC. Validate the decoded plaintext as the expected type and structure before using it in a query, command, redirect, or HTML response.

9. Use Password Hashing Instead for Passwords

9.1 Store a password hash

For a login password, call password_hash() with a supported password algorithm and store the complete returned string. The result contains the information needed by password_verify(), including the algorithm configuration and salt information.

9.2 Verify without decrypting

On login, retrieve the stored hash and pass the submitted password and hash to password_verify(). The function returns whether they match. There is no original password for the application to recover, which is the desired property for password storage.

9.3 Rehash when appropriate

When the password policy or algorithm settings become stronger, check whether a successful password should be rehashed and replace the stored value. This lets a system improve gradually without requiring every user to reset a password at once.

10. Common PHP Encryption Mistakes

10.1 Hard-coding keys

A key embedded in a public repository, code sample copied to production, or client-side application is not secret. Move it to protected server-side configuration and plan access controls before deploying.

10.2 Reusing an IV or nonce

Do not use a fixed value simply because it makes the example shorter. Generate the required public value for each encryption operation and store it with the ciphertext.

10.3 Treating Base64 as encryption

Base64 is an encoding. Anyone can decode it. It can make binary ciphertext transportable, but it does not protect data by itself.

10.4 Encrypting passwords or trusting decrypted input blindly

Hash passwords and validate every decrypted value as untrusted input. Encryption protects confidentiality; it does not make the recovered data safe to insert into SQL, HTML, shell commands, or filesystem paths.

11. Using Encrypted Values in Applications

11.1 Database fields

Encrypted fields cannot usually be searched like ordinary plaintext fields. Store a separate non-secret lookup value only when the design permits it, and understand that searchable metadata can reveal information. Keep the encrypted package and key-management policy documented.

11.2 Cookies and URLs

Values placed in a browser, cookie, or URL can be copied and replayed even when their contents are encrypted. Use expiration, audience checks, rotation, and server-side session controls when the value represents authorization or a sensitive action.

11.3 Key rotation

Include a key identifier or format version when multiple keys may exist. During rotation, decrypt with the key associated with the old record and re-encrypt with the active key after successful validation. Do not discard the old key until all required records have migrated.


FAQ

Is Mcrypt still the right way to encrypt a PHP string?

No. It is legacy code and should not be the default for a new application. Use maintained cryptographic facilities and a documented authenticated-encryption design.

Should MD5 be used to encrypt a PHP string?

No. MD5 is a one-way digest and is not suitable for password storage or modern security-sensitive integrity protection. Use password hashing for passwords and authenticated encryption for recoverable data.

Where should a PHP encryption key be stored?

Keep it outside source code in protected deployment configuration or a secret-management service. Limit access and plan how keys will be rotated without losing the ability to read existing data.

What is the difference between encryption and hashing?

Encryption is reversible with the correct key. Hashing is intended to be one-way, which makes it appropriate for verifying passwords rather than recovering them.

How can PHP detect failed decryption?

Use an authenticated mode and verify its tag. Reject malformed packages, failed verification, unavailable keys, and unexpected plaintext instead of continuing with partial output.

Conclusion

Safe PHP encryption requires more than calling a function that returns unreadable text. Choose a maintained cipher mode, generate keys and initialization values correctly, preserve the complete encrypted package, verify authenticity, and keep secrets out of the codebase.

For passwords, do not encrypt at all: use password_hash() and password_verify(). For recoverable application data, document the format and failure behavior so future maintainers can rotate keys and update algorithms without guessing how old values were produced.


FAQ

Is Mcrypt still a good choice for PHP encryption?

No. Treat Mcrypt code as legacy material and do not use it as the template for new work. Use a maintained cryptographic API such as OpenSSL, then test the result on the PHP and OpenSSL versions used by your application.

Should MD5 be used to encrypt a PHP string?

No. MD5 is a one-way digest, not reversible encryption, and it should not be used for password storage or new security-sensitive integrity designs. It cannot restore the original string.

Where should an encryption key be stored?

Keep the key outside source control and protect it with deployment configuration or a secret-management service. Restrict access, exclude it from logs, and document a rotation and recovery process.

What is the difference between encryption and hashing?

Encryption is reversible when the correct key is available. Hashing is designed to be one-way and is normally used to verify passwords or compare data without recovering the original input.

How can PHP detect failed decryption?

Validate the payload, verify the authentication tag in an authenticated mode, check the return value from the OpenSSL function, and reject malformed or unauthenticated data before using it.

Conclusion

To PHP encrypt and decrypt a string safely, choose a maintained cryptographic API, generate a fresh IV for every operation, protect the key, authenticate the ciphertext, and document a versioned payload format. The old Mcrypt class and fixed secrets in the original example should be treated as historical code, not as a secure template.

Use reversible encryption only when the application must recover the original value. For passwords, use password_hash() and password_verify(). Finally, test wrong keys, modified payloads, invalid encodings, and key rotation as carefully as the successful round trip.

Write a comment