wrapper-open.cpp 974 B

12345678910111213141516171819202122
  1. #include <string>
  2. using std::string;
  3. #include "crypto_secretbox.h"
  4. string crypto_secretbox_open(const string &c,const string &n,const string &k)
  5. {
  6. if (k.size() != crypto_secretbox_KEYBYTES) throw "incorrect key length";
  7. if (n.size() != crypto_secretbox_NONCEBYTES) throw "incorrect nonce length";
  8. size_t clen = c.size() + crypto_secretbox_BOXZEROBYTES;
  9. unsigned char cpad[clen];
  10. for (int i = 0;i < crypto_secretbox_BOXZEROBYTES;++i) cpad[i] = 0;
  11. for (int i = crypto_secretbox_BOXZEROBYTES;i < clen;++i) cpad[i] = c[i - crypto_secretbox_BOXZEROBYTES];
  12. unsigned char mpad[clen];
  13. if (crypto_secretbox_open(mpad,cpad,clen,(const unsigned char *) n.c_str(),(const unsigned char *) k.c_str()) != 0)
  14. throw "ciphertext fails verification";
  15. if (clen < crypto_secretbox_ZEROBYTES)
  16. throw "ciphertext too short"; // should have been caught by _open
  17. return string(
  18. (char *) mpad + crypto_secretbox_ZEROBYTES,
  19. clen - crypto_secretbox_ZEROBYTES
  20. );
  21. }