Can I use NaCl's scalar multiplication functions for Diffie Hellman Key Agreement? I want to create some software that performs diffie hellman group key agreement but I don't want to reinvent the wheel even if I know how it's done. So I came accross the NaCl library, especially the scalar_mult functions.

As far I know you can perform Diffie Hellman key agreement on elliptic curves therefore, my thought is if I combine it with crypto_box ones for key generation, I can do a Diffie Hellman Key agreement. 

My Idea is (described in some sort of pseudocode) shown in the following image:



Would you recommend it as shown above?
Yes.

The DH function is $$\operatorname{X25519}(n, p) := x\bigl([\operatorname{clamp}(n)] x^{-1}(\operatorname{decode}(p))\bigr)$$ with scalar multiplication $[\alpha]P$ on the curve $y^2 = x^3 + 486662 x^2 + x$ over the prime field $\operatorname F_{2^{255} - 19}$, where $n$ is 32-byte string representing a private key, and $p$ is a 32-byte string representing a public key.

Here $\operatorname{decode}(p)$ maps a 32-byte string into an element of $\mathbb F_{2^{255} - 19}$, and $\operatorname{clamp}(n)$ maps a uniform random 32-byte string into a uniform random integer in $\{2^{254}, 2^{254} + 8, 2^{254} + 16, \dots, 2^{255} - 8\}$—that is, an integer multiple of 8 between $2^{254}$ and $2^{255} - 1$.

As a DH function, this has the property that $\operatorname{X25519}(n, \operatorname{X25519}(m, \underline 9)) = \operatorname{X25519}(m, \operatorname{X25519}(n, \underline 9))$, where $\underline 9$ is the encoding of the standard base point, whose $x$ coordinate is 9, which means that both parties will arrive at the same shared secret.

The security contract requires that that you must hash the shared secret: use $H(\operatorname{X25519}(n, p))$.  Specifically, the security conjecture is that even if you reveal $\operatorname{X25519}(n, \underline 9)$ and $p \mapsto H(\operatorname{X25519}(n, p))$ for any $p$ of an attacker's choice, then the attacker must spend ${\sim}2^{128}$ bit operations to find any shared secret.  The security contract also requires that you never use $n$ for any purpose except the two crypto_scalarmult functions:


crypto_scalarmult_base(p, n) sets $p$ to the public key $\operatorname{X25519}(n, \underline 9)$.  You may publish $p$.
crypto_scalarmult(q, n, p) sets $q$ to the unhashed shared secret $\operatorname{X25519}(n, p)$, the secret shared between the private key $n$ and the public key $p$.  You must hash $q$ before using it.