4 ms·
If you really want a minimum implementation that you can understand for educational purposes, perhaps you could try djb's original Curve25519 library to compute
by segfaultbuserr 7y ago
If you really want a minimum implementation that you can understand for educational purposes, perhaps you could try djb's original Curve25519 library to compute a shared-secret. It's extremely simple, a Diffie-Hellman exchange can be implemented within 30 lines of C by calling the library. I think nobody really uses it, but it's the reference implementation of the Curve25519 paper. WARNING: This implementation is probably not secured against side-channel attacks on a modern CPU, offline-use only. https://cr.yp.to/ecdh.html https://cr.yp.to/ecdh.html
1. Computing secret keys. Inside your program, to generate a 32-byte Curve25519 secret key, start by generating 32 secret random bytes from a cryptographically safe source: mysecret[0], mysecret[1], ..., mysecret[31]. Then do
mysecret[0] &= 248;
mysecret[31] &= 127;
mysecret[31] |= 64;
to create a 32-byte Curve25519 secret key mysecret[0], mysecret[1], ..., mysecret[31].
2. Computing public keys. To generate the corresponding 32-byte Curve25519 public key mypublic[0], mypublic[1], ..., mypublic[31], call
curve25519(mypublic,mysecret,basepoint);
where the constant basepoint is 9 followed by all zeros:
const unsigned char basepoint[32] = {9};
3. Computing shared secrets. Given someone else's Curve25519 public key hispublic[0], hispublic[1], ..., hispublic[31], call
curve25519(shared,mysecret,hispublic);
Done, you've just got a shared secret. Then you can use standard tools like OpenSSL or "gpg --symmetric" to encrypt the data using AES with that key.
But seriously, just use libsodium. It has received extensive audits, its abstraction model is easy to use and understand, while mistakes are hard to make.