-
-
Notifications
You must be signed in to change notification settings - Fork 0
Getting started
This guide shows the smallest useful setup for encrypting and decrypting one message.
composer require phpgt/cipherThe 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.
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.
use GT\Cipher\Message\PlainTextMessage;
$message = new PlainTextMessage("Hello from Cipher");At this point the message also has an IV attached internally.
$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();$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.
$decryptedMessage = $encryptedMessage->decrypt($sharedKey);
echo $decryptedMessage;The output is a new PlainTextMessage, so it can be cast straight to a string.
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);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.
PHP.GT/Cipher is a separately maintained component of PHP.GT/WebEngine.