class Crypto (View source)

Constants

private HEADER

Header tagging the authenticated (random-IV + HMAC) payload format.

The ':' is not part of the base64 alphabet, so a value carrying this prefix can never be confused with a legacy (base64-only) ciphertext.

private SIGN_HEADER

Header tagging an authenticated-but-unencrypted (signed) payload. The ':' keeps it distinguishable from an encrypted (BOW2:) or base64 value.

private MAC_LENGTH

The authentication tag length in bytes (HMAC-SHA256).

Methods

static void
setKey(string $key, string|null $cipher = null)

Set the key

static void
allowLegacy(bool $allow = true)

Allow or forbid decrypt() from falling back to the unauthenticated legacy format. Off by default; enable only while migrating old ciphertexts.

static string
encrypt(string $data)

Encrypt data.

static string|bool
decrypt(string $data)

Decrypt data.

static string
sign(string $data)

Produce a tamper-proof but readable payload.

static string|bool
verify(string $data)

Verify a signed payload, returning the original data or false on a bad tag.

Details

static void setKey(string $key, string|null $cipher = null)

Set the key

Parameters

string $key
string|null $cipher

Return Value

void

static void allowLegacy(bool $allow = true)

Allow or forbid decrypt() from falling back to the unauthenticated legacy format. Off by default; enable only while migrating old ciphertexts.

Parameters

bool $allow

Return Value

void

static string encrypt(string $data)

Encrypt data.

Produces an authenticated payload: a fresh random IV is used for every call (so identical plaintexts yield different ciphertexts) and an encrypt-then-MAC HMAC-SHA256 tag protects against tampering.

Parameters

string $data

Return Value

string

static string|bool decrypt(string $data)

Decrypt data.

Authenticated payloads are verified before decryption and fail closed (return false) on a bad tag, truncation or wrong key. Values produced by the previous unauthenticated format are still readable for backward compatibility.

Parameters

string $data

Return Value

string|bool

static string sign(string $data)

Produce a tamper-proof but readable payload.

Unlike encrypt(), the data is not enciphered — only a detached HMAC-SHA256 tag is prepended — so the payload stays inspectable in transit (e.g. a queue backend) while still being protected against tampering and forgery. Use when integrity matters but confidentiality does not.

Parameters

string $data

Return Value

string

static string|bool verify(string $data)

Verify a signed payload, returning the original data or false on a bad tag.

Fails closed (false) on a wrong header, truncation, tampering or wrong key, exactly like decrypt().

Parameters

string $data

Return Value

string|bool