As the first step for generating a secret DH key a uniformly distributed random number $k$ must be generated, which is used to calculate the $k$-th exponent of the basepoint $A$. Depending on the group order $n$, $k$ can be between $1 \ldots n-1$ .
The binary representation length of the group order is 32 Bytes in my case, but not all bits of those $32 \cdot 8=256$ bits are used, since the group order is slightly smaller than the prime $p$, and also $p$ is smaller than $2^{256}-1$ . Therefore if I generate a 32 Byte random number $k$ , sometimes it is larger than $n$. When this happens, is it allowed to take the modulo $n$ of this number to get a new randon number
$k' = k \,\, mod \,\, n$
and use that instead? I was told to do it in that way.
First I was tempted to confirm that, but then I see that the upper end of the intervall $1 \ldots 2^{256}-1$, namely $n \ldots 2^{256}-1$ is mapped back into $1 \ldots 2^{256}-1-n$ . And therefore the distribution of random numbers for the target interval is not uniform anymore, since each representative within the interval $1 \ldots 2^{2561}-1-n$ is double-weighted - one time from the original interval and another time from the mapped back interval, so the odds for this interval are doubled as compared to numbers outside the interval. And what to do with $k'=0$, when $k=n$ ?
The other option would be to generate a random number exaktly between 1 and n-1.
Since I'm not 100% sure but this was a tip from a really experienced crypto-programmer I'm wavered between the two options...