<?php

namespace CookieSession\Encrypter;

class EncrypterTest extends \PhpUnit_Framework_TestCase
{
    protected $encrypter;

    public function testSymmetricEncryption()
    {
        $original = 'Lorem Ipsum Dolor Sit Amet Consetetur';

        $encrypted = $this->getEncrypter()->encrypt($original);

        $this->assertNotEquals($original, $encrypted);
        $this->assertEquals($original, $this->getEncrypter()->decrypt($encrypted));
    }

    public function testSignature()
    {
        $original = 'Lorem Ipsum Dolor Sit Amet Consetetur';
        $encrypter = $this->getEncrypter();

        $encrypted = $encrypter->encrypt($original);

        $signature = $encrypter->sign($encrypted);

        $this->assertTrue($encrypter->verify($encrypted, $signature));
    }

    public function testPublicEncrypt()
    {
        $original = 'Lorem Ipsum Dolor Sit Amet Consetetur';

        $encr = $this->getEncrypter();

        $encrypted = $encr->encryptPublic($original);

        $this->assertNotEquals($original, $encrypted);
        $this->assertEquals($original, $encr->decryptPrivate($encrypted));
    }

    public function testPrivateEncrypt()
    {
        $original = 'Lorem Ipsum Dolor Sit Amet Consetetur';

        $encr = $this->getEncrypter();

        $encrypted = $encr->encryptPrivate($original);

        $this->assertNotEquals($original, $encrypted);
        $this->assertEquals($original, $encr->decryptPublic($encrypted));
    }

    /**
     * @return Encrypter
     */
    protected function getEncrypter()
    {
        if(!$this->encrypter instanceof Encrypter)
        {
            $this->encrypter = new Encrypter();

            $this->encrypter->setMethod('aes-256-cbc');
            $this->encrypter->setSecret(openssl_random_pseudo_bytes(32));
            $this->encrypter->setIV(openssl_random_pseudo_bytes(16));
            $this->encrypter->setPublicKey(file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR .'../../pki/public.crt'));
            $this->encrypter->setPrivateKey(file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR .'../../pki/private.pem'));
        }

        return $this->encrypter;
    }
}