PHPackages                             devuri/encryption - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. devuri/encryption

ActiveLibrary[Security](/categories/security)

devuri/encryption
=================

A Composer package for handling encryption and decryption operations.

0.3.1(2y ago)224.4k↓100%[1 PRs](https://github.com/devuri/encryption/pulls)3MITPHPPHP ^7.4 || ^8.0CI failing

Since Jul 29Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/devuri/encryption)[ Packagist](https://packagist.org/packages/devuri/encryption)[ RSS](/packages/devuri-encryption/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (7)Versions (7)Used By (3)

Encryption Package
==================

[](#encryption-package)

The **Encryption** package is a simple Composer package that provides functionality for encrypting and decrypting data using the [Defuse PHP encryption library](https://github.com/defuse/php-encryption) or encrypting and decrypting data using OpenSSL. This package simplifies the process of handling encryption keys and allows you to perform encryption and decryption operations on files and data with ease.

Requirements
------------

[](#requirements)

- PHP 7.4 or higher.
- OpenSSL PHP Extension enabled.

Installation
------------

[](#installation)

To use this package in your PHP application, you need to have [Composer](https://getcomposer.org/) installed. Once you have Composer set up, run the following command to add the package to your project:

```
composer require devuri/encryption
```

Usage
-----

[](#usage)

### Encryption Key Generation

[](#encryption-key-generation)

To encrypt and decrypt data using the library, you need to generate an encryption key. The `EncryptionKey` class provides a simple way to generate a new random encryption key in ASCII format:

```
use Urisoft\EncryptionKey;

// Generate a new encryption key
$key = EncryptionKey::generate_key();

// Store the generated key securely (e.g., in a secret key file) for future use.
```

Ensure you keep the generated encryption key secure and protected, as it is essential for encrypting and decrypting sensitive data.

### Setting up Encryption

[](#setting-up-encryption)

To use the Encryption package, you first need to set up the `Encryption` class by providing the necessary parameters:

```
use Urisoft\Encryption;
use Urisoft\Filesystem;

// Replace these with the appropriate values for your application
$rootDirPath = __DIR__;
$filesystem = new Filesystem(); // Optional, required only for encrypt_envfile()
$secretKeyPath = '/path/to/secret_key_directory';
$keyId = 'secret'; // Optional, default is 'secret'

try {
    $encryption = new Encryption($rootDirPath, $filesystem, $secretKeyPath, $keyId);
} catch (InvalidArgumentException $e) {
    // Handle exception if the secret key file is not found
}
```

> **Note**: The `$filesystem` parameter is optional. Pass `null` if you don't need the `encrypt_envfile()` method. You can also provide your own implementation of `FilesystemInterface`.

### Encrypting and Decrypting Files

[](#encrypting-and-decrypting-files)

You can use the `encrypt_file()` and `decrypt_file()` methods to encrypt and decrypt files:

```
try {
    // Encrypt a file
    $inputFile = '/path/to/input_file.txt';
    $outputFile = '/path/to/encrypted_file.txt';
    $encryption->encrypt_file($inputFile, $outputFile);

    // Decrypt the encrypted file
    $encryptedFile = '/path/to/encrypted_file.txt';
    $decryptedFile = '/path/to/decrypted_file.txt';
    $encryption->decrypt_file($encryptedFile, $decryptedFile);
} catch (Exception $e) {
    // Handle encryption/decryption errors
}
```

### Encrypting Data

[](#encrypting-data)

You can use the `encrypt()` method to encrypt data, such as sensitive information:

```
$dataToEncrypt = 'This is sensitive data';
$encryptedData = $encryption->encrypt($dataToEncrypt);

// Optionally, encode the encrypted data in base64
$base64EncodedData = $encryption->encrypt($dataToEncrypt, true);
```

### Decrypting Data

[](#decrypting-data)

To decrypt encrypted data, use the `decrypt()` method:

```
$encryptedData = '...'; // Replace this with the actual encrypted data
$decryptedData = $encryption->decrypt($encryptedData);

// Optionally, if the encrypted data was base64-encoded
$base64EncodedData = '...'; // Replace this with the actual base64-encoded data
$decodedDecryptedData = $encryption->decrypt($base64EncodedData, true);

if ($decryptedData === null || $decodedDecryptedData === null) {
    // Decryption failed or wrong key was loaded
    // Handle the error accordingly
}
```

### Encrypting .env File

[](#encrypting-env-file)

The package provides a method to encrypt the contents of a .env file:

```
try {
    // Encrypt the .env file
    $encryption->encrypt_envfile('/.env');
} catch (Exception $e) {
    // Handle encryption errors
}
```

The encrypted contents will be saved in a file named `.env.encrypted`.

Key Management
--------------

[](#key-management)

The Encryption class expects the secret key file to be stored in ASCII format. It retrieves the encryption key from the secret key file specified during initialization. Make sure to keep the secret key file secure and protected.

If you have a constant `WEBAPP_ENCRYPTION_KEY` defined, the class will use that as the encryption key. Otherwise, it will look for the secret key file in the provided directory with the default filename identifier 'secret'. The key file should be named as '.secret.txt' by default unless you specify a different key filename identifier during initialization.

OpenSSLEncrypt
==============

[](#opensslencrypt)

The `OpenSSLEncrypt` class, provides a simple interface for encrypting and decrypting data using OpenSSL. It supports various cipher algorithms and output formats, such as base64 and hex.

Usage
-----

[](#usage-1)

```
use Urisoft\OpenSSLEncrypt;

$key = 'your-encryption-key'; // Replace with your secure key.
$cipher = 'AES-128-CBC'; // Optional, default is AES-128-CBC.

$encryptor = new OpenSSLEncrypt($key, $cipher);
```

If you don't specify a cipher, AES-128-CBC is used by default.

### Encrypting Data

[](#encrypting-data-1)

```
$plainText = "Hello, World!";
$outputFormat = 'base64'; // Optional, formats: base64, hex, binary. Default is base64.

$encryptedText = $encryptor->encrypt($plainText, $outputFormat);
```

### Decrypting Data

[](#decrypting-data-1)

```
$inputFormat = 'base64'; // Should match the format used in encryption. Default is base64.

$decryptedText = $encryptor->decrypt($encryptedText, $inputFormat);
```

Methods
-------

[](#methods)

- `__construct(string $key, string $cipher = 'AES-128-CBC')`: Constructor to initialize the encryption key and cipher algorithm. Throws `InvalidArgumentException` if an unsupported cipher is provided.
- `encrypt(string $data, string $outputFormat = 'base64')`: Encrypts the provided data and returns it in the specified format. Throws `RuntimeException` if encryption fails.
- `decrypt(string $data, string $inputFormat = 'base64')`: Decrypts the provided data assuming it's in the specified format. Throws `RuntimeException` if decryption fails or input format is invalid.

Notes
-----

[](#notes)

- It is crucial to use a secure and unique key for encryption.
- Cipher names are case-insensitive (e.g., `AES-128-CBC` and `aes-128-cbc` are both valid).
- The choice of cipher algorithm can be modified based on your requirements. Use `openssl_get_cipher_methods()` to list available ciphers.
- The class automatically handles format conversions for input and output.

License
-------

[](#license)

This package is open-source software licensed under the [MIT License](https://opensource.org/licenses/MIT).

Acknowledgments
---------------

[](#acknowledgments)

The Encryption package utilizes the [Defuse PHP encryption library](https://github.com/defuse/php-encryption) for encryption and decryption operations.

For more information on how to use the Defuse PHP encryption library, please refer to its documentation.

**Note**: Replace the ellipsis (...) in the usage examples with actual data or file paths relevant to your application. Always handle exceptions appropriately when performing encryption and decryption operations.

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance62

Regular maintenance activity

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~93 days

Total

4

Last Release

736d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8fd19f958b007ec6588d0a5ca2fe78e107edd652f286b836d36b5d1781d573a5?d=identicon)[devuri](/maintainers/devuri)

---

Top Contributors

[![devuri](https://avatars.githubusercontent.com/u/4777400?v=4)](https://github.com/devuri "devuri (22 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

securityencryptionsecurecryptographic

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/devuri-encryption/health.svg)

```
[![Health](https://phpackages.com/badges/devuri-encryption/health.svg)](https://phpackages.com/packages/devuri-encryption)
```

###  Alternatives

[phpseclib/phpseclib

PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.

5.6k434.8M1.3k](/packages/phpseclib-phpseclib)[defuse/php-encryption

Secure PHP Encryption Library

3.9k162.4M212](/packages/defuse-php-encryption)[ass/xmlsecurity

The XmlSecurity library is written in PHP for working with XML Encryption and Signatures

955.6M30](/packages/ass-xmlsecurity)[nzo/url-encryptor-bundle

The NzoUrlEncryptorBundle is a Symfony Bundle used to Encrypt and Decrypt data and variables in the Web application or passed through URL

961.0M2](/packages/nzo-url-encryptor-bundle)[tilleuls/url-signer-bundle

Create and validate signed URLs with a limited lifetime in Symfony

81340.1k](/packages/tilleuls-url-signer-bundle)[causal/fal-protect

Protect everything within /fileadmin/ based on associated folder and file restrictions (visibility, user groups and dates of publication).

1269.5k](/packages/causal-fal-protect)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
