# Are developers expected to implement Diffie-Hellman key exchange themselves?

I noticed that the GO standard library has some really nice functions for performing AES encryption / decryption in various modes. However, I couldn't (yet) find anything for Diffie-Hellman key exchange.

I'm not sure if I should proceed by searching more carefully, switching to a different language with a more extensive crypto library, or trying to implement the key exchange protocol myself.

The protocol "seems" implementable:

• Alice sends $g^a \mod p$ to Bob
• Bob sends $g^b \mod p$ to Alice
• We need to choose $g, a, b, p$ appropriately

But I'd bet that there are a lot of subtleties buried in that "straightforward protocol" (for example, we need some out-of-band mechanism to defend against man in the middle attacks).

Plus, one of the first lessons of crypto is don't implement cryptographic primitives yourself, and I don't know if this warrants an exception to that lesson.

Are developers generally expected to implement Diffie-Hellman key exchange themselves? If so, what are the primitives that I should be using, and where can I find a good reference for some of the subtleties that should be considered?

• You should definitely avoid implementing crypto yourself if anyhow possible (nice to have noted that yourself :) Some example subtleties: You need to ensure p is chosen appropriately, you need to ensure a and b are generated sufficiently randomly, you should ensure that the operation is sufficiently fast, you should ensure that an attacker can't deduce your private key from the timing and not to start with the "out of band" methods... – SEJPM Mar 8 '16 at 20:33
• I guess you want to perform some sort of communication. Did you look for a SSL/TLS library for Go? – SEJPM Mar 8 '16 at 20:34
• SEJPM, thanks for the input! I did look at the TLS package, but I'd probably only use SSL/TLS if there are no other options. My main concern here is that I'm implementing something where clients are communicating through an UNtrusted server. Since I'd like to have OTR-like security properties (end-to-end encryption, preservation of forward secrecy even if the server logs all traffic), I'm not sure if TLS alone will be sufficient. – Elliott Mar 8 '16 at 20:40
• TLS can do that if you use the (EC)DHE cipher suites (and if you connect via the server and not to the server). Additionally there is supplemental crypto code here. If you really want to do (EC)DH, I think you may have to implement it yourself (this should be easier with ECC if you always check if points are on curves, use the library for scalar multiplication and hash the agreed value) or (better) switch to another language. – SEJPM Mar 8 '16 at 21:28
• The latter part of the question is off topic as a link/implementation request. The former is sort of on topic, I think. – otus Mar 9 '16 at 7:35