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 .
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 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 .
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
The sidebar is recommended
- My friend's stock suffered a terrible loss. When I was angry, I crawled the latest data of securities with Python
- Python interface automation testing framework -- if you want to do well, you must first sharpen its tools
- Python multi thread crawling weather website pictures and saving
- How to convert pandas data to excel file
- Python series tutorials 122
- Python Complete Guide - printing data using pyspark
- Python Complete Guide -- tuple conversion array
- Stroke the list in python (top)
- Analysis of Python requests module
- Comments and variables in Python
guess what you like
-
New statement match, the new version of Python is finally going to introduce switch case?
-
Fanwai 6 Different operations for image details in Python opencv
-
Python crawler native code learning (I)
-
Python quantitative data warehouse building series 2: Python operation database
-
Python code reading (Part 50): taking elements from list intervals
-
Pyechart + pandas made word cloud pictures of 19 report documents
-
[Python crawler] multithreaded daemon & join() blocking
-
Python crawls cat pictures in batches to realize thousand image imaging
-
Van * Python | simple crawling of a planet
-
Input and output of Python practice
Random recommended
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
- Python hashlib module
- The cover of Python 3 web crawler development (Second Edition) has been determined!
- The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
- [Python basics] explain Python basic functions in detail, including teaching and learning
- Python web crawler - crawling cloud music review (4)
- The first step of scientific research: create Python virtual environment on Linux server
- Writing nmap scanning tool in Python -- multithreaded version
- leetcode 2057. Smallest Index With Equal Value(python)
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python crawler actual combat, requests module, python realizes capturing a video barrage
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
- How IOS developers learn python programming 3-operator 2
- How IOS developers learn python programming 2-operator 1
- [Python applet] 8 lines of code to realize file de duplication
- Python uses the pynvml tool to obtain the working status of GPU
- Data mining: Python actual combat multi factor analysis
- Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
- Use Python VTK to batch read 2D slices and display 3D models
- Complete image cutting using Python version VTK
- Python interface automation test framework (basic) -- common data types Dict
- Python specific text extraction in actual combat challenges the first step of efficient office