HMAC and Key Derivation
原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/vgqqwhf8y0on8guf
原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/vgqqwhf8y0on8guf ↗
Simply calculating hash_func(key + msg) to obtain a MAC (message authentication code) is considered insecure (see the details ↗). It is recommended to use the HMAC algorithm instead, e.g. HMAC-SHA256 or HMAC-SHA3-512 or other secure MAC algorithm.
What is HMAC?#
HMAC ↗ = Hash-based Message Authentication Code (MAC code, calculated using a cryptographic hash function):
HMAC(key, msg, hash_func) -> hashpythonThe results MAC code is a message hash mixed with a secret key. It has the cryptographic properties of hashes: irreversible, collision resistant, etc.
The hash_func can be any cryptographic hash function like SHA-256, SHA-512, RIPEMD-160, SHA3-256 or BLAKE2s.
HMAC is used for message authenticity, message integrity and sometimes for key derivation.
Key Derivation Functions (KDF)#
Key derivation function (KDF) is a function which transforms a variable-length password to fixed-length key (sequence of bits):
function(password) -> keypythonAs very simple KDF function, we can use SHA256: just hash the password. Don’t do this, because it is insecure. Simple hashes are vulnerable to dictionary attacks.
As more complicated KDF function, you can derive a password by calculating HMAC(salt, msg, SHA256) using some random value called “salt”, which is stored along with the derived key and used later to derive the same key again from the password.
Using HKDF (HMAC-based key derivation) for key derivation is less secure than modern KDFs, so experts recommend using stronger key derivation functions like PBKDF2 ↗, Bcrypt ↗, Scrypt ↗ and Argon2 ↗. We shall discuss all these KDF functions later.
HMAC Calculation - Example#
To get a better idea of HMAC and how it is calculated, try this online tool: https://www.freeformatter.com/hmac-generator.html ↗

Play with calculating HMAC(‘sample message’, ‘12345’, ‘SHA256’):
HMAC('sample message', '12345', 'SHA256') =
'ee40ca7bc90df844d2f5b5667b27361a2350fad99352d8a6ce061c69e41e5d32'pythonTry the above example yourself.
HMAC Calculation - Examples#
In Python we can calculate HMAC codes as follows (using the hashlib and hmac libraries):
import hashlib, hmac, binascii
def hmac_sha256(key, msg):
return hmac.new(key, msg, hashlib.sha256).digest()
key = b"12345"
msg = b"sample message"
print(binascii.hexlify(hmac_sha256(key, msg)))pythonRun the above code example: https://repl.it/@nakov/HMAC-SHA256-Examples ↗.
The above code will calculate and print the expected HMAC code (like in our previous example):
ee40ca7bc90df844d2f5b5667b27361a2350fad99352d8a6ce061c69e41e5d32bashTry the code yourself and play with it.
知识图谱
当前文档、同目录指南与引用关系。
正在构建知识图谱...