Skip to content

x.crypto.poly1305 #

poly1305

Poly1305 is a one-time authenticator originally designed by D. J. Bernstein. Poly1305 takes a 32-byte one-time key and a message and produces a 16-byte tag. It can be used to verify the data integrity and the authenticity of a message.

This module provides generic poly1305 message authentication code (MAC) module in pure V.

As a note, a key must only be used for a single message. Authenticating two different messages with the same key allows an attacker to forge authenticators for other messages with the same key.

[!Warning] > This is an experimental module, which is subject to change, please use it carefully and thoroughly

Examples

module main

import encoding.hex
import x.crypto.poly1305

fn main() {
    // this examples mostly based on rfc
    // provide yours secure key
    yourkey := '0000000000000000000000000000000036e5f6b5c5e06070f0efca96227a863e'
    key := hex.decode(yourkey)!

    // messages to be authenticated
    msg := 'Sample messages'.bytes()

    mut out := []u8{len: 16}
    // lets create tag (mac) stored into out
    poly1305.create_tag(mut out, msg, key)!
    status := poly1305.verify_tag(out, msg, key)
    assert status == true
}

fn create_tag #

fn create_tag(mut out []u8, msg []u8, key []u8) !

create_tag generates 16 bytes tag, i.e., a one-time message authenticator code (mac) stored into out. It accepts the message bytes to be authenticated and the 32 bytes of the key. This is an oneshot function to create a tag and reset internal state after the call. For incremental updates, use the method based on Poly1305 mac instance.

fn new #

fn new(key []u8) !&Poly1305

new creates a new Poly1305 mac instance from 32 bytes of key provided.

fn verify_tag #

fn verify_tag(tag []u8, msg []u8, key []u8) bool

verify_tag verifies the tag is a valid message authentication code for the msg compared to the tag output from the calculated process. It returns true if two tags is matching, false otherwise.

fn (Poly1305) update #

fn (mut po Poly1305) update(msg []u8)

update updates internal of Poly1305 state by message.

fn (Poly1305) verify #

fn (po Poly1305) verify(tag []u8) bool

verify verifies if the tag is a valid message authenticated code for current state of Poly1305 instance. Internally, it works on clone of the current instance.

fn (Poly1305) finish #

fn (mut po Poly1305) finish(mut out []u8)

finish finalizes the message authentication code calculation and stores the result into out. After calls this method, don't use the instance anymore to do most anything, but, you should reinitialize the instance with the new key with .reinit method instead.

fn (Poly1305) reinit #

fn (mut po Poly1305) reinit(key []u8)

reinit reinitializes Poly1305 mac instance by resetting internal fields, and then reinit instance with the new key.