Nonce Security Implementation

Brief:

Nonce is used to avoid the replay attacks. When any request hits server, the intruder holds that request for some time and then they make some change in the request header so that they try to divert the response of that request to their server side or wherever they want. So that they will get the data.

How It Works:

To avoid the replay attacks, we will generate one token, in that we will send the expiry time and one random key that will be unique for every request when the request hits to the server. Then, before sending a response to the client, the server will check that the request is from valid client by using that token and also that request needs to be completed in the specified time else the server will send response that you are not a validated user.


function generateNonce($timeoutSeconds = NONCE_TIME_OUT) {
    $randomString = self::generateJWTRandomString();
    $time = time();
    $maxTime = $time + $timeoutSeconds;
    $data = $maxTime . "," . $randomString;
    $nonce = self::encryptJWTTocken($data);
    return "<input type='hidden' name='_nonce' value='".$nonce."'/>";
}




Firstly we generate the nonce_token using generateNonce function . In that we will create one string with current time plus the expiry time for token and one random string, Both will concatenate using ', (comma)' operator, and then that complete string will be encrypted by using the JWT encryption methods with our own private key. Then the encrypted string will be stored in the hidden variable in the client side. When any request will be sent to the server, this encrypted string will be sent along with the data.


function checkNonce($nonceClientSide) {
    $secretKey = base64_decode($this->jwtOwnPrivateKey);
    $nonce = JWT::decode($nonceClientSide, $secretKey, array(JWT_ALGORITHM));
    if (is_string($nonce) == false) {
        return false;
    }
    $stringExploid = explode(',', $nonce);
    $maxTime = intval($stringExploid[0]);
    if (time() > $maxTime) {
        return false;
    }
    return true;
}



On sever side call the function checkNonce with the parameter nonce client key, in this function it will decrypt the nonce client key using private key. We will call the function decode from JWT library, that will return the original string. After that we will check if that request is within the given time or not, else it will send FALSE response in return. And then server will send return response as you are not valid user to access this service.

Benefits:

Using the Nonce security method we can secure our request from replay attacks, or we can stop reply attacks on our request hits on server side. So that the response data from server side will be secured.

Podcast

Michael Patterson sat down with the CEO of Boston Byte, Mustapha Shaikh to discuss the significance and rapid digitization of the healthcar...