SoFunction
Updated on 2024-11-17

Python hmac module use case analysis

This article introduces the Python hmac module to use the example of analysis, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference learning value, the need for friends can refer to the following

The role of the hmac module:

Used to verify the integrity of information.

1, hmac message signature (default use MD5 plus algorithm)

hmac_md5.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hmac
# Default use is the md5 algorithm
digest_maker = ('secret-shared-key'.encode('utf-8'))
with open('', 'rb') as f:
  while True:
    block = (1024)
    if not block:
      break
    digest_maker.update(block)
digest = digest_maker.hexdigest()
print(digest)


Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec
egestas, enim et consectetuer ullamcorper, lectus ligula rutrum leo, a
elementum elit tortor eu quam. Duis tincidunt nisi ut ante. Nulla
facilisi. Sed tristique eros eu libero. Pellentesque vel arcu. Vivamus
purus orci, iaculis ac, suscipit sit amet, pulvinar eu,
lacus. Praesent placerat tortor sed nisl. Nunc blandit diam egestas
dui. Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Aliquam viverra fringilla
leo. Nulla feugiat augue eleifend nulla. Vivamus mauris. Vivamus sed
mauris in nibh placerat egestas. Suspendisse potenti. Mauris massa. Ut
eget velit auctor tortor blandit sollicitudin. Suspendisse imperdiet
justo.

operational effect

[root@ mnt]# python3 hmac_md5.py 
79cbf5942e8f67be558bc28610c02117

2. hmac message signature digest (using SHA1 addition algorithm)

hmac_sha1.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hmac

digest_maker = ('secret-shared-key'.encode('utf-8'), b'', digestmod='sha1')
# (key,msg,digestmod)
# key: key with salt, # key: key with salt.
# msg: encrypted content.
# digestmod: the encryption

with open('hmac_sha1.py', 'rb') as f:
  while True:
    block = (1024)
    if not block:
      break
    digest_maker.update(block)
digest = digest_maker.hexdigest()
print(digest)

operational effect

[root@ mnt]# python3 hmac_sha1.py 
e5c012eac5fa76a274f77ee678e6cc98cad8fff9

3. hmac binary message signature digest (using SHA1 plus algorithm)

hmac_base64.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hmac
import base64
import hashlib

with open('', 'rb') as f:
  body = ()

# The default is the md5 algorithm
digest_maker = ('secret-shared-key'.encode('utf-8'), body, hashlib.sha1)
# (key,msg,digestmod)
# key: key with salt, # key: key with salt.
# msg: encrypted content.
# digestmod: the encryption

digest = digest_maker.digest() # The default content is of type byte, so base64 is required
print((digest)) #take note ofbase64The result is to\nclose,the reason whyHttpFor head or other transmissions,Needs to be removed\n

operational effect

[root@ mnt]# python3 hmac_base64.py 
b'Y9a4OMRqU4DB6Ks/hGfru+MNXAw=\n'

4. hmac summary data comparison example

hmac_pickle.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import hashlib
import hmac
import io
import pickle

def make_digest(message):
  "Return message summarized, ciphered."
  hash = (
    'secret-shared-key'.encode('utf-8'),
    message,
    hashlib.sha1
  )
  return ().encode('utf-8')

class SimpleObject(object):
  def __init__(self, name):
     = name

  def __str__(self):
    return 

# Output buffers
out_s = ()
o = SimpleObject('digest matches')
pickle_data = (o) # Serialization
digest = make_digest(pickle_data) # Use sha1 encryption algorithm
header = b'%s  %d\n' % (digest, len(pickle_data))
print('draw attention to sth.:{}'.format(header))
out_s.write(header) # Write message headers to buffer
out_s.write(pickle_data) # Write serialized content to buffer

o = SimpleObject('digest does not matches')
pickle_data = (o)
digest = make_digest(b'not the pickled data at all')
header = b'%s  %d\n' % (digest, len(pickle_data))
print('draw attention to sth.:{}'.format(header))
out_s.write(header) # Write message headers to buffer
out_s.write(pickle_data) # Write serialized content to buffer
out_s.flush() # Refresh the buffer

# Input buffer
in_s = (out_s.getvalue())

while True:
  first_line = in_s.readline()
  if not first_line:
    break
  incoming_digest, incoming_length = first_line.split(b'  ')
  incoming_length = int(incoming_length.decode('utf-8'))
  print('Read:', incoming_digest, incoming_length)

  incoming_pickled_data = in_s.read(incoming_length)

  actual_digest = make_digest(incoming_pickled_data) # Actual summary
  print('Actual value:', actual_digest)

  if hmac.compare_digest(actual_digest, incoming_digest): # Compare two summaries for equality
    obj = (incoming_pickled_data)
    print('OK:', obj)
  else:
    print('Incomplete data')

operational effect

[root@ mnt]# python3 hmac_pickle.py 
draw attention to sth.:b'00e080735a8de379e19fe2aa731c92fc9253a6e2  69\n'
draw attention to sth.:b'1d147690f94ea374f6f8c3767bd5a5f9a8989a53  78\n'
retrieve: b'00e080735a8de379e19fe2aa731c92fc9253a6e2' 69
actual value: b'00e080735a8de379e19fe2aa731c92fc9253a6e2'
OK: digest matches
retrieve: b'1d147690f94ea374f6f8c3767bd5a5f9a8989a53' 78
actual value: b'4dcaad9b05bbb67b571a64defa52e8960a27c45d'
Incomplete data

This is the whole content of this article.