dimanche 15 novembre 2020

Building a web service to generate an n-long hex string

My goal is to build a Web Service using PHP that, given a number n that represents how many bytes you want returned you get a string of pseudo random hexadecimal numbers. I have it so that it works if I hard code n but when I try to let the client choose the number it returns an error code (I made up error codes for debugging).

Here is the code: <?php

function get_random_bytes($n)
{
    if(is_int($n) && $n > 0)
    {
        $bytes = openssl_random_pseudo_bytes($n, $cstrong);
        $hex   = bin2hex($bytes);
        $hex_up = strtoupper($hex);

        if($cstrong === TRUE)
        {
            return $hex_up;
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return FALSE;
    }
}

function handle_request()
{
    if(empty($_GET[n]))
    {
        return 'EMPTY';
    }
    elseif(!isset($_GET[n]))
    {
        return 'VAR_NOT_SET';
    }
    else
    {
        return $_GET[n];
    }
}

function handle_response($array)
{
    header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header("Pragma: no-cache"); // HTTP/1.0
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

    echo json_encode($array);
}

function main()
{
    $n = handle_request();

    if(!isset($n))
    {
        $array=array("STATUS" => "VAR_NOT_SET");
        handle_response($array);
    }
    elseif(empty($_GET['n']))
    {
        $array = array("STATUS" => "VAR_NOT_SET");
        handle_response($array);
    }
    else
    {
        $bytes = get_random_bytes($n);
        $array = array("random_bytes" => $bytes);
        handle_response($array);
    }
}

main();
?>

When I run this I get the following response on my browser: {"STATUS":"VAR_NOT_SET"}

I'm sure I'm overlooking something obvious but any help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire