<?php

declare(strict_types=1);

/*
 * Copyright (c) 2023-2024 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\Radius;

use fkooman\Radius\Exception\PasswordException;

/**
 * Encrypt the RADIUS User-Password Attribute.
 *
 * @see lib/libradius/radius_userpass.c (OpenBSD)
 * @see https://www.rfc-editor.org/rfc/rfc2865#section-5.2
 */
class Password
{
    private const BLOCK_SIZE = 16;

    public static function encrypt(string $userPassword, string $requestAuthenticator, string $sharedSecret): string
    {
        // add padding (iff needed)
        if (0 !== (strlen($userPassword) % self::BLOCK_SIZE)) {
            $userPassword .= str_repeat("\x00", self::BLOCK_SIZE - strlen($userPassword) % self::BLOCK_SIZE);
        }

        $encryptedUserPassword = '';
        for ($o = 0; $o < strlen($userPassword); $o += self::BLOCK_SIZE) {
            $hashContext = hash_init('md5');
            hash_update($hashContext, $sharedSecret);
            if (0 === $o) {
                hash_update($hashContext, $requestAuthenticator);
            } else {
                hash_update($hashContext, Utils::safeSubstr($encryptedUserPassword, $o - self::BLOCK_SIZE, self::BLOCK_SIZE));
            }
            $hashValue = hash_final($hashContext, true);
            $encryptedUserPassword .= Utils::safeSubstr($userPassword, $o, self::BLOCK_SIZE) ^ $hashValue;
        }

        return $encryptedUserPassword;
    }

    public static function decrypt(string $encryptedUserPassword, string $requestAuthenticator, string $sharedSecret): string
    {
        if (0 !== strlen($encryptedUserPassword) % self::BLOCK_SIZE) {
            throw new PasswordException('invalid encrypted password length');
        }

        $userPassword = '';
        for ($o = 0; $o < strlen($encryptedUserPassword); $o += self::BLOCK_SIZE) {
            $hashContext = hash_init('md5');
            hash_update($hashContext, $sharedSecret);
            if (0 === $o) {
                hash_update($hashContext, $requestAuthenticator);
            } else {
                hash_update($hashContext, Utils::safeSubstr($encryptedUserPassword, $o - self::BLOCK_SIZE, self::BLOCK_SIZE));
            }
            $hashValue = hash_final($hashContext, true);
            $userPassword .= Utils::safeSubstr($encryptedUserPassword, $o, self::BLOCK_SIZE) ^ $hashValue;
        }

        return rtrim($userPassword, "\x00");
    }
}
