Random numbers used for ECC Diffie-Hellman
Your analysis is correct, generating a random 32 Bytes number and reducing it modulo $n$ gives an incorrect distribution (in general). I see three natural solutions to this issue: (I'm not a programmer and do not know which one would be the most suited for efficiency)

1) Generate the random number directly between $1$ and $n-1$ as you suggested

2) Generate a random $32+\kappa$ Byes number, where $\kappa$ is a security parameter (e.g. $\kappa = 10$ for 80 bits of security), and reduce it modulo $n$. This gives a distribution statistically close to uniform over $[1, n]$

Explanation: so, you have this $256$ bit modulus $n$, and you pick (say) a random $336$ bits integer. You do not obtain a uniform distribution by reducing it modulo $n$, but "almost": let us write $2^{336} = n \times N + R$, with $R &lt; n$ ($N,R$ are the quotient and remainder of the Euclidean division by $n$). Intuitively, if we had generated our number between $1$ and $n \times N$, we would indeed have obtained a uniform distribution when reducing it modulo $n$ (as it is a multiple of $n$). The bad case happens when the random number we generate is between $n\times N + 1$ and $2^{336}$. But this happens with probability at most $R/2^{336} &lt; 2^{256}/2^{336} = 2^{-80}$, which is extremely unlikely. Thus, by adding some security parameter to the size of the sampled bit strings, you ensure that you'll get a distribution statistically close to uniform.

As poncho pointed out in a comment, when $n$ is already chosen very close to $2^{256}$, then there is no need to add such "security bits", taking a random 256 bits number will already give something close to uniform (my answer focused on the most general case).

3) Generate 32 Bytes integers and use rejection sampling: if a number is higher than $n$, ignore it and restart until you get a number smaller than $n$. This gives a uniform distribution over $[1,n]$ and is efficient if $n$ is very close to $2^{256}-1$

Any of those solution should be a proper fix to the problem; the direct modulo reduction seem theoretically unacceptable to me (but might be accepted on the basis that it still provides some good security level in practice, enough at least to circumvent any known attack, even though it's a bit dirty).

EDIT: the case $k'=0$ when $k=n$ that you mention is not a problem as it has a negligible probability to happen.