訊息認證碼 hmac

2021-08-09 17:58:21 字數 2151 閱讀 6391

hmac (hash message authentication code) 是用來確認訊息的完整性及認證訊息的傳送者的技術

完整性,是通過判斷hash值來確定的

認證,是通過對稱密碼的金鑰來完成的

因為是對稱密碼,所以傳送發和接收方事先需要共享金鑰

公式:

hmac = hash(msg, key)

傳送方傳送 msg + hmac

接收方利用公式 hash(msg, key)計算出hmac,然後與接收到的hmac進行對比,如果相同則可確定訊息沒有被篡改,且是傳送者傳送的

macos 上**封裝

標頭檔案 hmac.h

#ifndef hmac_h

#define hmac_h

#include

#include

class hmac final ;

public:

typedef

std::vector

data;

public:

static data md5(const data &msg, const data &key);

static data sha1(const data &msg, const data &key);

public:

~hmac();

hmac(algorithm alg, const data &key);

hmac(hmac &&hmac) noexcept;

hmac &operator=(hmac &&hmac) noexcept;

void update(const data &data);

data final();

private:

struct hmacimpl *_impl = nullptr;

};#endif /* hmac_h */

實現檔案 hmac.cpp

#include "hmac.h"

#include

#include

struct hmacimpl final

cchmacinit(&_ctx, hmacalg, key, keylength);

}void update(const hmac::data &data)

hmac::data final()

private:

cchmaccontext _ctx;

hmac::data _hmac;

};#pragma mark -

hmac::~hmac()

hmac::hmac(algorithm alg, const data &key)

: _impl(new hmacimpl(alg, key.data(), key.size()))

hmac::hmac(hmac &&hmac) noexcept : _impl(hmac._impl)

hmac &hmac::operator=(hmac &&hmac) noexcept

void hmac::update(const data &data)

hmac::data hmac::final()

#pragma mark -

hmac::data hmac::md5(const data &msg, const data &key)

hmac::data hmac::sha1(const data &msg, const data &key)

示例:

#include

<

string

>

#include

"hmac.h"

int main()

; // 一般是對稱密碼的金鑰

std::string msg =

"hello, world";

hmac::data

data(msg.cbegin(), msg.cend());

auto sha1_mac = hmac::sha1(data, key);

auto md5_mac = hmac::md5(data, key);

// ...

}

訊息認證碼 CMAC

於nist的標準 recommendation for block cipher modes of operation the cmac mode for authentication nist 基於分組密碼cbc模式的 訊息認證碼,最後乙個分組 可能需要填充填充10.0 與子金鑰異或後參與cbc模...

訊息認證碼(MAC)

訊息認證碼 帶密碼的hash 能提取訊息的 指紋 訊息認證碼 mac message authentication code 是種訊息認證技術。傳送方a和接收方b共享金鑰 k,若a向b傳送訊息。則a計算利用c f k,m 計算mac值 然後將原始訊息m和c一起傳送給接收方。接收方b對收到的訊息m用相...

資料完整性演算法 訊息認證碼 2

訊息認證函式 任何訊息認證或數字簽名都有上下兩層,下層有產生認證符的函式,認證符是乙個用來認證訊息的值,上層協議將該函式作為原語使接收方可以驗證訊息的真實性。產生認證符的函式有哪些?訊息加密 訊息加密提供了一種認證手段,對稱密碼和公鑰密碼體制中對訊息加密的方法是不同的,下面的我們先談談公鑰加密 直接...