aboutsummaryrefslogtreecommitdiff
path: root/src/crypto/poly1305.h
diff options
context:
space:
mode:
authorPieter Wuille <pieter@wuille.net>2023-07-10 14:32:17 -0400
committerPieter Wuille <pieter@wuille.net>2023-07-12 22:40:55 -0400
commit40e6c5b9fce92ffe64e91c2aba38bb2ed57bfbfb (patch)
tree1a55dbdccfa81563518e70c72bc2080d198744c5 /src/crypto/poly1305.h
parent50269b391fa18556bad72dc8c2fb4e2493a6a054 (diff)
downloadbitcoin-40e6c5b9fce92ffe64e91c2aba38bb2ed57bfbfb.tar.xz
crypto: add Poly1305 class with std::byte Span interface
Diffstat (limited to 'src/crypto/poly1305.h')
-rw-r--r--src/crypto/poly1305.h37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/crypto/poly1305.h b/src/crypto/poly1305.h
index 39b69e1cd4..080543ffee 100644
--- a/src/crypto/poly1305.h
+++ b/src/crypto/poly1305.h
@@ -5,6 +5,9 @@
#ifndef BITCOIN_CRYPTO_POLY1305_H
#define BITCOIN_CRYPTO_POLY1305_H
+#include <span.h>
+
+#include <cassert>
#include <cstdlib>
#include <stdint.h>
@@ -32,6 +35,40 @@ void poly1305_finish(poly1305_context *st, unsigned char mac[16]) noexcept;
} // namespace poly1305_donna
+/** C++ wrapper with std::byte Span interface around poly1305_donna code. */
+class Poly1305
+{
+ poly1305_donna::poly1305_context m_ctx;
+
+public:
+ /** Length of the output produced by Finalize(). */
+ static constexpr unsigned TAGLEN = POLY1305_TAGLEN;
+
+ /** Length of the keys expected by the constructor. */
+ static constexpr unsigned KEYLEN = POLY1305_KEYLEN;
+
+ /** Construct a Poly1305 object with a given 32-byte key. */
+ Poly1305(Span<const std::byte> key) noexcept
+ {
+ assert(key.size() == KEYLEN);
+ poly1305_donna::poly1305_init(&m_ctx, UCharCast(key.data()));
+ }
+
+ /** Process message bytes. */
+ Poly1305& Update(Span<const std::byte> msg) noexcept
+ {
+ poly1305_donna::poly1305_update(&m_ctx, UCharCast(msg.data()), msg.size());
+ return *this;
+ }
+
+ /** Write authentication tag to 16-byte out. */
+ void Finalize(Span<std::byte> out) noexcept
+ {
+ assert(out.size() == TAGLEN);
+ poly1305_donna::poly1305_finish(&m_ctx, UCharCast(out.data()));
+ }
+};
+
void poly1305_auth(unsigned char out[POLY1305_TAGLEN], const unsigned char *m, size_t inlen,
const unsigned char key[POLY1305_KEYLEN]);