Getting started
This guide shows the smallest useful setup for encrypting and decrypting one message.
1. Install the package
composer require phpgt/cipher
The package requires the sodium extension. On current PHP versions this is usually available already, but it still needs to be enabled in the runtime environment.
2. Create a shared key
Cipher uses symmetric encryption, so both sides must know the same key.
use GT\Cipher\Key;
$sharedKey = new Key();
If one side generates the key, the other side must receive the same bytes through a secure channel.
3. Create a plain text message
use GT\Cipher\Message\PlainTextMessage;
$message = new PlainTextMessage("Hello from Cipher");
At this point the message also has an IV attached internally.
4. Encrypt the message
$cipherText = $message->encrypt($sharedKey);
Now we have three important pieces of data:
- the key
- the IV
- the cipher text
The key must remain secret. The IV and cipher text can be transmitted to the receiver.
For example, the sender might transmit these text-safe values:
$outgoingCipher = (string)$cipherText;
$outgoingIv = (string)$message->getIv();
5. Reconstruct the encrypted message on the receiving side
$encryptedMessage = new EncryptedMessage($incomingCipher, $incomingIv);
The EncryptedMessage constructor takes the incoming base64 cipher string plus the incoming base64 IV. When the IV is supplied as a string, it is converted internally into an InitVector from base64.
6. Decrypt using the same key
$decryptedMessage = $encryptedMessage->decrypt($sharedKey);
echo $decryptedMessage;
The output is a new PlainTextMessage, so it can be cast straight to a string.
Full example
use GT\Cipher\Key;
use GT\Cipher\Message\EncryptedMessage;
use GT\Cipher\Message\PlainTextMessage;
$sharedKey = new Key();
$message = new PlainTextMessage("Hello from Cipher");
$cipherText = $message->encrypt($sharedKey);
$cipherString = (string)$cipherText;
$ivString = (string)$message->getIv();
// Send $outgoingCipher and $outgoingIv to the receiver...
// ... then on the receiver:
$encryptedMessage = new EncryptedMessage(
$cipherString,
$ivString,
);
echo $encryptedMessage->decrypt($sharedKey);
A note on sharing the key
In the example above, both sides are in the same PHP script just to keep the flow visible. In a real system:
- the sender and receiver are usually separate processes or separate machines
- both sides must already know the same secret key
- the key should not be transmitted in the same channel as the encrypted payload
With the basic flow working, continue to Encrypting and decrypting messages for a closer look at each step.