#17-bit lfsr---This is one of the two LFSR's used in #the (broken) Content Scrambling System to copy-protect DVDs, #and is used in one of the problems in Assignment 2. #State is implemented as an integer; this will be overridden #by initstate. #I used a lot of bitwise operations--shifts and masks and the like-- #rather than the more expensive operations of division and remaindering. #Probably unnecessary in small examples of this scale. import bytestuff state = 1 #The key is a string which we will convert to #a long integer and then grab the low-order 17 bits #as a regular int to initialize the register. def init_state(key): global state bytelist=bytestuff.ascii_to_bytes(key) state=int(bytestuff.bytes_to_long(bytelist)&(0x1ffff)) #update the register and return the new high-order bit def update_state(): global state lowbit=state&1 tapbit=((1<<14)&state)>>14 state=(state>>1) highbit=(lowbit^tapbit)<<16 state = state|highbit return lowbit^tapbit #Get the next byte from the register def next_byte(): val=0 for j in range(8): val=2*val+update_state() return val #Return a list of the next k bytes from the register def get_bytes(k): blist=[] for j in range(k): blist.append(next_byte()) return blist