How to Create and Use Nonces

How to create and use nonces

It's actually quite easy to do... There are some libraries out there to do it for you:

  1. PHP Nonce Library
  2. OpenID Nonce Library

Or if you want to write your own, it's pretty simple. Using the WikiPedia page as a jumping off point, In pseudo-code:

On the server side, you need two client callable functions

getNonce() {
$id = Identify Request //(either by username, session, or something)
$nonce = hash('sha512', makeRandomString());
storeNonce($id, $nonce);
return $nonce to client;
}

verifyNonce($data, $cnonce, $hash) {
$id = Identify Request
$nonce = getNonce($id); // Fetch the nonce from the last request
removeNonce($id, $nonce); //Remove the nonce from being used again!
$testHash = hash('sha512',$nonce . $cnonce . $data);
return $testHash == $hash;
}

And on the client side:

sendData($data) {
$nonce = getNonceFromServer();
$cnonce = hash('sha512', makeRandomString());
$hash = hash('sha512', $nonce . $cnonce . $data);
$args = array('data' => $data, 'cnonce' => $cnonce, 'hash' => $hash);
sendDataToClient($args);
}

The function makeRandomString really just needs to return a random number or string. The better the randomness, the better the security... Also note that since it's fed right into a hash function, the implementation details don't matter from request to request. The client's version and the server's version don't need to match. In fact, the only bit that needs to match 100% is the hash function used in hash('sha512', $nonce . $cnonce . $data);... Here's an example of a reasonably secure makeRandomString function...

function makeRandomString($bits = 256) {
$bytes = ceil($bits / 8);
$return = '';
for ($i = 0; $i < $bytes; $i++) {
$return .= chr(mt_rand(0, 255));
}
return $return;
}

How to use nonce in a login system using php to avoid replay attack?

<?php
session_start();
//Check nonce against session
if(isset($_POST) && $_POST["nonce"] === $_SESSION["csrf"]){
//save data
//redirect
}
//generate new nonce for form
$_SESSION["csrf"] = uniqid(mt_rand(),true);
?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>">
<input type="hidden" name="nonce" value="<?php echo $_SESSION['csrf']; ?>"/>
<!-- other form fields -->
<!-- submit button -->
</form>

What is the standard method for generating a nonce in Python?

Here's how python-oauth2 does it:

def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])

They also have:

@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))

Additionally there is this issue entitled: "make_nonce is not random enough", which proposes:

def gen_nonce(length):
""" Generates a random string of bytes, base64 encoded """
if length < 1:
return ''
string=base64.b64encode(os.urandom(length),altchars=b'-_')
b64len=4*floor(length,3)
if length%3 == 1:
b64len+=2
elif length%3 == 2:
b64len+=3
return string[0:b64len].decode()

And also references CVE-2013-4347. TL;DR version, use os.urandom or the abstracted interface to it (SystemRandom).

I like my lambdas—and didn't want non-alphanumeric characters—so I used this:

lambda length: filter(lambda s: s.isalpha(), b64encode(urandom(length * 2)))[:length]

what is nonce in the api client

The NIST glossary defines a nonce as follows:

"A time-varying value that has at most a negligible chance of repeating, for example, a random value that is generated anew for each use, a timestamp, a sequence number, or some combination of these."

Source: https://csrc.nist.gov/glossary/term/nonce

See also:

  • How to create and use nonces

Nonce values are typically used in security related use-cases to help defend against replay attacks.


It is not obvious (to me) how the nonce should be generated and used for your particular use-case. However, for it to be effective, it needs to be part of the message that is being hashed.

Generate nonce c++

I am wondering if there is a way to generate a cryptographic nonce using OpenSSL or Crypto++ libraries.

Crypto++:

SecByteBlock nonce(16);
AutoSeededRandomPool prng;

prng.GenerateBlock(nonce, nonce.size());

OpenSSL:

unsigned char nonce[16];
int rc = RAND_bytes(nonce, sizeof(nonce));
unsigned long err = ERR_get_error();

if(rc != 1) {
/* RAND_bytes failed */
/* `err` is valid */
}

/* OK to proceed */

Is there anything more to it than just generating a set of random bytes using autoseeded pools?

A nonce is basically an IV. Its usually considered a public parameter, like an IV or a Salt.

A nonce must be unique within a security context. You may need a nonce to be unpredictable, too.

Uniqueness and unpredictability are two different properties. For example, a counter starting at 0000000000000000 is unique, but its also predictable.

When you need both uniqueness and unpredictability, you can partition the nonce into a random value and a counter. The random value will take up 8 bytes of a 16 byte nonce; while the counter will take up the remaining 8 bytes of a 16 byte nonce. Then you use an increment function to basically perform i++ each time you need a value.

You don't need an 8-8 split. 12-4 works, as does 4-12. It depends on the application and the number of nonces required before rekeying. Rekeying is usually driven by plain text byte counts.

16-0 also works. In this case, you're using random values, avoiding the counter, and avoiding the increment function. (The increment function is basically a cascading add).

NIST SP800-38C and SP800-38D offer a couple of methods for creating nonces because CCM and GCM uses them.

Also see What are the requirements of a nonce? on the Crypto Stack Exchange.

How to use a generated nonce in NodeJS and do validation without a database call?

It's always better practise to have a database to store and validate the nonce. To restrict with time, either you can use a mongodb with expiry or you can generate the timestamp, then generate a hmac with timestamp, nonce & private key. Then send the nonce, timestamp & hmac to the client. This way you can secure the timestamp as well you can restrict the nonce with particular time if your database is not supporting the document expiry as mongodb. Hope it explains.

How to generate a nonce in node.js?

Just to confirm that indeed this does work in NodeJS for CSP nonces

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');

AES: Use nonce to create new key for HMAC

There are many ways to solve this. The easiest would be to use hashing. You can use HMAC or even HKDF.

SessionKey = HMAC_SHA256(SecretKey, Nonce)

Be sure to use the user's SecretKey only for deriving other keys. If you want to use this derivation for different things, then you need to bind the uses into the key:

SessionKey = HMAC_SHA256(SecretKey, "Encryption".Concat(Nonce))
SessionToken = HMAC_SHA256(SecretKey, "Token".Concat(Nonce))

This is just pseudo-code. Here are some examples of actual HMAC in C#.

How to associate nonce attribute random id with inline JavaScript

https://www.w3.org/TR/CSP3/#security-nonces says that you should generate a unique value every time you submit your policy. This means that you can reuse the nonce throughout the document. On the next page load you need a new nonce.



Related Topics



Leave a reply



Submit