chacha20.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Based on
  3. * 1. OpenSSL lib
  4. * 2. PurpleI2P source code
  5. * 3. cppcodec lib
  6. *
  7. * PUBLIC DOMAIN C++ WRAPPER
  8. * acetone, 2022
  9. */
  10. #include "chacha20.h"
  11. #include <memory>
  12. #include <openssl/evp.h>
  13. namespace FriendlyCrypto {
  14. std::vector<uint8_t> chaCha20 (const std::vector<uint8_t> &msg, const std::array<uint8_t, 32> &key, const uint8_t *nonce) noexcept
  15. {
  16. uint8_t fakenonce[24] {0};
  17. if (!nonce)
  18. {
  19. nonce = fakenonce;
  20. }
  21. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
  22. uint32_t iv[4];
  23. iv[0] = htole32 (1); memcpy (iv + 1, nonce, 12); // counter | nonce
  24. EVP_EncryptInit_ex(ctx, EVP_chacha20(), NULL, key.data(), reinterpret_cast<const uint8_t*>(iv));
  25. std::vector<uint8_t> out(msg.size());
  26. int outlen = msg.size();
  27. EVP_EncryptUpdate(ctx, out.data(), &outlen, msg.data(), msg.size());
  28. EVP_EncryptFinal_ex(ctx, NULL, &outlen);
  29. EVP_CIPHER_CTX_free (ctx);
  30. return out;
  31. }
  32. std::vector<uint8_t> chaCha20 (const uint8_t *msg, size_t msgSize, const std::array<uint8_t, 32> &key, const uint8_t *nonce) noexcept
  33. {
  34. std::vector<uint8_t> vector;
  35. for (size_t i = 0; i < msgSize; ++i)
  36. {
  37. vector.push_back(msg[i]);
  38. }
  39. return chaCha20 (vector, key, nonce);
  40. }
  41. } // namespace