From d1a927a92ecccb1d3616c9c2b8acc8b12facf06d Mon Sep 17 00:00:00 2001 From: MinRK Date: Sun, 29 Sep 2013 13:02:39 -0700 Subject: [PATCH] add zmq_curve_keypair to zmq_utils --- include/zmq_utils.h | 4 ++++ src/zmq_utils.cpp | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/include/zmq_utils.h b/include/zmq_utils.h index 4fe8fcd2..90ae8f88 100644 --- a/include/zmq_utils.h +++ b/include/zmq_utils.h @@ -88,6 +88,10 @@ ZMQ_EXPORT char *zmq_z85_encode (char *dest, uint8_t *data, size_t size); /* Decode data with Z85 encoding. Returns decoded data */ ZMQ_EXPORT uint8_t *zmq_z85_decode (uint8_t *dest, char *string); +/* Generate z85-encoded public and private keypair with libsodium. */ +/* Returns 0 on success. */ +ZMQ_EXPORT int zmq_curve_keypair (char* z85_public_key, char *z85_secret_key); + #undef ZMQ_EXPORT #ifdef __cplusplus diff --git a/src/zmq_utils.cpp b/src/zmq_utils.cpp index 9cef5dec..3f51c0a8 100644 --- a/src/zmq_utils.cpp +++ b/src/zmq_utils.cpp @@ -30,6 +30,10 @@ #else #include "windows.hpp" #endif +#ifdef HAVE_LIBSODIUM +# include +#endif + void zmq_sleep (int seconds_) { @@ -125,7 +129,7 @@ char *zmq_z85_encode (char *dest, uint8_t *data, size_t size) return dest; } - + // -------------------------------------------------------------------------- // Decode an encoded string into a binary frame; dest must be at least // strlen (string) * 4 / 5 bytes long. Returns dest. strlen (string) @@ -153,3 +157,34 @@ uint8_t *zmq_z85_decode (uint8_t *dest, char *string) assert (byte_nbr == strlen (string) * 4 / 5); return dest; } + +// -------------------------------------------------------------------------- +// Generate a public/private keypair with libsodium. +// Generated keys will be 40 byte z85-encoded strings. +// Returns 0 on success, -1 on failure, setting errno. +// Sets errno = ENOTSUP in the absence of libsodium. + +int zmq_curve_keypair (char* z85_public_key, char *z85_secret_key) +{ +#ifdef HAVE_LIBSODIUM +# if crypto_box_PUBLICKEYBYTES != 32 \ + || crypto_box_SECRETKEYBYTES != 32 +# error "libsodium not built correctly" +# endif + + uint8_t public_key [32]; + uint8_t secret_key [32]; + + int rc = crypto_box_keypair (public_key, secret_key); + // is there a sensible errno to set here? + if (rc) return rc; + + zmq_z85_encode (z85_public_key, public_key, 32); + zmq_z85_encode (z85_secret_key, secret_key, 32); + + return 0; +#else // requires libsodium + errno = ENOTSUP; + return -1; +#endif +}