PHP code example of geekcell / sodium-bundle

1. Go to this page and download the library: Download geekcell/sodium-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

geekcell / sodium-bundle example snippets




return [
    // other bundles ...
    GeekCell\SodiumBundle\GeekCellSodiumBundle::class => ['all' => true],
];



// Sender

namespace Alice\Service;

use GeekCell\SodiumBundle\Sodium\Sodium;

class AnonymousEncryptionService
{
    public function __construct(
        private readonly Sodium $sodium,
    ) {}

    public function encryptMessage(string $message): string
    {
        return $this->sodium
            ->with('box')
            ->encrypt($message)
        ;
    }
}



// Receiver

namespace Bob\Service;

use GeekCell\SodiumBundle\Sodium\Sodium;

class AnonymousDecryptionService
{
    public function __construct(
        private readonly Sodium $sodium,
    ) {}

    public function decryptMessage(string $message): string
    {
        return $this->sodium
            ->with('box')
            ->decrypt($message)
        ;
    }
}

// Sender

namespace Alice\Service;

use GeekCell\SodiumBundle\Sodium\Sodium;

class AuthenticatedEncryptionService
{
    public function __construct(
        private readonly Sodium $sodium,
    ) {}

    public function encryptMessage(string $message, string $recipientPublicKey, $string $nonce): string
    {
        return $this->sodium
            ->with('box')
            ->for($recipientPublicKey)
            ->encrypt($message, $nonce)
        ;
    }
}



// Receiver

namespace Bob\Service;

use GeekCell\SodiumBundle\Sodium\Sodium;

class AuthenticatedDecryptionService
{
    public function __construct(
        private readonly Sodium $sodium,
    ) {}

    public function decryptMessage(string $message, string $senderPublicKey, string $nonce): string
    {
        return $this->sodium
            ->with('box')
            ->from($senderPublicKey)
            ->decrypt($message, $nonce)
        ;
    }
}



namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use GeekCell\SodiumBundle\Support\Facade\Sodium;

#[ORM\Entity]
class DiaryEntry
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    private ?int $id;

    #[ORM\Column(type: 'datetime')]
    private \DateTimeInterface $date;

    #[Column(type: 'text')]
    private string $encryptedEntry;

    public function setEntry(string $entry): void
    {
        $this->encryptedEntry = Sodium::with('box')->encrypt($entry);
    }

    // ...
}