Package: hamming-check
hamming-checkA command line tool and python library to encode and decode data using a generic (in byte size) hamming code algorithm.Hamming CodeHamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data
is moved or stored from the sender to the receiver. It is technique developed by R.W. Hamming for error correction.You can find more about it on hisWikipedia Article,MSU notesand in the awesome videos by3Blue1Brown:Hamming pt1andHamming pt2.InstallingLocallyClone the repo.gitclonegit@github.com:Tomcat-42/hamming_check.gitRunsetup.pysudopythonsetup.pyinstallUsing piphamming_checkis available onpypi.sudopipinstallhamming_checkCommand Line InterfaceDescriptionhamming_checkis a cli tool that is intended to help creating secure copies of a file in a hamming encoded output file, and fixing that secure file for single bit corruptions. Also it can check for double bit corruptions, but could not fix that type of error.Usageusage: hamming_check [-h] (-e | -d) [-v] [-b BUFFER_SIZE]
                     [input_file] [output_file]

positional arguments:
  input_file            file used for reading data. If not specified,
                        data is read from stdin.
  output_file           file used for writing data. If not specified,
                        data is written to stdout.

options:
  -h, --help            show this help message and exit
  -e, --encode          encode a file into a hamming-encoded file
  -d, --decode          decode a hamming-encoded file into a file
  -v, --verbose         increase output verbosity (can be used
                        multiple times)
  -b BUFFER_SIZE, --buffer-size BUFFER_SIZE
                        change the buffer size (in bytes) used for
                        encoding/decodinginput_file: original file that will be secure copied or a secure file that will be recovered.If not provided, data will be read from STDIN.output_file: secure file that will be created from a file or a file that will be recovered from a secure file.If not provided, data will be written to STDOUT.-e|--encode: Sets the encoding operation.File->Secure File.-d|--decode: Sets the decoding operation.Secure File->Filewith error checking/correction.-b|--buffer-size: Sets the number of bytes that will be used for the hamming code, default is 1. Higher Values tends to speed up encoding.-v: Sets the verbosity. If not provided, will be in quiet mode, if-v, only errors will be printed,-vvwill print the result of the encoding/decoding operations and-vvvwill print all of the hamming algorithm steps.-h: prints the help text.ExamplesEncode the file cat.jpg into the secure file cat.jpg.whamhamming_check -e cat.jpg cat.jpg.whamDecode the secure file cat.jpg.wham into the file cat.jpg.whamhamming_check -d cat.jpg.wham cat.jpgEncode the file cat.jpg into the secure file cat.jpg.wham using a 4096 bytes hamming codehamming_check -e -b 4096 cat.jpg cat.jpg.whamdecode the secure file cat.jpg.wham into the file cat.jpg using a 4096 bytes hamming codehamming_check -d -b 4096 cat.jpg.wham cat.jpgEncode the string "test" into the secure file file.txt.whamecho -n "test" | hamming_check -e file.txt.whamEncode the string "test" and print the encoded result to STDOUTecho -n "test" | hamming_check -eDecode the encoded string  and print the decoded result to STOUTecho -n <STR> | hamming_check -dDecode the encoded string  and save the result to file.txtecho -n <STR> | hamming_check -d file.txtDecode the file.txt.wham and print the results to STDOUThamming_check -d file.txt.whamhamming_checklibraryDescriptionhamming_checkis a library for encoding and decoding binary data using the hamming code.UsageHammingModuleEncode and decodes datas using the hamming code of a givenbuffer_sizein bytes.fromhamming_checkimportHamming,DecodeStatus,DecodeResult,VerbosityTypes...hamming=Hamming(buffer_size=1,verbose=VerbosityTypes.QUIET)size_of_encoded_data=hamming.get_number_of_output_bytes()encoded_data=hamming.encode(b't')...decoded_result=hamming.decode(encode)decoded_data,decoded_status=decoded_result.get_data(),decoded_result.get_status()ioModuleAbstractions over files and bytes. TheBytesclass is inherited from thebitarrayand theFilesclass is just a wrapper for the python file interface.fromhamming_checkimportHamming,DecodeStatus,DecodeResult,VerbosityTypes,File,Bytes...hamming=Hamming(buffer_size=2,verbose=VerbosityTypes.QUIET)input_file=File(open("input_file.txt","rb"),bytes_per_read=2)output_file=File(open("output_file.txt","wb"))# read data, encodes it, flips a bit and then writefordataininput_file:encoded_data=hamming.encode(data)bytes=Bytes(encoded_data)bytes[0]^=1output_file.write(bytes.tobytes())input_file.close()output_file.close()ExampleSend a encoded file over the network and check it for corruption.Client Codeclient.py: Read aimage4096 bytes per time, encode that chunk of bytes, add a random noise to the encoded data and sends it over the network.#!/usr/bin/env pythonfromrandomimportrandint,randomimportsocketfromargparseimportArgumentParserfrommathimportefromhamming_check.hammingimportHammingdefmain():# argparserparser=ArgumentParser()parser.add_argument("-p","--port",type=int,default=8080)parser.add_argument("-f","--file",type=str)parser.add_argument("-b","--bytes",type=int,default=4096)parser.add_argument("-d","--double-noise",action="store_true")args=parser.parse_args()# opens the socket connection and the files=socket.socket()s.connect(("localhost",args.port))filetosend=open(args.file,"rb")# Hamming checkhamming=Hamming(args.bytes)bytes_to_send=hamming.get_number_of_output_bytes()# sends the encodedwhiledata:=filetosend.read(args.bytes):encoded_data=bytearray(hamming.encode(data))# 30% chance of sending the data with noiseifrandom()>0.3:print("Sending data with noise")encoded_data[randint(0,bytes_to_send)]^=1<<randint(0,7)# if enabled, 50% of chance to add double noise to dataifargs.double_noiseandrandom()>0.5:print("Sending data with double noise")encoded_data[randint(0,bytes_to_send)]^=1<<randint(0,7)s.send(encoded_data)filetosend.close()s.send(b"DONE")print("Done Sending.")s.shutdown(2)s.close()exit(0)if__name__=="__main__":try:main()exceptKeyboardInterrupt:print("\nExiting...")Server Codeserver.py: Receives encoded data throught the network, decodes it, tries to recover noisy data and then sava it to a output file#!/usr/bin/env pythonimportsocketfromargparseimportArgumentParserfromhamming_check.hammingimportDecodeResult,DecodeStatus,Hammingfromhamming_check.types.verbosity_typesimportVerbosityTypesdefmain()->None:# ArgumentParserparser=ArgumentParser()parser.add_argument("-p","--port",type=int,default=8080)parser.add_argument("-f","--file",type=str)parser.add_argument("-b","--bytes",type=int,default=4096)args=parser.parse_args()# opens sockets=socket.socket()s.bind(("localhost",args.port))s.listen(1)c,a=s.accept()filetodown=open(args.file,"wb")# Hamming checkhamming=Hamming(args.bytes,VerbosityTypes.QUIET)bytes_to_receive=hamming.get_number_of_output_bytes()whileTrue:data=c.recv(bytes_to_receive,socket.MSG_WAITALL)ifdata==b"DONE"orlen(data)==0:print("Done Receiving.")breakencoded_data=hamming.decode(data)# if status is not DecodeStatus.NO_ERROR or# DecodeStatus.SINGLE_ERROR_CORRECTED, then we have a problembytes_received,status=encoded_data.get_data(),encoded_data.get_status()ifstatus==DecodeStatus.SINGLE_ERROR_CORRECTED:print("One error detected, and corrected")elifstatus==DecodeStatus.DOUBLE_ERROR_DETECTED:print("Two errors detected, your file is corrupted")filetodown.write(bytes_received)filetodown.flush()filetodown.close()c.shutdown(2)c.close()s.close()if__name__=="__main__":try:main()exceptKeyboardInterrupt:print("\nBye!")Putting all togetherRun server code./examples/send_over_network/server.py-fout.jpgRun client code./examples/send_over_network/examples.py-f./examples/send_over_network/really_cool_cat.jpgCheck out.jpgEven though was added noise to the data, the server was able to recover the image.