<?php
/**
 * MsaCrypt - decrypts credentials stored in the server environment.
 *
 * AES-256-CBC + HMAC-SHA256 (encrypt-then-MAC). PHP 5.4+.
 * Payload format: 'enc:v1:' . base64(iv|hmac|ciphertext)
 */
class MsaCrypt
{
    const ENV_MASTER_KEY_NAME = 'MSA_CRYPT_KEY';
    const PREFIX = 'enc:v1:';

    const CIPHER      = 'aes-256-cbc';
    const MASTER_LEN  = 32;
    const IV_LEN      = 16;
    const MAC_LEN     = 32;

    private static $masterCache = null;
    private static $envFileLoaded = array();

    /** Base64 master key. Run once per environment; dev and prod must differ. */
    public static function generateMasterKey()
    {
        return base64_encode(self::randomBytes(self::MASTER_LEN));
    }

    public static function masterKey()
    {
        if (self::$masterCache !== null) {
            return self::$masterCache;
        }

        $b64 = self::env(self::ENV_MASTER_KEY_NAME);
        if ($b64 === null || $b64 === '') {
            throw new Exception(
                'MsaCrypt: env var ' . self::ENV_MASTER_KEY_NAME . ' is not set. '
                . 'Generate one with: php encrypt_secret.php --genkey'
            );
        }

        $raw = base64_decode($b64, true);
        if ($raw === false || strlen($raw) !== self::MASTER_LEN) {
            throw new Exception(
                'MsaCrypt: ' . self::ENV_MASTER_KEY_NAME . ' must be base64 of exactly '
                . self::MASTER_LEN . ' bytes (got ' . ($raw === false ? 'invalid base64' : strlen($raw) . ' bytes') . ').'
            );
        }

        self::$masterCache = $raw;
        return $raw;
    }

    // Separate subkeys for encryption and MAC.
    private static function encKey($master) { return hash_hmac('sha256', 'msacrypt/v1/enc', $master, true); }
    private static function macKey($master) { return hash_hmac('sha256', 'msacrypt/v1/mac', $master, true); }

    public static function encrypt($plaintext, $master = null)
    {
        if ($master === null) { $master = self::masterKey(); }

        $iv  = self::randomBytes(self::IV_LEN);
        $ct  = openssl_encrypt($plaintext, self::CIPHER, self::encKey($master), OPENSSL_RAW_DATA, $iv);
        if ($ct === false) {
            throw new Exception('MsaCrypt: openssl_encrypt failed');
        }

        $mac = hash_hmac('sha256', $iv . $ct, self::macKey($master), true);

        return self::PREFIX . base64_encode($iv . $mac . $ct);
    }

    public static function decrypt($payload, $master = null)
    {
        if ($master === null) { $master = self::masterKey(); }

        if (strpos($payload, self::PREFIX) !== 0) {
            throw new Exception('MsaCrypt: payload is not ' . self::PREFIX . ' encoded');
        }

        $blob = base64_decode(substr($payload, strlen(self::PREFIX)), true);
        if ($blob === false || strlen($blob) < self::IV_LEN + self::MAC_LEN + 1) {
            throw new Exception('MsaCrypt: payload is truncated or not valid base64');
        }

        $iv  = substr($blob, 0, self::IV_LEN);
        $mac = substr($blob, self::IV_LEN, self::MAC_LEN);
        $ct  = substr($blob, self::IV_LEN + self::MAC_LEN);

        // Verify before decrypting.
        $expected = hash_hmac('sha256', $iv . $ct, self::macKey($master), true);
        if (!self::hashEquals($expected, $mac)) {
            throw new Exception('MsaCrypt: MAC check failed (wrong master key or payload tampered)');
        }

        $pt = openssl_decrypt($ct, self::CIPHER, self::encKey($master), OPENSSL_RAW_DATA, $iv);
        if ($pt === false) {
            throw new Exception('MsaCrypt: openssl_decrypt failed');
        }
        return $pt;
    }

    /**
     * Read an env var and decrypt its enc:v1: payload.
     * Pass $requireEncrypted = false to also accept a plaintext value.
     */
    public static function secret($envName, $requireEncrypted = true)
    {
        $val = self::env($envName);
        if ($val === null || $val === '') {
            throw new Exception('MsaCrypt: env var ' . $envName . ' is not set');
        }

        if (strpos($val, self::PREFIX) === 0) {
            return self::decrypt($val);
        }

        if ($requireEncrypted) {
            throw new Exception('MsaCrypt: env var ' . $envName . ' does not start with '
                . self::PREFIX . ' - check for quotes or whitespace around the value');
        }
        return $val;
    }

    /** $_SERVER covers nginx fastcgi_param, which getenv() does not see. */
    public static function env($name)
    {
        $v = getenv($name);
        if ($v !== false && $v !== '') { return $v; }
        if (isset($_ENV[$name]) && $_ENV[$name] !== '') { return $_ENV[$name]; }
        if (isset($_SERVER[$name]) && $_SERVER[$name] !== '') { return $_SERVER[$name]; }
        return null;
    }

    /** Optional .env reader for repos with no framework. Never overwrites real env. */
    public static function loadEnvFile($path)
    {
        $real = realpath($path);
        if ($real === false || isset(self::$envFileLoaded[$real])) { return false; }
        self::$envFileLoaded[$real] = true;

        $lines = file($real, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines === false) { return false; }

        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || $line[0] === '#') { continue; }
            $pos = strpos($line, '=');
            if ($pos === false) { continue; }

            $k = trim(substr($line, 0, $pos));
            $v = trim(substr($line, $pos + 1));
            $len = strlen($v);
            if ($len >= 2 && (($v[0] === '"' && $v[$len-1] === '"') || ($v[0] === "'" && $v[$len-1] === "'"))) {
                $v = substr($v, 1, -1);
            }
            if ($k === '' || self::env($k) !== null) { continue; }
            putenv($k . '=' . $v);
            $_ENV[$k] = $v;
        }
        return true;
    }

    /** random_bytes() is PHP 7.0+; openssl fallback for older. */
    public static function randomBytes($n, $forceLegacy = false)
    {
        if (!$forceLegacy && function_exists('random_bytes')) {
            return random_bytes($n);
        }
        $strong = false;
        $b = openssl_random_pseudo_bytes($n, $strong);
        if ($b === false || $strong !== true) {
            throw new Exception('MsaCrypt: no cryptographically strong RNG available');
        }
        return $b;
    }

    /** hash_equals() is PHP 5.6+; constant-time fallback for older. */
    public static function hashEquals($a, $b, $forceLegacy = false)
    {
        if (!$forceLegacy && function_exists('hash_equals')) {
            return hash_equals($a, $b);
        }
        if (strlen($a) !== strlen($b)) { return false; }
        $r = 0;
        for ($i = 0, $n = strlen($a); $i < $n; $i++) { $r |= ord($a[$i]) ^ ord($b[$i]); }
        return $r === 0;
    }

    /** Test seam: round trip forced down the PHP 5.4 code paths. */
    public static function selfTestLegacyPaths($plaintext, $master)
    {
        $iv  = self::randomBytes(self::IV_LEN, true);
        $ct  = openssl_encrypt($plaintext, self::CIPHER, self::encKey($master), OPENSSL_RAW_DATA, $iv);
        if ($ct === false) { throw new Exception('MsaCrypt: openssl_encrypt failed'); }
        $mac = hash_hmac('sha256', $iv . $ct, self::macKey($master), true);

        $expected = hash_hmac('sha256', $iv . $ct, self::macKey($master), true);
        if (!self::hashEquals($expected, $mac, true)) {
            throw new Exception('MsaCrypt: legacy MAC compare failed');
        }
        $pt = openssl_decrypt($ct, self::CIPHER, self::encKey($master), OPENSSL_RAW_DATA, $iv);
        if ($pt === false) { throw new Exception('MsaCrypt: openssl_decrypt failed'); }
        return $pt;
    }

    /** Test seam. */
    public static function resetCache() { self::$masterCache = null; }
}
