HMAC

HMAC-SHA1 generation

In cryptography, an HMAC (sometimes expanded as either keyed-hash message authentication code or hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key. As with any MAC, it may be used to simultaneously verify both the data integrity and authenticity of a message. An HMAC is a type of keyed hash function that can also be used in a key derivation scheme or a key stretching scheme.

HMAC can provide authentication using a shared secret instead of using digital signatures with asymmetric cryptography. It trades off the need for a complex public key infrastructure by delegating the key exchange to the communicating parties, who are responsible for establishing and using a trusted channel to agree on the key prior to communication.

Details

Any cryptographic hash function, such as SHA-2 or SHA-3, may be used in the calculation of an HMAC; the resulting MAC algorithm is termed HMAC-x, where x is the hash function used (e.g. HMAC-SHA256 or HMAC-SHA3-512). The cryptographic strength of the HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output, and the size and quality of the key.[1]

HMAC uses two passes of hash computation. Before either pass, the secret key is used to derive two keys – inner and outer. Next, the first pass of the hash algorithm produces an internal hash derived from the message and the inner key. The second pass produces the final HMAC code derived from the inner hash result and the outer key. Thus the algorithm provides better immunity against length extension attacks.

An iterative hash function (one that uses the Merkle–Damgård construction) breaks up a message into blocks of a fixed size and iterates over them with a compression function. For example, SHA-256 operates on 512-bit blocks. The size of the output of HMAC is the same as that of the underlying hash function (e.g., 256 and 512 bits in the case of SHA-256 and SHA3-512, respectively), although it can be truncated if desired.

HMAC does not encrypt the message. Instead, the message (encrypted or not) must be sent alongside the HMAC hash. Parties with the secret key will hash the message again themselves, and if it is authentic, the received and computed hashes will match.

The definition and analysis of the HMAC construction was first published in 1996 in a paper by Mihir Bellare, Ran Canetti, and Hugo Krawczyk,[1][2] and they also wrote RFC 2104 in 1997.[3]: §2  The 1996 paper also defined a nested variant called NMAC (Nested MAC). FIPS PUB 198 generalizes and standardizes the use of HMACs.[4] HMAC is used within the IPsec,[2] SSH and TLS protocols and for JSON Web Tokens.

Definition

This definition is taken from RFC 2104:

where

is a cryptographic hash function.
is the message to be authenticated.
is the secret key.
is a block-sized key derived from the secret key, K; either by padding to the right with 0s up to the block size, or by hashing down to less than or equal to the block size first and then padding to the right with zeros.
denotes concatenation.
denotes bitwise exclusive or (XOR).
is the block-sized outer padding, consisting of repeated bytes valued 0x5c.
is the block-sized inner padding, consisting of repeated bytes valued 0x36.[3]: §2 
Hash function H b, bytes L, bytes
MD5 64 16
SHA-1 64 20
SHA-224 64 28
SHA-256 64 32
SHA-512/224 128 28
SHA-512/256 128 32
SHA-384 128 48
SHA-512 128 64[5]
SHA3-224 144 28
SHA3-256 136 32
SHA3-384 104 48
SHA3-512 72 64[6]
out = H(in)
L = length(out)
b = H's internal block length[3]: §2 

Implementation

The following pseudocode demonstrates how HMAC may be implemented. The block size is 512 bits (64 bytes) when using one of the following hash functions: SHA-1, MD5, RIPEMD-128.[3]: §2 

function hmac is
    input:
        key:        Bytes    // Array of bytes
        message:    Bytes    // Array of bytes to be hashed
        hash:       Function // The hash function to use (e.g. SHA-1)
        blockSize:  Integer  // The block size of the hash function (e.g. 64 bytes for SHA-1)
        outputSize: Integer  // The output size of the hash function (e.g. 20 bytes for SHA-1)

    // Compute the block sized key
    block_sized_key = computeBlockSizedKey(key, hash, blockSize)

    o_key_pad ← block_sized_key xor [0x5c blockSize]   // Outer padded key
    i_key_pad ← block_sized_key xor [0x36 blockSize]   // Inner padded key

    return  hash(o_key_pad ∥ hash(i_key_pad ∥ message))

function computeBlockSizedKey is
    input:
        key:        Bytes    // Array of bytes
        hash:       Function // The hash function to use (e.g. SHA-1)
        blockSize:  Integer  // The block size of the hash function (e.g. 64 bytes for SHA-1)
 
    // Keys longer than blockSize are shortened by hashing them
    if (length(key) > blockSize) then
        key = hash(key)

    // Keys shorter than blockSize are padded to blockSize by padding with zeros on the right
    if (length(key) < blockSize) then
        return  Pad(key, blockSize) // Pad key with zeros to make it blockSize bytes long

    return  key

Design principles

The design of the HMAC specification was motivated by the existence of attacks on more trivial mechanisms for combining a key with a hash function. For example, one might assume the same security that HMAC provides could be achieved with MAC = H(keymessage). However, this method suffers from a serious flaw: with most hash functions, it is easy to append data to the message without knowing the key and obtain another valid MAC ("length-extension attack"). The alternative, appending the key using MAC = H(messagekey), suffers from the problem that an attacker who can find a collision in the (unkeyed) hash function has a collision in the MAC (as two messages m1 and m2 yielding the same hash will provide the same start condition to the hash function before the appended key is hashed, hence the final hash will be the same). Using MAC = H(keymessagekey) is better, but various security papers have suggested vulnerabilities with this approach, even when two different keys are used.[1][7][8]

No known extension attacks have been found against the current HMAC specification which is defined as H(keyH(keymessage)) because the outer application of the hash function masks the intermediate result of the internal hash. The values of ipad and opad are not critical to the security of the algorithm, but were defined in such a way to have a large Hamming distance from each other and so the inner and outer keys will have fewer bits in common. The security reduction of HMAC does require them to be different in at least one bit.[citation needed]

The Keccak hash function, that was selected by NIST as the SHA-3 competition winner, doesn't need this nested approach and can be used to generate a MAC by simply prepending the key to the message, as it is not susceptible to length-extension attacks.[9]

Security

The cryptographic strength of the HMAC depends upon the size of the secret key that is used and the security of the underlying hash function used. It has been proven that the security of an HMAC construction is directly related to security properties of the hash function used. The most common attack against HMACs is brute force to uncover the secret key. HMACs are substantially less affected by collisions than their underlying hashing algorithms alone.[2][10][11] In particular, Mihir Bellare proved that HMAC is a pseudo-random function (PRF) under the sole assumption that the compression function is a PRF.[12] Therefore, HMAC-MD5 does not suffer from the same weaknesses that have been found in MD5.[13]

RFC 2104 requires that "keys longer than B bytes are first hashed using H" which leads to a confusing pseudo-collision: if the key is longer than the hash block size (e.g. 64 bytes for SHA-1), then HMAC(k, m) is computed as HMAC(H(k), m). This property is sometimes raised as a possible weakness of HMAC in password-hashing scenarios: it has been demonstrated that it's possible to find a long ASCII string and a random value whose hash will be also an ASCII string, and both values will produce the same HMAC output.[14][15][16]

In 2006, Jongsung Kim, Alex Biryukov, Bart Preneel, and Seokhie Hong showed how to distinguish HMAC with reduced versions of MD5 and SHA-1 or full versions of HAVAL, MD4, and SHA-0 from a random function or HMAC with a random function. Differential distinguishers allow an attacker to devise a forgery attack on HMAC. Furthermore, differential and rectangle distinguishers can lead to second-preimage attacks. HMAC with the full version of MD4 can be forged with this knowledge. These attacks do not contradict the security proof of HMAC, but provide insight into HMAC based on existing cryptographic hash functions.[17]

In 2009, Xiaoyun Wang et al. presented a distinguishing attack on HMAC-MD5 without using related keys. It can distinguish an instantiation of HMAC with MD5 from an instantiation with a random function with 297 queries with probability 0.87.[18]

In 2011 an informational RFC 6151 was published to summarize security considerations in MD5 and HMAC-MD5. For HMAC-MD5 the RFC summarizes that – although the security of the MD5 hash function itself is severely compromised – the currently known "attacks on HMAC-MD5 do not seem to indicate a practical vulnerability when used as a message authentication code", but it also adds that "for a new protocol design, a ciphersuite with HMAC-MD5 should not be included".[13]

In May 2011, RFC 6234 was published detailing the abstract theory and source code for SHA-based HMACs.[19]

Examples

Here are some HMAC values, assuming 8-bit ASCII for the input and hexadecimal encoding for the output:

HMAC_MD5("key", "The quick brown fox jumps over the lazy dog")    = 80070713463e7749b90c2dc24911e275

HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog")   = de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9

HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

HMAC_SHA512("key", "The quick brown fox jumps over the lazy dog") = b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a

See also

References

  1. ^ a b c Bellare, Mihir; Canetti, Ran; Krawczyk, Hugo (1996). "Keying Hash Functions for Message Authentication" (PDF). pp. 1–15. CiteSeerX 10.1.1.134.8430.
  2. ^ a b c Bellare, Mihir; Canetti, Ran; Krawczyk, Hugo (Spring 1996). "Message Authentication using Hash Functions—The HMAC Construction" (PDF). CryptoBytes. 2 (1).
  3. ^ a b c d H. Krawczyk; M. Bellare; R. Canetti (February 1997). HMAC: Keyed-Hashing for Message Authentication. Network Working Group. doi:10.17487/RFC2104. RFC 2104. Informational. Updated by RFC 6151.
  4. ^ "FIPS 198-1: The Keyed-Hash Message Authentication Code (HMAC)". Federal Information Processing Standards. 16 July 2008.
  5. ^ "FIPS 180-2 with Change Notice 1" (PDF). csrc.nist.gov.
  6. ^ Dworkin, Morris (4 August 2015). "SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions". Federal Information Processing Standards – via NIST Publications.
  7. ^ Preneel, Bart; van Oorschot, Paul C. (1995). "MDx-MAC and Building Fast MACs from Hash Functions". CiteSeerX 10.1.1.34.3855. {{cite journal}}: Cite journal requires |journal= (help)
  8. ^ Preneel, Bart; van Oorschot, Paul C. (1995). "On the Security of Two MAC Algorithms". CiteSeerX 10.1.1.42.8908. {{cite journal}}: Cite journal requires |journal= (help)
  9. ^ Keccak team. "Keccak Team – Design and security". Retrieved 31 October 2019. Unlike SHA-1 and SHA-2, Keccak does not have the length-extension weakness, hence does not need the HMAC nested construction. Instead, MAC computation can be performed by simply prepending the message with the key.
  10. ^ Schneier, Bruce (August 2005). "SHA-1 Broken". Retrieved 9 January 2009. although it doesn't affect applications such as HMAC where collisions aren't important
  11. ^ H. Krawczyk; M. Bellare; R. Canetti (February 1997). HMAC: Keyed-Hashing for Message Authentication. Network Working Group. doi:10.17487/RFC2104. RFC 2104. Informational. sec. 6. Updated by RFC 6151. The strongest attack known against HMAC is based on the frequency of collisions for the hash function H ("birthday attack") [PV,BCK2], and is totally impractical for minimally reasonable hash functions.
  12. ^ Bellare, Mihir. "New Proofs for NMAC and HMAC: Security without Collision-Resistance" (PDF). Journal of Cryptology. Retrieved 15 December 2021. This paper proves that HMAC is a PRF under the sole assumption that the compression function is a PRF. This recovers a proof based guarantee since no known attacks compromise the pseudorandomness of the compression function, and it also helps explain the resistance-to-attack that HMAC has shown even when implemented with hash functions whose (weak) collision resistance is compromised.
  13. ^ a b S. Turner; L. Chen (March 2011). Updated Security Considerations for the MD5 Message-Digest and the HMAC-MD5 Algorithms. IETF. doi:10.17487/RFC6151. RFC 6151. Informational. Updates RFC 2104 and 1321.
  14. ^ "PBKDF2+HMAC hash collisions explained · Mathias Bynens". mathiasbynens.be. Retrieved 7 August 2019.
  15. ^ "Aaron Toponce : Breaking HMAC". Retrieved 7 August 2019.
  16. ^ "RFC 2104 Errata Held for Document Update · Erdem Memisyazici". www.rfc-editor.org. Retrieved 23 September 2016.
  17. ^ Jongsung, Kim; Biryukov, Alex; Preneel, Bart; Hong, Seokhie (2006). "On the Security of HMAC and NMAC Based on HAVAL, MD4, MD5, SHA-0 and SHA-1" (PDF). SCN 2006. Springer-Verlag.
  18. ^ Wang, Xiaoyun; Yu, Hongbo; Wang, Wei; Zhang, Haina; Zhan, Tao (2009). "Cryptanalysis on HMAC/NMAC-MD5 and MD5-MAC" (PDF). Retrieved 15 June 2015. {{cite journal}}: Cite journal requires |journal= (help)
  19. ^ Eastlake 3rd, D.; Hansen, T. (May 2011). US Secure Hash Algorithms (SHA and SHA-based HMAC and HKDF). Internet Engineering Task Force. doi:10.17487/RFC6234. ISSN 2070-1721. RFC 6234. Informational. Obsoletes RFC 4634. Updates RFC 3174

Read other articles:

Milton FriedmanLahir(1912-07-31)31 Juli 1912Brooklyn, New YorkMeninggal16 November 2006(2006-11-16) (umur 94)San Francisco, CaliforniaKebangsaanAmericanInstitusiHoover Institution (1977–2006)University of Chicago (1946–77)Columbia University (1937–41, 1943–45, 1964–65)NBER (1937–40)BidangEconomicsMazhabChicago School of EconomicsAlma materColumbia University (Ph.D.), 1946, University of Chicago (M.A.), 1933 Rutgers University (B.A.), (1932)DipengaruhiAdam Smith, Irving ...

 

 

Raoul dari Lorraine Raoul (atau Rodolphe) dari Lorraine dikenal juga sebagai sang Pemberani (lahir 1320 dan meninggal 26 Agustus 1346, dalam pertempuran Crécy), putra adipati Ferry IV dari Lorraine dan Élisabeth dari Lorraine, merupakan adipati Lorraine dari 1329 hingga 1346. Setelah kematian ayahandanya, Raoul (Radulphus atau Rodolphe) baru berusia sembilan tahun. Dalam wasiat yang dibuat sebelum kematiannya, Elisabeth ditunjuk sebagai wali penguasa kadipaten hingga 1334.[1] Pernik...

 

 

Ichthyodes affinis Klasifikasi ilmiah Kerajaan: Animalia Filum: Arthropoda Kelas: Insecta Ordo: Coleoptera Famili: Cerambycidae Genus: Ichthyodes Spesies: Ichthyodes affinis Ichthyodes affinis adalah spesies kumbang tanduk panjang yang berasal dari famili Cerambycidae. Spesies ini juga merupakan bagian dari genus Ichthyodes, ordo Coleoptera, kelas Insecta, filum Arthropoda, dan kingdom Animalia. Larva kumbang ini biasanya mengebor ke dalam kayu dan dapat menyebabkan kerusakan pada batang kay...

Ini adalah nama Korea; marganya adalah Yoon. Yoon So-heeLahir7 Mei 1993 (umur 30)Busan, South KoreaPendidikanKAISTPekerjaanAktrisTahun aktif2013-sekarangAgenS.M. Culture & ContentsNama KoreaHangul윤소희 Hanja尹邵熙 Alih AksaraYun So-heeMcCune–ReischauerYun Sohŭi Templat:Korean membutuhkan parameter |hangul=. Yoon So-hee (Hangul: 윤소희; lahir pada 7 Mei 1993) merupakan aktris dari Korea Selatan Latar Belakang Yoon So-hee lahir di Stuttgart, Jerman p...

 

 

Часть серии статей о Холокосте Идеология и политика Расовая гигиена · Расовый антисемитизм · Нацистская расовая политика · Нюрнбергские расовые законы Шоа Лагеря смерти Белжец · Дахау · Майданек · Малый Тростенец · Маутхаузен ·&...

 

 

United States historic placeKendall Boiler and Tank Company BuildingU.S. Historic districtContributing property The Kendall Boiler and Tank Company Building is part of the larger Blake and Knowles Steam Pump Company National Register District.Show map of MassachusettsShow map of the United StatesLocation275 Third Street, Cambridge, MassachusettsCoordinates42°21′58″N 71°5′2″W / 42.36611°N 71.08389°W / 42.36611; -71.08389Part ofBlake and Knowles Steam Pump C...

Sarah LacySarah Lacy, diambil oleh Doc Searls di LeWeb3 di ParisLahir29 Desember 1975 (umur 48)Memphis, TennesseeAlmamaterRhodes CollegeSuami/istriGeoffrey Ellis Sarah Ruth Lacy (lahir December 29, 1975) adalah seorang penulis dan jurnalis teknologi Amerika Serikat.[1] Kehidupan awal Lacy menerima B.A. di bidang literatur dari Perguruan Tinggi Rhodes.[2] Karier Lacy merupakan mantan pembawa acara dari sebuah pertunjukkan video web Yahoo! Tech Ticker[3] dan merupa...

 

 

Lord Buddha statue in Japan Japanese sutra book open to the Shorter Sukhāvatīvyūha Sūtra Part of a series onMahāyāna Buddhism Teachings Bodhisattva Buddhahood Mind of Awakening Buddha-nature Skillful Means Transcendent Wisdom Transcendent Virtues Emptiness Two truths Consciousness-only Three bodies Three vehicles Non-abiding Nirvana One Vehicle Bodhisattva Precepts Bodhisattva vow Bodhisattva stages Pure Lands Luminous mind Dharani Three Turnings Buddhas and Bodhisattvas Shakyamuni Amit...

 

 

ACF FiorentinaCalcio Viola, Gigliati Segni distintivi Uniformi di gara Casa Trasferta Terza divisa Colori sociali Viola Simboli Giglio di Firenze Inno Canzone violaMarcello Manni(testo di Enzo Marcacci, riedita da Narciso Parigi) Dati societari Città Firenze Nazione  Italia Confederazione UEFA Federazione FIGC Campionato Serie A Fondazione 1926 Rifondazione2002 Proprietario Rocco Commisso(attraverso Columbia Soccer Ventures LLC) Presidente Rocco Commisso Allenatore Vincenzo Italiano St...

Jalur kereta api Purwosari–Wonogiri–BaturetnoKonvoi militer di jalur kereta api Purwosari-Wonogiri–BaturetnoIkhtisarJenisJalur lintas cabangSistemJalur kereta api rel ringanStatusBeroperasi (segmen Purwosari–Wonogiri) Tidak Beroperasi (segmen Wonogiri - Baturetno)LokasiKota Surakarta, Kabupaten Sukoharjo, dan Kabupaten Wonogiri, Jawa TengahTerminusPurwosariWonogiriStasiun26OperasiDibangun olehSolosche Tramweg MaatschappijNederlands-Indische Spoorweg MaatschappijDibuka1892-1922PemilikD...

 

 

69th (South Lincolnshire) Regiment of FootActive10 December 1756–1 July 1881Country Kingdom of Great Britain (1756–1800) United Kingdom (1801–1881)Branch British ArmyTypeInfantrySizeOne battalion (two battalions 1795–1796 and 1803–1816)Garrison/HQMaindy Barracks, CardiffNickname(s)The Ups and DownsThe Old Agamemnons[1]EngagementsSeven Years' WarNapoleonic WarsFenian raidsMilitary unit The 69th (South Lincolnshire) Regiment of Foot was an infantry regiment of t...

 

 

2011 studio album by The Rural Alberta AdvantageDepartingStudio album by The Rural Alberta AdvantageReleasedMarch 1, 2011GenreIndie rock, Indie folkLabelPaper Bag Records (CAN)Saddle Creek Records (US)The Rural Alberta Advantage chronology Hometowns(2008) Departing(2011) Mended with Gold(2014) Departing is the second full-length album by Canadian indie rock band The Rural Alberta Advantage, released March 1, 2011 on Paper Bag Records in Canada and Saddle Creek Records in the United S...

Stringed musical instrument For the plant genus, see Valiha (plant). A valiha player in Ambohimahasoa, central Madagascar Lullaby played on valiha Valiha orchestra at the Paris World Exposition of 1931. Valiha with larger diameter bamboo tube. The valiha is a tube zither from Madagascar made from a species of local bamboo; it is considered the national instrument of Madagascar.[1] The term is also used to describe a number of related zithers of differing shapes and materials.[2 ...

 

 

National Historic Site of the United States Eleanor Roosevelt National Historic SiteStone CottageShow map of New YorkShow map of the United StatesLocationHaviland, Hyde Park, Dutchess County, New York, United StatesCoordinates41°45′47″N 73°53′56″W / 41.76306°N 73.89889°W / 41.76306; -73.89889Area181 acres (73 ha)EstablishedMay 27, 1977Visitors52,690 (in 2005)Governing bodyNational Park ServiceWebsiteEleanor Roosevelt National Historic Sit...

 

 

Scoot IATA ICAO Kode panggil TR[1] TGW SCOOTER Didirikan1 November 2011Mulai beroperasi4 Juni 2012PenghubungSingapura-ChangiKota fokusTaipei-TaoyuanProgram penumpang setiaKrisFlyerAliansiValue AllianceArmada59Tujuan70SloganGet Outta Here!Perusahaan indukSingapore AirlinesKantor pusat4 Airline RoadChangi AirportSingapore 819825Tokoh utamaCampbell Wilson (CEO)Karyawan1.976 (2020/21)Situs webflyscoot.com Scoot Tigerair Pte Ltd. (dioperasikan juga Scoot) adalah maskapai penerbangan bertar...

2015 UK local government election 2015 Canterbury City Council election[1] ← 2011 7 May 2015 2019 → All 39 seats in the Canterbury City Council20 seats needed for a majority   First party Second party   Party Conservative Labour Last election Conservative Seats won 31 3 Popular vote 29,670 16,954 Percentage 37.4% 21.4%   Third party Fourth party   Party Liberal Democrats UKIP Seats won 3 2 Popular vote 10,305 12,939 Pe...

 

 

الدوري التونسي لكرة اليد للرجال الموسم 1979-1980 البلد تونس  المنظم الجامعة التونسية لكرة اليد  النسخة 25 عدد الفرق 20   الفائز الترجي الرياضي التونسي الشبيبة الرياضية القيروانية (الثاني) الدوري التونسي لكرة اليد 1978–79  الدوري التونسي لكرة اليد 1980–81  تعديل مصدري - ت�...

 

 

Griffith InstituteHistoireFondation 1939CadreType InstitutPays  Royaume-UniOrganisationSite web www.griffith.ox.ac.ukmodifier - modifier le code - modifier Wikidata Le Griffith Institute est une institution fondée dans le musée Ashmolean de l'université d'Oxford pour la promotion de l'égyptologie en tant que discipline. Il a été nommé d'après l'éminent égyptologue Francis Llewellyn Griffith, qui a légué des fonds dans son testament à la fondation de l'Institut. Il a été in...

Tool for separation of solid materials by particle size This article is about the tool. For other uses, see Sieve (disambiguation). Sift redirects here. For other uses, see Sift (disambiguation).Drainer redirects here. For the music culture, see Drain Gang. Metal laboratory sieves An ami shakushi, a Japanese ladle or scoop that may be used to remove small drops of batter during the frying of tempura ancient sieve A sieve, fine mesh strainer, or sift, is a tool used for separating wanted eleme...

 

 

Questa voce sull'argomento tennisti statunitensi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Mitchell KruegerMitchell Krueger nel 2022Nazionalità Stati Uniti Altezza188 cm Peso77 kg Tennis Carriera Singolare1 Vittorie/sconfitte 8-19 (29.63%) Titoli vinti 0 Miglior ranking 135º (18 luglio 2022) Ranking attuale ranking Risultati nei tornei del Grande Slam  Australian Open 1T (2019)  Roland Garros Q1 (2015, 2017, 2019)  Wimbledo...