Пример #1
0
    def PRBS(self):
        """Returns a pseudo-random binary sequence 
        which ranges between -1 and +1. This algorithm
        assumes the maximum time constant is 10, and uses
        the time constant to determine the """

        sample, max_len = self.PRBS_parameterization()

        if self.length > max_len:
            self.length = max_len

        L = LFSR(fpoly=[9, 5], initstate='random', verbose=False)
        L.runKCycle(int(np.floor(self.length / sample)) + 1)
        seq = L.seq
        PRBS = np.zeros(self.length)
        for i in range(0, int(self.length / sample) + 1):
            if seq[i] == 0:
                seq[i] = -1

            if sample * i + sample >= self.length:
                PRBS[sample * i:] = seq[i]
                break

            PRBS[sample * i:sample * i + sample] = seq[i]

        return PRBS
Пример #2
0
def Decrypt_PN_Sequence(data):
    from pylfsr import LFSR
    state = [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1]
    poly = [2, 2, 3, 4, 2]
    l = LFSR(fpoly=poly, initstate=state)

    allseq = l.runFullCycle()
    seq = ""
    # print("i am in function",type(data))
    import ast

    eval_expr = ast.literal_eval(data)
    ciphertext = eval_expr

    plaintext = b""
    seq_index = 0

    for x in allseq:
        seq += str(x)

    for counter in range(len(ciphertext)):
        ran_seq = seq[seq_index:seq_index + 8]
        plaintext += bytes([int(ciphertext[counter]) ^ int(ran_seq, 2)])
        seq_index += 8
    # print ( plaintext.decode ( ) )

    return plaintext.decode()
Пример #3
0
 def _run_lfsr(self,
               n,
               lfsr_sz,
               keep_rng=True,
               inv=False,
               save_init=False,
               init_state=None):
     if not keep_rng or self.lfsr is None:
         fpoly = self._lfsr_get_fpoly(lfsr_sz)
         if save_init:
             if self.lfsr_init is None:
                 L = self._lfsr_init_nonzero(fpoly, lfsr_sz, init_state)
                 self.lfsr_init = L.state
             else:
                 L = LFSR(fpoly=fpoly, initstate=self.lfsr_init)
         else:
             L = self._lfsr_init_nonzero(fpoly, lfsr_sz, init_state)
         self.lfsr = np.zeros(n, dtype=np.uint32)
         for i in range(n):
             L.runKCycle(1)
             self.lfsr[i] = bit_vec_to_int(L.state)
     if inv:
         mask = (1 << lfsr_sz) - 1
         return np.bitwise_not(self.lfsr) & mask
     return self.lfsr
Пример #4
0
 def _lfsr_init_nonzero(self, fpoly, lfsr_sz, init_state):
     if init_state is None:
         while True:
             L = LFSR(fpoly=fpoly, initstate='random')
             if not np.all(L.state == np.zeros(lfsr_sz)):
                 break
         return L
     return LFSR(fpoly=fpoly, initstate=init_state)
Пример #5
0
 def _lfsr_get_fpoly(self, lfsr_sz):
     """If the lfsr size is changed, then get a polynomial for the new size, otherwise use the old one"""
     if self.lfsr_sz is None or lfsr_sz != self.lfsr_sz:
         L = LFSR()
         self.fpoly = L.get_fpolyList(
             m=lfsr_sz
         )[0]  #The 0th index holds the lfsr poly with the fewest xor gates
     self.lfsr_sz = lfsr_sz
     return self.fpoly
Пример #6
0
def get_lfsr_seq(width=8):
    polylist = LFSR().get_fpolyList(m=width)
    poly = polylist[np.random.randint(0, len(polylist), 1)[0]]
    L = LFSR(fpoly=poly,initstate ='random')
    lfsr_seq = []
    for i in range(2**width):
        value = 0
        for j in range(width):
            value = value + L.state[j]*2**(width-1-j)
        lfsr_seq.append(value)
        L.next()
    return lfsr_seq
Пример #7
0
def pnSequence(data):
    data = data.encode()
    state = [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1]
    poly = [2, 2, 3, 4, 2]
    from pylfsr import LFSR
    l = LFSR(fpoly=poly, initstate=state)
    ciphertext = b""
    allseq = l.runFullCycle()
    seq = ""
    index = 0
    for x in allseq:
        seq += str(x)
    for i in range(len(data)):
        newseq = seq[index:index + 8]

        ciphertext += bytes([int(data[i]) ^ int(newseq, 2)])
        index += 8

    return ciphertext
Пример #8
0
def lfsr_check(bits, seed, polynom, length):
    index = 0
    for x in lfsr(bits, seed, polynom):
        print(x)

        index += 1
        if index == length:
            break

    for x in lfsr_lib(LFSR(fpoly=polynom, initstate=seed, verbose=True), bits,
                      length + bits):
        print(x)
Пример #9
0
    def generate(self):
        try:
            maks = int(self.plainTextEdit_9.toPlainText())

            str1 = self.plainTextEdit_2.toPlainText()
            str2 = self.plainTextEdit_3.toPlainText()
            str3 = self.plainTextEdit_4.toPlainText()
            str4 = self.plainTextEdit_5.toPlainText()
            str5 = self.plainTextEdit_6.toPlainText()
            str6 = self.plainTextEdit_7.toPlainText()

            poly1 = list(map(int, str1.split(", ")))
            poly2 = list(map(int, str2.split(", ")))
            poly3 = list(map(int, str3.split(", ")))
            state1 = list(map(int, str4.split(", ")))
            state2 = list(map(int, str5.split(", ")))
            state3 = list(map(int, str6.split(", ")))

            L1 = LFSR(fpoly=poly1, initstate=state1, verbose=False)
            L2 = LFSR(fpoly=poly2, initstate=state2, verbose=False)
            L3 = LFSR(fpoly=poly3, initstate=state3, verbose=False)
            a = []
            n = 0

            for x in range(maks):
                L1.next()
                L2.next()
                L3.next()
                out = (L3.outbit & L1.outbit) ^ ((1 ^ L1.outbit) & L2.outbit)
                self.progressBar.setValue(int((x / maks) * 100))
                a.append(out)

            self.progressBar.setValue(100)

            self.plainTextEdit.setPlainText(''.join(map(str, a)))
        except:
            QMessageBox.about(self, "Error", "Set all needed informations!")
Пример #10
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 12:22:28 2020

@author: RileyBallachay
"""
import numpy as np
from pylfsr import LFSR

L = LFSR(fpoly=[23,18],initstate ='random',verbose=True)
L.info()
max_sample = 5
L.runKCycle(1000)
L.info()
seq = L.seq

G = np.zeros(max_sample*1000)
Пример #11
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 12:22:28 2020

@author: RileyBallachay
"""
import numpy as np
from pylfsr import LFSR
import matplotlib.pyplot as plt
from random import randrange, uniform

L = LFSR(fpoly=[9, 5], initstate='random', verbose=False)
L.info()
max_sample = 25
L.runKCycle(1000)
L.info()
seq = L.seq
print(seq)
G = np.zeros(max_sample * 1000)
for i in range(0, 1000):
    if seq[i] == 0:
        seq[i] = -1
    G[25 * i:25 * i + 25] = seq[i]

Y = np.zeros_like(G)

irand = randrange(0, 10)

a = np.linspace(0, 2, 100)
b = np.linspace(0, .1, 100)
Пример #12
0
states = list(itertools.product([0, 1], repeat=16))
states = [np.asarray(s) for s in states]
#personal
first_bits = [
    1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0,
    1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0,
    1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1
]
#test
#first_bits = [1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
for j in range(0, 20000):
    s = states[j]
    #s = [0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0]
    print(j, '/', 2**16)

    L = LFSR(fpoly=f_poly, initstate=s)
    S = L.runKCycle(4 * 2 * len_x)
    S = S.astype(int).tolist()
    ok = True
    if S[0:len(first_bits)] != first_bits:
        continue
    #bin_repr = ['0','b']
    bin_repr = []
    for b in S:
        bin_repr.append(str(b))
    bin_repr = ''.join(bin_repr)
    mu = int(bin_repr, 2)
    print(mu)
    mu = hex(mu)[2:2 * len_x + 2]
    print(len(mu))
    x = strxor(bytes.fromhex(i_ct), bytes.fromhex(mu))
Пример #13
0
import numpy as np
from pylfsr import LFSR
## Example 1  ## 5 bit LFSR with x^5 + x^2 + 1
L = LFSR()
L.info()
L.next()
L.runKCycle(10)
L.runFullCycle()
L.info()
tempseq = L.runKCycle(10000)  # generate 10000 bits from current state

## Example 2  ## 5 bit LFSR with custum state and feedback polynomial
state = [0, 0, 0, 1, 0]
fpoly = [5, 4, 3, 2]
L = LFSR(fpoly=fpoly, initstate=state, verbose=True)
L.info()
tempseq = L.runKCycle(10)
tempseq
L.set(fpoly=[5, 3])

## Example 3  ## 23 bit LFSR with custum state and feedback polynomial
L = LFSR(fpoly=[23, 19], initstate='ones', verbose=True)
L.info()
L.runKCycle(10)
L.info()
seq = L.seq
L.changeFpoly(newfpoly=[23, 21])
seq1 = L.runKCycle(20)
Пример #14
0
Seccion 10
Lic. Luis Alberto Suriano
Grupo 4

main.py
Proposito: Crear una linea dentro del framebuffer con las posibles optimizaciones
"""
#Imnportar pylfsr en pip install
# Manual https://pypi.org/project/pylfsr/

# En este programa se puede explicar el método de Linear-feedback shift register (LFSR)
import numpy as np
from pylfsr import LFSR

#La primera forma es utilizar una libreria externa que permite hacer simular este tipo de algoritmo
L = LFSR()
#Esta funcion nos muestra en la terminal un LFSR de 5-bits con una semilla de [1,1,1,1,1] y contiene
#los bits bit 5, bit 2 y el bit inicial como estado para determinar el output, con el %2 entre la suma de estos
# 3 bits
# Este estado es el "feedback" para generar un numero random
L.info()
L.runFullCycle()

#Tambien se puede modificar el estado y el feedback deseado para cambiar el proceso de determiner el output

state = [0, 0, 0, 1, 0]  # 5-bits
fstate = [
    5, 4, 3, 2
]  # (bit 5 + bit 4 + bit 3 + bit 2 + (bit 0 == 1, ya que xsub0 ^ 2 = 1)) % 2
L2 = LFSR(fpoly=fstate, initstate=state, verbose=True)
#Tenemos un espacio muestal de 5 bits {0,1}^5
Пример #15
0
from pylfsr import LFSR

stan = [0, 1, 0, 1, 0, 1, 0]
xor = [1, 5, 7]

L = LFSR(initstate=stan, fpoly=xor)

print('Iteracja \t Stan \t\t\t Bit wyjsciowy \tSekwencja')
print('\t\t 1 2 3 4 5 6 7 ')
for _ in range(24):
    print(L.count, L.state, '', L.outbit, L.seq, sep='\t\t')
    L.next()
print('Wyjscie: ', L.seq)

L.Viz(show=False, show_labels=False, title='R1')
    tmp = b""
    for i in range(len(content)):
        tmp += xor(content[i], key[i % len(key)])
    return tmp


def shuffle_str(s):
    str_list = list(s)
    random.shuffle(str_list)
    return ''.join(chr(i) for i in str_list).encode('latin1')


ran_str = ''.join(chr(random.randint(1, 256)) for _ in range(512)).encode()
content = ran_str + flag

L4 = LFSR(fpoly=[4, 3], initstate='random', verbose=True)
data = L4.runFullCycle()
k4 = b""
for _ in range(len(data)):
    a = b''
    for _ in range(8):
        a += str(L4.next()).encode()
    k4 += long_to_bytes(int(a, 2))

L5 = LFSR(fpoly=[5, 4, 2, 1], initstate='random', verbose=True)
data = L5.runFullCycle()
k5 = b""
for _ in range(len(data)):
    a = b''
    for _ in range(8):
        a += str(L5.next()).encode()
Пример #17
0
 def create_LFSR_register_1(self):
     feedback_tap_polynome_R1 = self.convert_feedback_tap(self.feedback_tap_R1)
     L1=LFSR(fpoly=feedback_tap_polynome_R1,initstate=self.start_value_R1,verbose=False)
     tempseq=L1.runKCycle(self.primary_code_lenght)
     self.primCodeR1=L1.seq
Пример #18
0
def lfsr_lib(L: LFSR, bits, length):
    for i in range(length - 1):
        if i >= (bits - 1):
            yield L.next()
        else:
            L.next()
Пример #19
0
 def create_LFSR_register_2(self):
     feedback_tap_polynome_R2 = self.convert_feedback_tap(self.feedback_tap_R2)
     L2=LFSR(fpoly=feedback_tap_polynome_R2,initstate=self.start_value_R2,verbose=False)
     tempSeq = L2.runKCycle(self.primary_code_lenght)
     self.primCodeR2=L2.seq
Пример #20
0
def prbs(Tmax, Tmin, initstate='random'):
    '''Pseudo Random Binary signal (PRBS)

    Args:
        Tmax: maximum number of samples in one state
        Tmin: minimum number of samples in one state
        initstate: initial state of the linear feedback state register
            'ones': binary numpy array of ones, dimension = (length register,)
            'random': random binary numpy array, dimension = (length register,)

    Returns:
        PRBS as a numpy array

    Notes:
        The Linear Feedback Shift Register (LFSR) can be installed
        from PyPi: https://pypi.org/project/pylfsr/
        or from the source:  https://github.com/Nikeshbajaj/Linear_Feedback_Shift_Register
    '''
    if not isinstance(Tmax, int):
        raise TypeError('`Tmax` must be an integer')

    if Tmax < 2:
        raise ValueError('`Tmax` must be > 2')

    if not isinstance(Tmin, int):
        raise TypeError('`Tmax` must be an integer')

    if Tmin < 1:
        raise ValueError('`Tmin` must be > 1')

    if Tmin >= Tmax:
        raise ValueError('`Tmax` must be strictly superior to `Tmin`')

    __init_availabble__ = ['random', 'ones']
    if initstate not in __init_availabble__:
        raise ValueError(f'`initstate` must be either {__init_availabble__}')

    # get the register length
    n = np.ceil(Tmax / Tmin)
    if n < 2 or n > 31:
        raise ValueError('The PRBS cannot be generated, ' 'decompose the signal in two sequences')

    # Linear feedback register up to 32 bits
    fpoly = {
        2: [2, 1],
        3: [3, 1],
        4: [4, 1],
        5: [5, 2],
        6: [6, 1],
        7: [7, 1],
        8: [8, 4, 3, 2],
        9: [9, 4],
        10: [10, 3],
        11: [11, 2],
        12: [12, 6, 4, 1],
        13: [13, 4, 3, 1],
        14: [14, 8, 6, 1],
        15: [15, 1],
        16: [16, 12, 3, 1],
        17: [17, 3],
        18: [18, 7],
        19: [19, 5, 2, 1],
        20: [20, 3],
        21: [21, 2],
        22: [22, 1],
        23: [23, 5],
        24: [24, 7, 2, 1],
        25: [25, 3],
        26: [26, 6, 2, 1],
        27: [27, 5, 2, 1],
        28: [28, 3],
        29: [29, 2],
        30: [30, 23, 2, 1],
        31: [31, 3],
    }

    L = LFSR(fpoly=fpoly[n], initstate=initstate, verbose=False)

    seq = []
    for n in range(L.expectedPeriod):
        L.next()
        seq.append(L.state[0])

    seq_padded = np.repeat(seq, Tmin)

    # check generated PRBS
    assert seq_padded.shape[0] == L.expectedPeriod * Tmin
    assert max(len(list(v)) for g, v in itertools.groupby(seq_padded)) == Tmax
    assert min(len(list(v)) for g, v in itertools.groupby(seq_padded)) == Tmin

    return seq_padded
import numpy as np
from pylfsr import LFSR
## Example 1  ## 5 bit LFSR with x^5 + x^2 + 1
L = LFSR()
L.info()
L.next()
L.runKCycle(10)
L.runFullCycle()
L.info()
tempseq = L.runKCycle(10000)    # generate 10000 bits from current state

## Example 2  ## 5 bit LFSR with custum state and feedback polynomial
state = [0,0,0,1,0]
fpoly = [5,4,3,2]
L1 = LFSR(fpoly=fpoly,initstate =state, verbose=True)
L1.info()
tempseq = L1.runKCycle(10)
tempseq
L1.set(fpoly=[5,3])

## Example 3 ## TO visualize the process with 3-bit LFSR, with default counter_start_zero = True
state = [1,1,1]
fpoly = [3,2]
L = LFSR(initstate=state,fpoly=fpoly)
print('count \t state \t\toutbit \t seq')
print('-'*50)
for _ in range(15):
    print(L.count,L.state,'',L.outbit,L.seq,sep='\t')
    L.next()
print('-'*50)
print('Output: ',L.seq)