<?php
/*
2023-10-28
*/
class CryptoHelper
{
    private static $SECRET_KEY = "vVHEa7hdklV6G0qRahMsWGsfqSrbOAX+Abac43WgI5s=";//44 char secret key
    private static $NONCE_KEY = "/j5ub8L+BTMtnsiK9sJajDtcVXzRcM83"; //32 STRING

    /**
     * Encrypt a message
     * 
     * @param string $message - message to encrypt
     * @return string
     */
    public static function encrypt($message)
    {
        //$key = CryptoHelper::$SECRET_KEY;
        $key = base64_decode(CryptoHelper::$SECRET_KEY);
        //$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $nonce = base64_decode(CryptoHelper::$NONCE_KEY);

        $cipher = base64_encode($nonce.sodium_crypto_secretbox($message,$nonce,$key));
        
        sodium_memzero($message);
        sodium_memzero($key);
        return $cipher;
    }
    
    /**
     * Decrypt a message
     * 
     * @param string $encrypted - message encrypted with safeEncrypt()
     * @return string
     */
    public static function decrypt($encrypted)
    {   
        $key = base64_decode(CryptoHelper::$SECRET_KEY);
        $decoded = base64_decode($encrypted);
        if ($decoded === false) {
            throw new Exception('Scream bloody murder, the encoding failed');
        }
        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
            throw new Exception('Scream bloody murder, the message was truncated');
        }
        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        $plain = sodium_crypto_secretbox_open(
            $ciphertext,
            $nonce,
            $key
        );
        if ($plain === false) {
             throw new Exception('the message was tampered with in transit');
        }
        sodium_memzero($ciphertext);
        sodium_memzero($key);
        return $plain;
    }

}