<?php

/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

declare(strict_types=1);

namespace Resursbank\MerchantApi\Crypto;

use Defuse\Crypto\Crypto;
use Defuse\Crypto\Exception\CryptoException;
use Defuse\Crypto\Exception\EnvironmentIsBrokenException;
use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;

/**
 * Encryption library using OpenSSL.
 */
class Openssl
{
    /**
     * @param string $secret
     */
    public function __construct(
        private readonly string $secret
    ) {
    }

    /**
     * @param string $data
     *
     * @return string
     *
     * @throws CryptoException
     * @throws EnvironmentIsBrokenException
     */
    public function encrypt(
        string $data
    ): string {
        return Crypto::encryptWithPassword($data, $this->secret);
    }

    /**
     * @param string $data
     *
     * @return string
     *
     * @throws CryptoException
     * @throws EnvironmentIsBrokenException
     * @throws WrongKeyOrModifiedCiphertextException
     */
    public function decrypt(
        string $data
    ): string {
        return Crypto::decryptWithPassword($data, $this->secret);
    }
}
