This is a python module for encoding and correcting data using BCH codes. This is a fork of https://github.com/jkent/python-bchlib that extends support for Galois Field orders up to 31 (previous implementation supported up to 15).
For Windows, python3.5 or greater required.
For Linux and MacOS, python2.7 or python3.4 or greater required.
$ pip install bchlib
Make sure you have python-dev setup. For Windows, this means you need Visual Studio 2015.
$ pip install .
bchlib.BCH( polynomial, t[, reverse] ) → bch
Constructor creates a BCH object with given
polynomial
andt
bit strength,reverse
is an optional boolean that flips the bit order of data. The Galois field order is automatically determined from thepolynomial
.
bch.encode( data[, ecc] ) → ecc
Encodes
data
with an optional startingecc
and returns an ecc.
bch.decode( data, ecc ) → ( bitflips, data, ecc )
Corrects
data
usingecc
and returns a tuple.
bch.decode_inplace( data, ecc ) → bitflips
Corrects
data
usingecc
in place, returning the number of bitflips.
bch.decode_syndromes( data, syndromes ) → ( bitflips, data )
Corrects
data
using a sequence ofsyndromes
, of t*2 elements, returning a tuple.
bch.compute_even_syndromes( syndromes ) → syndromes
Computes even syndromes from odd ones. Takes and returns a sequence of t*2 elements.
bch.ecc_bytes
A readonly field; the number of bytes an ecc takes up.
bch.ecc_bits
A readonly field; the number of bits an ecc takes up.
bch.m
A readonly field; the Galois field order.
bch.n
A readonly field; the maximum codeword size in bits.
bch.syndromes
A readonly field; a tuple of syndromes after performing a correct operation.
bch.t
A readonly field; the number bit errors that can be corrected.
import bchlib
import hashlib
import os
import random
# create a bch object
BCH_POLYNOMIAL = 8219
BCH_BITS = 16
bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)
# random data
data = bytearray(os.urandom(512))
# encode and make a "packet"
ecc = bch.encode(data)
packet = data + ecc
# print hash of packet
sha1_initial = hashlib.sha1(packet)
print('sha1: %s' % (sha1_initial.hexdigest(),))
def bitflip(packet):
byte_num = random.randint(0, len(packet) - 1)
bit_num = random.randint(0, 7)
packet[byte_num] ^= (1 << bit_num)
# make BCH_BITS errors
for _ in range(BCH_BITS):
bitflip(packet)
# print hash of packet
sha1_corrupt = hashlib.sha1(packet)
print('sha1: %s' % (sha1_corrupt.hexdigest(),))
# de-packetize
data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]
# correct
bitflips = bch.decode_inplace(data, ecc)
print('bitflips: %d' % (bitflips))
# packetize
packet = data + ecc
# print hash of packet
sha1_corrected = hashlib.sha1(packet)
print('sha1: %s' % (sha1_corrected.hexdigest(),))
if sha1_initial.digest() == sha1_corrected.digest():
print('Corrected!')
else:
print('Failed')