Documentation

Cryptex
in package

FinalYes

Cryptex performs 2-way authenticated encryption using XChaCha20 + Poly1305.

This class leverages the Sodium crypto library, added to PHP in version 7.2. A salt value of length SODIUM_CRYPTO_PWHASH_SALTBYTES is required and should be randomly generated with the included generateSalt() function or another secure function like random_bytes().

Tags
category

Encryption/Decryption

author

Michael Mawhinney

copyright

2023

license

https://opensource.org/licenses/MIT/ MIT

version
4.0.0

Table of Contents

Constants

NONCE_LENGTH  = \SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES
SALT_LENGTH  = \SODIUM_CRYPTO_PWHASH_SALTBYTES

Methods

decrypt()  : string
Authenticates and decrypts data encrypted by Cryptex (XChaCha20+Poly1305).
encrypt()  : string
Encrypts data using XChaCha20 + Poly1305 (from the Sodium crypto library).
generateSalt()  : string
Generates a salt value.
generateDerivedKey()  : string
Generates a derived binary key using Argon2id v1.3.

Constants

NONCE_LENGTH

private int NONCE_LENGTH = \SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES

Required length of the nonce value

SALT_LENGTH

private int SALT_LENGTH = \SODIUM_CRYPTO_PWHASH_SALTBYTES

Required length of the salt value

Methods

decrypt()

Authenticates and decrypts data encrypted by Cryptex (XChaCha20+Poly1305).

public static decrypt(string $ciphertext, string $key, string $salt) : string
Parameters
$ciphertext : string

Encrypted data.

$key : string

Encryption key.

$salt : string

Salt value.

Tags
throws
NonceLengthException

If the decoded data is not the expected length.

throws
DecryptionException

If the data decryption fails.

Return values
string

Unencrypted data.

encrypt()

Encrypts data using XChaCha20 + Poly1305 (from the Sodium crypto library).

public static encrypt(string $plaintext, string $key, string $salt) : string
Parameters
$plaintext : string

Unencrypted data.

$key : string

Encryption key.

$salt : string

Salt value of length SODIUM_CRYPTO_PWHASH_SALTBYTES.

Tags
throws
EncryptionException

If the data encryption fails.

Return values
string

Encrypted data (hex-encoded).

generateSalt()

Generates a salt value.

public static generateSalt() : string
Tags
throws
Exception

If an error occurs while generating the salt value.

Return values
string

Random salt value of length SODIUM_CRYPTO_PWHASH_SALTBYTES.

generateDerivedKey()

Generates a derived binary key using Argon2id v1.3.

private static generateDerivedKey(string $key, string $salt) : string
Parameters
$key : string

Encryption key.

$salt : string

Salt value of length SODIUM_CRYPTO_PWHASH_SALTBYTES.

Tags
throws
SaltLengthException

If the salt is not the expected length.

throws
Exception

If an error occurs while generating the derived binary key.

Return values
string

Derived binary key.


        
On this page

Search results