<?php

namespace idoit\Module\License\Crypt;

use phpseclib\Crypt\Rijndael;

/**
 * i-doit
 *
 * Helper methods for Crypting via phpseclib
 *
 * @package     i-doit
 * @subpackage  Helper
 * @author      Kevin Mauel <kmauel@i-doit.org>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @since       1.0
 */
class DefaultEncryption
{
    /**
     * Default delimiter
     *
     * @type string
     */
    const DELIMITER = '|$$|';

    /**
     * Decrypt a string.
     *
     * @param  string $string
     *
     * @param string $encryptionKey
     *
     * @return null|string
     */
    public function decrypt($string, $encryptionKey)
    {
        // Prepare encrypting password
        $base64decoding = base64_decode($string, true);

        // Check whether delimiter is included
        if (strpos($base64decoding, self::DELIMITER) !== false) {
            // Split encrypted string with given delimiter
            $encryptedArray = explode(self::DELIMITER, $base64decoding);

            // Prepare and run decrypting routine
            $cipher = new Rijndael();
            $cipher->setKey($encryptionKey);
            $cipher->setIV($encryptedArray[0]);

            // Decrypt password
            return $cipher->decrypt($encryptedArray[1]);
        }

        return null;
    }
}
