Key and IV objects
Key and InitVector are deliberately tiny classes, but they are central to how the rest of the library stays readable.
Key
Key wraps the raw bytes used as the shared secret.
Creating a new random key
use GT\Cipher\Key;
$key = new Key();
With no constructor argument, Cipher generates cryptographically secure random bytes of the correct length.
Reconstructing an existing key
$storedBase64 = "…";
$key = new Key(base64_decode($storedBase64));
This is the usual approach when the key comes from configuration, a secrets store, or another trusted process.
Converting to a string
echo (string)$key;
Casting to a string returns a base64 representation of the key bytes.
That is useful for storage, but the string should still be treated as secret material.
Accessing raw bytes
$bytes = $key->getBytes();
The raw bytes are what libsodium uses internally.
InitVector
InitVector represents the random data used during encryption and decryption.
Creating an IV
use GT\Cipher\InitVector;
$iv = new InitVector();
In practice, we often do not need to do this ourselves because PlainTextMessage creates one automatically.
Converting to a string
echo (string)$iv;
The string value is base64 encoded, which makes it suitable for transmission in query strings or other text-safe transports.
Reconstructing from bytes
$iv = (new InitVector())->withBytes(base64_decode($storedBase64Iv));
withBytes() returns a cloned object with the supplied bytes, leaving the original object untouched.
Valid byte length
If we pass an invalid length less than 1 to the constructor, Cipher throws CipherException.
new InitVector(0); // throws
Key and IV responsibilities
It is useful to keep their roles separate:
- the key is secret and must stay private
- the IV is not secret, but it must match the encrypted message
- both are required for successful decryption
A practical pattern
One common pattern is:
- Generate the key once and store it securely.
- Generate a fresh IV for each message.
- Transmit the IV with the encrypted payload.
- Reuse the same key only between the systems that are meant to trust each other.
Cipher fits neatly around that model.
Next, read Error handling to see how failures are surfaced by the API.