crypto_format.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* Copyright (c) 2012-2013, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /* Formatting and parsing code for crypto-related data structures. */
  4. #define CRYPTO_CURVE25519_PRIVATE
  5. #include "orconfig.h"
  6. #ifdef HAVE_SYS_STAT_H
  7. #include <sys/stat.h>
  8. #endif
  9. #include "crypto.h"
  10. #include "crypto_curve25519.h"
  11. #include "util.h"
  12. #include "torlog.h"
  13. int
  14. curve25519_public_to_base64(char *output,
  15. const curve25519_public_key_t *pkey)
  16. {
  17. char buf[128];
  18. base64_encode(buf, sizeof(buf),
  19. (const char*)pkey->public_key, CURVE25519_PUBKEY_LEN);
  20. buf[CURVE25519_BASE64_PADDED_LEN] = '\0';
  21. memcpy(output, buf, CURVE25519_BASE64_PADDED_LEN+1);
  22. return 0;
  23. }
  24. int
  25. curve25519_public_from_base64(curve25519_public_key_t *pkey,
  26. const char *input)
  27. {
  28. size_t len = strlen(input);
  29. if (len == CURVE25519_BASE64_PADDED_LEN - 1) {
  30. /* not padded */
  31. return digest256_from_base64((char*)pkey->public_key, input);
  32. } else if (len == CURVE25519_BASE64_PADDED_LEN) {
  33. char buf[128];
  34. if (base64_decode(buf, sizeof(buf), input, len) != CURVE25519_PUBKEY_LEN)
  35. return -1;
  36. memcpy(pkey->public_key, buf, CURVE25519_PUBKEY_LEN);
  37. return 0;
  38. } else {
  39. return -1;
  40. }
  41. }