poly1305.h (2284B)
1 // chacha20-poly1305: https://www.rfc-editor.org/info/rfc8439/ 2 3 #ifndef POLY1305_H 4 #define POLY1305_H 5 6 #include <assert.h> 7 #include <limits.h> 8 #include <stdalign.h> 9 #include <stddef.h> 10 #include <stdint.h> 11 12 #define POLY1305_ALIGN 64 13 14 typedef uint32_t poly1305_word_t; 15 16 #define POLY1305_WORD_BITS 32 17 #define POLY1305_KEY_BITS 256 18 #define POLY1305_BLOCK_BITS 128 19 #define POLY1305_DIGEST_BITS 128 20 21 #define POLY1305_KEY_WORDS (POLY1305_KEY_BITS / POLY1305_WORD_BITS) 22 #define POLY1305_KEY_SIZE (POLY1305_KEY_BITS / CHAR_BIT) 23 24 #define POLY1305_HALFKEY_WORDS (POLY1305_KEY_WORDS / 2) 25 #define POLY1305_HALFKEY_SIZE (POLY1305_KEY_SIZE / 2) 26 27 #define POLY1305_BLOCK_WORDS (POLY1305_BLOCK_BITS / POLY1305_WORD_BITS) 28 #define POLY1305_BLOCK_SIZE (POLY1305_BLOCK_BITS / CHAR_BIT) 29 #define POLY1305_BLOCK_MASK (POLY1305_BLOCK_SIZE - 1) 30 31 #define POLY1305_DIGEST_WORDS (POLY1305_DIGEST_BITS / POLY1305_WORD_BITS) 32 #define POLY1305_DIGEST_SIZE (POLY1305_DIGEST_BITS / CHAR_BIT) 33 34 // NOTE: our "bignum" is actually stored as 5 26-bit "limbs" of a larger 35 // 130-bit number, and so must fit into 5 32-bit words 36 37 #define POLY1305_BIGNUM_BITS 130 38 #define POLY1305_BIGNUM_LIMBS 5 39 #define POLY1305_LIMB_BITS (POLY1305_BIGNUM_BITS / POLY1305_BIGNUM_LIMBS) 40 static_assert(POLY1305_LIMB_BITS < POLY1305_WORD_BITS, "poly1305 bignum limb doesnt fit into poly1305_word_t"); 41 42 #define POLY1305_BIGNUM_WORDS POLY1305_BIGNUM_LIMBS 43 #define POLY1305_BIGNUM_SIZE \ 44 ((POLY1305_BIGNUM_BITS + (CHAR_BIT - 1)) / CHAR_BIT) 45 46 struct poly1305_ctx { 47 alignas(POLY1305_ALIGN) 48 poly1305_word_t r[POLY1305_BIGNUM_WORDS]; // half of key, r, as bignum 49 poly1305_word_t a[POLY1305_BIGNUM_WORDS]; // accumulator, as bignum 50 poly1305_word_t s[POLY1305_HALFKEY_WORDS]; // half of key, s 51 52 alignas(POLY1305_ALIGN) 53 unsigned char block[POLY1305_BLOCK_SIZE]; 54 size_t ctr; 55 }; 56 57 void 58 poly1305_init(struct poly1305_ctx *ctx, 59 unsigned char const key[static POLY1305_KEY_SIZE]); 60 61 void 62 poly1305_push(struct poly1305_ctx *ctx, void const *buf, size_t len); 63 64 void 65 poly1305_dgst(struct poly1305_ctx *ctx, 66 unsigned char digest[static POLY1305_DIGEST_SIZE]); 67 68 void 69 poly1305(unsigned char const key[static POLY1305_KEY_SIZE], 70 void const *buf, size_t len, 71 unsigned char digest[static POLY1305_DIGEST_SIZE]); 72 73 #endif /* POLY1305_H */