wrapper-open.cpp 1.1 KB

123456789101112131415161718192021222324252627
  1. #include <string>
  2. using std::string;
  3. #include "crypto_box.h"
  4. string crypto_box_open(const string &c,const string &n,const string &pk,const string &sk)
  5. {
  6. if (pk.size() != crypto_box_PUBLICKEYBYTES) throw "incorrect public-key length";
  7. if (sk.size() != crypto_box_SECRETKEYBYTES) throw "incorrect secret-key length";
  8. if (n.size() != crypto_box_NONCEBYTES) throw "incorrect nonce length";
  9. size_t clen = c.size() + crypto_box_BOXZEROBYTES;
  10. unsigned char cpad[clen];
  11. for (int i = 0;i < crypto_box_BOXZEROBYTES;++i) cpad[i] = 0;
  12. for (int i = crypto_box_BOXZEROBYTES;i < clen;++i) cpad[i] = c[i - crypto_box_BOXZEROBYTES];
  13. unsigned char mpad[clen];
  14. if (crypto_box_open(mpad,cpad,clen,
  15. (const unsigned char *) n.c_str(),
  16. (const unsigned char *) pk.c_str(),
  17. (const unsigned char *) sk.c_str()
  18. ) != 0)
  19. throw "ciphertext fails verification";
  20. if (clen < crypto_box_ZEROBYTES)
  21. throw "ciphertext too short"; // should have been caught by _open
  22. return string(
  23. (char *) mpad + crypto_box_ZEROBYTES,
  24. clen - crypto_box_ZEROBYTES
  25. );
  26. }