ChaCha20.h 862 B

1234567891011121314151617181920212223242526272829303132
  1. /*
  2. * Copyright (c) 2022, stelar7 <dudedbz@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. namespace Crypto::Cipher {
  9. class ChaCha20 {
  10. static constexpr u32 CONSTANT_16_BYTES[] { 0x61707865, 0x3120646E, 0x79622D36, 0x6B206574 };
  11. static constexpr u32 CONSTANT_32_BYTES[] { 0x61707865, 0x3320646E, 0x79622D32, 0x6B206574 };
  12. public:
  13. ChaCha20(ReadonlyBytes key, ReadonlyBytes nonce, u32 initial_counter = 0);
  14. void encrypt(ReadonlyBytes input, Bytes& output);
  15. void decrypt(ReadonlyBytes input, Bytes& output);
  16. void generate_block();
  17. ReadonlyBytes block() const { return { m_block, 64 }; }
  18. private:
  19. void run_cipher(ReadonlyBytes input, Bytes& output);
  20. ALWAYS_INLINE void do_quarter_round(u32& a, u32& b, u32& c, u32& d);
  21. u32 m_state[16] {};
  22. u32 m_block[16] {};
  23. };
  24. }