Skip to content
CryoCryo home
Stdlibhash

hmac

import std::hash::hmac; · source

Keyed message authentication codes (RFC 2104) over SHA-256 and SHA-1.

HmacSha256 (HmacSha1) authenticates a message that arrives in pieces — new(key), update, then finish — or one held whole (mac), giving the code as a Sha256Digest (Sha1Digest). A key longer than a block is hashed first. verify recomputes a code and compares it with one received in time that does not depend on where they differ, which is how a received code must be checked: comparing with == stops at the first different byte and tells a caller how much of a forgery was right.

import std::hash::{ HmacSha256, Sha256Digest };

function main() -> int {
    const key: Str = "key";
    const message: Str = "The quick brown fox jumps over the lazy dog";
    const tag: Sha256Digest = HmacSha256::mac(key.as_bytes(), message.as_bytes());
    // tag.to_hex() == "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
    const ok: boolean = HmacSha256::verify(key.as_bytes(), message.as_bytes(), tag.as_bytes());
    return if (ok) { 0 } else { 1 };
}

Types

HmacSha256

type struct HmacSha256 {
    private inner:     Sha256;
    private outer_key: [u8; 64];
}

Constructors

static new(key: &Slice<u8>) -> HmacSha256;

A code under key over the empty message.

Static functions

static mac(key: &Slice<u8>, data: &Slice<u8>) -> Sha256Digest;

The code under key of data, a message held whole.

static verify(key: &Slice<u8>, data: &Slice<u8>, tag: &Slice<u8>) -> boolean;

Whether tag is the code under key of data, compared in time that does not depend on where a wrong tag differs.

Methods

update(mut &this, data: &Slice<u8>) -> void;

Append data to the message.

finish(mut this) -> Sha256Digest;

The code of the message fed so far.

HmacSha1

type struct HmacSha1 {
    private inner:     Sha1;
    private outer_key: [u8; 64];
}

Constructors

static new(key: &Slice<u8>) -> HmacSha1;

A code under key over the empty message.

Static functions

static mac(key: &Slice<u8>, data: &Slice<u8>) -> Sha1Digest;

The code under key of data, a message held whole.

static verify(key: &Slice<u8>, data: &Slice<u8>, tag: &Slice<u8>) -> boolean;

Whether tag is the code under key of data, compared in time that does not depend on where a wrong tag differs.

Methods

update(mut &this, data: &Slice<u8>) -> void;

Append data to the message.

finish(mut this) -> Sha1Digest;

The code of the message fed so far.