current position:Home>How to implement encrypted message signature and verification in Python -- HMAC

How to implement encrypted message signature and verification in Python -- HMAC

2022-01-31 05:58:49 Stone sword

Python Various built-in algorithms are provided for encryption tasks . This article will demonstrate hmac. Built in algorithm for encryption task One of **, For the use of Python Of Encrypted message signing and verification **, And pass Python4Delphi stay Python GUI Run in to get results .

hmac The module implements the bonding for message verification , Such as RFC 2104 Described in .HMAC The algorithm can be used to verify the integrity of the information transmitted between applications , Or stored in a potentially risky location .

Its basic idea is to generate encrypted hash of actual data , Combined with the shared secret key . then , The generated hash value can be used to check the transmitted or stored information , To determine the level of trust , Without transmitting the secret key .

This article will guide you

How to be in Windows GUI Use built-in... In your application hmac Library implementation Python Encryption services ?

precondition Before we start working , Please download and install the latest version of your platform Python. according to here Mentioned Python4Delphi Installation instructions . perhaps , You can also view the simple instructions in this video Start using Python4Delphi.

First , Use Python4Delphi And RAD Studio Project Demo1 Open and run our Python GUI. Then insert the script into the lower memo , Click the execute button , Get the results in the upper memo . You can GitHub Found on the Demo1 Source code . About Delphi How in this magical Python GUI Run your Python The behind the scenes details of the code can be found in this link Find .

How To Sign and Verify Cryptographic Messages In Your Apps - demo screen

open Demo01.dproj

How do we use binary digests to produce printable digests ?

Let's try a Binary Digest Example , To produce a printable summary . Some network services (Google checkout, Amazon S3) Use base64 Encoded binary digest instead of hexdigest. stay Python4Delphi GUI Run the following code in .

import base64
import hmac
import hashlib

with open('lorem.txt', 'rb') as f:
    body = f.read()

hash = hmac.new(
    b'secret-shared-key-goes-here',
    body,
    hashlib.sha1,
)

digest = hash.digest()
print(base64.encodebytes(digest))
 Copy code 

base64 The encoded string ends on a new line , When embedding a string http Header or other format sensitive environment , It often needs to be stripped out . Let's see Python GUI The output in .

How To Sign and Verify Cryptographic Messages In Your Apps - the app, in action

How to use Python The application of message signature ?

Next , Let's try a more advanced example Application of message signature .HMAC Authentication should be used for any public network service , And any time data is stored , And the safety of these times is very important . for example , When sending data through a pipe or socket , The data should be signed , Then test the signature before using the data .

Here is the implementation Message signing application Steps for :

  • Create a function to calculate the summary of a string , And establish a simple class to instantiate and pass through the communication channel .
  • Create a BytesIO Buffer to represent socket or pipe . This example uses a naive approach to data flow 、 But easy to parse format . The summary and length of the data are written , Then there is a new line . And then there's the pickle A serialized representation of the generated object .
  • For the program of this example , Write two objects into the stream . The first object is written with the correct summary value . The second object is written to the stream with an invalid digest , This summary is based on some other data rather than pickle Calculated from the data .
  • Now the data is BytesIO Buffer zone , It can be read again . First read the row of data with summary and data length . Then read the remaining data , Use length value .pickle.load() You can read directly from the data stream , But this assumes a trusted data stream , And this data has not been trusted enough to solve it . Read from the stream as a string pickle, Without actually unlocking the object , It's safer .
  • Once the extracted data is in memory , You can recalculate the summary value , And use compare_digest() Compare with the read data . If the summary matches , You can safely trust the data and unlock it .
import hashlib
import hmac
import io
import pickle
import pprint

def make_digest(message):
    "Return a digest for the message."
    hash = hmac.new(
        b'secret-shared-key-goes-here',
          message,
          hashlib.sha1,
    )
    return hash.hexdigest().encode('utf-8')

class SimpleObject:
    """Demonstrate checking digests before unpickling.
    """
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

# Simulate a writable socket or pipe with a buffer
out_s = io.BytesIO()

# Write a valid object to the stream:
#  digestnlengthnpickle
o = SimpleObject('digest matches')
pickled_data = pickle.dumps(o)
digest = make_digest(pickled_data)
header = b'%s %dn' % (digest, len(pickled_data))
print('WRITING: {}'.format(header))
out_s.write(header)
out_s.write(pickled_data)

# Write an invalid object to the stream
o = SimpleObject('digest does not match')
pickled_data = pickle.dumps(o)
digest = make_digest(b'not the pickled data at all')
header = b'%s %dn' % (digest, len(pickled_data))
print('nWRITING: {}'.format(header))
out_s.write(header)
out_s.write(pickled_data)

out_s.flush()

# Simulate a readable socket or pipe with a buffer
in_s = io.BytesIO(out_s.getvalue())

# Read the data
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('nREAD:', incoming_digest, incoming_length)

    incoming_pickled_data = in_s.read(incoming_length)

    actual_digest = make_digest(incoming_pickled_data)
    print('ACTUAL:', actual_digest)

    if hmac.compare_digest(actual_digest, incoming_digest):
        obj = pickle.loads(incoming_pickled_data)
        print('OK:', obj)
    else:
        print('WARNING: Data corruption')
 Copy code 
  • The output shows , The first object is validated , The second object is considered to be " The damaged ", As expected .

How To Sign and Verify Cryptographic Messages In Your Apps - the output

Comparing two digests with a simple string or byte can be used in timing attacks , Expose some or all of the keys by passing summaries of different lengths . compare_digest() A fast but constant time comparison function is realized , To prevent regular attacks .

congratulations ! You have learned how to achieve Python password . You've learned how to use Python GUI for Delphi Windows App The built-in hmac Library to implement Python Encryption services .

copyright notice
author[Stone sword],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310558458208.html

Random recommended