本文整理汇总了Python中BitVector类的典型用法代码示例。如果您正苦于以下问题:Python BitVector类的具体用法?Python BitVector怎么用?Python BitVector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BitVector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GenerateSubTable
def GenerateSubTable(modeChar):
#Table Generation Variables
modulus_poly = BitVector(bitstring = '100011011') #irreducible polynomial used in AES --> (x^8 + x^4 + x^3 + x + 1)
byte_c = BitVector(bitstring = '01100011') #Encryption Mangle-Byte
byte_d = BitVector(bitstring = '00000101') #Decryption Mangle-Byte
scrambledBV = BitVector(size = 8)
#Initialize 16x16 Sub-Table with all 0 Bit-Vectors
zeroBV = BitVector(size = 8)
LookUpTable = [[zeroBV.deep_copy() for x in range(16)] for y in range(16)]
#Set Each Table Entry to Multiplicative Inverse (in GF(2^8)) of Bit-Vector Concatenation of Row and Column 4-bit Bit-Vectors
for x in range(16):
for y in range(16):
rowBV = BitVector(intVal=x, size=4) #Creat Bit Vector for Row Value
colBV = BitVector(intVal=y, size=4) #Creat Bit Vector for Column Value
tableBV_entry = rowBV + colBV
#Perform MI & Bit-Mangling on Table Entries
#If Mode is Encryption...
if modeChar == 'E':
#Only find MI of all bit-vectors except 0
if (x != 0) or (y != 0):
tableBV_entry = tableBV_entry.gf_MI(modulus_poly, 8) #Determine MI of table entry Bit-Vector
for bit_ind in range(0, 8):
newBit = tableBV_entry[bit_ind]^tableBV_entry[(bit_ind+1)%8]^tableBV_entry[(bit_ind+2)%8]^tableBV_entry[(bit_ind+3)%8]^tableBV_entry[(bit_ind+4)%8]^byte_c[bit_ind]
scrambledBV[bit_ind] = newBit
#If Mode is Decryption...
else:
for bit_ind in range(0, 8):
newBit = tableBV_entry[(bit_ind+6)%8]^tableBV_entry[(bit_ind+3)%8]^tableBV_entry[(bit_ind+1)%8]^byte_d[bit_ind]
scrambledBV[bit_ind] = newBit
#Only find MI of all bit-vectors except 0
if int(scrambledBV) != 0:
scrambledBV = scrambledBV.gf_MI(modulus_poly, 8) #Determine MI of table entry Bit-Vector
LookUpTable[x][y] = copy.deepcopy(scrambledBV)
return LookUpTable
示例2: change_one_bit
def change_one_bit():
subprocess.call(['cp message.txt temp.tmp'],shell=True)
file_size = os.path.getsize(input_file)
num_blocks = file_size / 8
if file_size % 8 != 0:
with open(input_file,"a") as filein:
for i in range(0,file_size % 8):
filein.write(" ")
for i in range(0,num_blocks):
#subprocess.call(['cp temp.tmp temp2.tmp'],shell=True)
bv = BitVector( filename = "temp.tmp" )
os.remove("message.txt")
FILEOUT = open("message.txt",'ab')
for j in range(0,num_blocks):
bitvcec = bv.read_bits_from_file( 64 )
if j == i:
rand = randint(0,63)
bitvec[rand] ^= 1
bitvec.write_to_file(FILEOUT)
FILEOUT.close()
subprocess.call(['./DES_baio.py'],shell=True)
os.close(filehandle)
os.remove(input_file)
move(final, input_file)
示例3: diffusion_or_confusion
def diffusion_or_confusion(RE,LE,encrypt_or_decrypt,rkey,s_box):
bitvec = BitVector(size=64)
for i in range(16):
## write code to carry out 16 rounds of processing
TMP = RE
## Expansion_permutation
RE = RE.permute(expansion_permutation)
# Get the order of key right
if encrypt_or_decrypt == "encrypt":
RE = RE ^ rkey[i]
elif encrypt_or_decrypt == "decrypt":
RE = RE ^ rkey[15 - i]
## Do the S_boxes subsititution
k=0
output = BitVector(size = 0)
for ct in range(8):
row = RE[k]*pow(2,1) + RE[k+5]*pow(2,0)
col = RE[k+1]*pow(2,3) + RE[k+2]*pow(2,2)+ RE[k+3]*pow(2,1) + RE[k+4]*pow(2,0)
sbox_val = s_box[ct][row][col]
sbox_bv = BitVector(intVal = int(sbox_val), size = 4)
output += sbox_bv
k += 6
## Permutation with P-Box
output = output.permute(p_box_permutation)
## XOR with original LE
RE = LE ^ output
LE = TMP
## Add RE and LE up
bitvec = RE + LE
return bitvec
示例4: decrypt
def decrypt(encrypted_bv, key):
PassPhrase = "Hopes and dreams of a million years"
BLOCKSIZE = 16
numbytes = BLOCKSIZE // 8
# Reduce the passphrase to a bit array of size BLOCKSIZE:
bv_iv = BitVector(bitlist = [0]*BLOCKSIZE)
for i in range(0,len(PassPhrase) // numbytes):
textstr = PassPhrase[i*numbytes:(i+1)*numbytes]
bv_iv ^= BitVector( textstring = textstr )
# Reduce the key to a bit array of size BLOCKSIZE:
key_bv = BitVector(bitlist = [0]*BLOCKSIZE)
key_bv = BitVector(bitstring = key)
# Create a bitvector for storing the decrypted plaintext bit array:
msg_decrypted_bv = BitVector( size = 0 )
# Carry out differential XORing of bit blocks and decryption:
previous_decrypted_block = bv_iv
for i in range(0, len(encrypted_bv) // BLOCKSIZE):
bv = encrypted_bv[i*BLOCKSIZE:(i+1)*BLOCKSIZE]
temp = bv.deep_copy()
bv ^= previous_decrypted_block
previous_decrypted_block = temp
bv ^= key_bv
msg_decrypted_bv += bv
# Extract plaintext from the decrypted bitvector:
return msg_decrypted_bv.get_text_from_bitvector()
示例5: des
def des(encrypt_or_decrypt, input_file, output_file, key ):
bv = BitVector( filename = input_file )
FILEOUT = open( output_file, 'wb' )
bitvec = bv.read_bits_from_file( 64 ) ## assumes that your file has an integral
## multiple of 8 bytes. If not, you must pad it.
print bitvec
[LE, RE] = bitvec.divide_into_two()
示例6: pattern_to_dest
def pattern_to_dest(self,pattern,X):
# return -1 is reserved for random
bit_len = math.ceil(math.log(self.mesh_width*self.mesh_height,2))
bv = BitVector(intVal=X,size=bit_len)
if(pattern==Traffic_Patterns.random):
return -1;
elif(pattern==Traffic_Patterns.bit_complement):
return int(~bv)
elif(pattern==Traffic_Patterns.bit_reverse):
return int(bv.reverse())
elif(pattern==Traffic_Patterns.bit_rotation):
return int(bv<<1)
elif(pattern==Traffic_Patterns.transpose):
return 1
elif(pattern==Traffic_Patterns.shuffle):
t = bv[bit_len-1]
bv[bit_len-1] = bv[0]
bv[0] = t
return int(bv)
elif(pattern==Traffic_Patterns.manual):
return self.PE_dest[X]
示例7: get_c_byte_step
def get_c_byte_step( byte, encrypt ) :
byte = byte.reverse()
if(encrypt) :
c_d_byte = BitVector( bitstring = '11000110' )
xor_base = BitVector( bitstring = '10001111' )
else :
c_d_byte = BitVector( bitstring = '10100000' )
xor_base = BitVector( bitstring = '00100101' )
newByte = BitVector( bitstring = '00000000' )
xor_lists = [xor_base.deep_copy() >> x for x in range(8)]
for i, xor_list in enumerate(xor_lists) :
temp = xor_list & byte
newBit = get_xor_of_single_bv(temp)
newBit = newBit ^ c_d_byte[i]
newByte[i] = newBit
newByte = newByte.reverse()
return newByte
示例8: messwithfile
def messwithfile(rightf, messedf):
FILEOUT = open (messedf, 'wb')
lakey = DES_flegmann.get_encryption_key()
round_keys = DES_flegmann.extract_round_key(lakey)
tamano = os.path.getsize(rightf)
tamano = tamano / 8
bv = BitVector(filename = rightf)
count = 0
tot = 0
for index in range(8):
while (bv.more_to_read):
bitvec = bv.read_bits_from_file( 64 )
leng = bitvec.length()
pad = 64 - leng
if count == index:
bitvec.pad_from_right(pad)
bitvec[random.randint(0,15)] ^= 1
bitvec.write_to_file(FILEOUT)
count = count + 1
FILEOUT.close()
bv.close_file_object()
DES_flegmann.des(1, rightf, 'righte.txt',round_keys)
DES_flegmann.des(1, messedf, 'messede.txt', round_keys)
tot += checkdiff('righte.txt', 'messede.txt')
os.remove('righte.txt')
os.remove('messede.txt')
return tot / 8
示例9: AES_encrypt
def AES_encrypt(filename, key) :
encrypted_data = BitVector(size=0)
words_4 = get_first_four_words(BitVector( textstring = key ))
key_sch = Key_Schedule(words_4)
round_keys = key_sch.round_keys
input_blocks = get_input_blocks(filename)
for block in input_blocks :
state_array = convert_block_to_state_array(block)
state_array = add_round_key(state_array, round_keys[0])
for i in range(10) :
state_array = substitute_bytes(state_array)
state_array = shift_rows(state_array)
if not (i == 9):
state_array = mix_columns(state_array)
state_array = add_round_key(state_array, round_keys[i+1])
encrypted_data += convert_state_array_to_128bits(state_array)
FILEOUT = open( "encrypted.txt", 'wb' )
encrypted_data.write_to_file(FILEOUT)
FILEOUT.close()
示例10: AES_decrypt
def AES_decrypt(key) :
decrypted_data = BitVector(size=0)
#Split the input key into 4, 32 bit words
words_4 = get_first_four_words(BitVector( textstring = key ))
#Get the key schedule based on input key
key_sch = Key_Schedule(words_4)
round_keys = key_sch.round_keys
#Get input data in 128 bit blocks at a time
encrypted_blocks = get_input_blocks("encrypted.txt")
for block in encrypted_blocks :
#Do the pre-round processing
state_array = convert_block_to_state_array(block)
state_array = add_round_key(state_array, round_keys[10])
state_array = inv_shift_rows(state_array)
state_array = inv_substitute_bytes(state_array)
#Do the 10 rounds of processing
for i in reversed(range(1,10)) :
state_array = add_round_key(state_array, round_keys[i])
state_array = inv_mix_columns(state_array)
state_array = inv_shift_rows(state_array)
state_array = inv_substitute_bytes(state_array)
#Append decrypted data
state_array = add_round_key(state_array, round_keys[0])
decrypted_data += convert_state_array_to_128bits(state_array)
#Write decrypted data to file
FILEOUT = open( "decrypted.txt", 'wb' )
decrypted_data.write_to_file(FILEOUT)
FILEOUT.close()
示例11: decrypt
def decrypt(filename, private, p, q):
decrypted = []
## Open file and get the contents
encrypted = openFile(filename, False)
## Using the chinese remainder theorem
## pCRT = C^d mod p
## qCRT = C^d mod q
pCRT , qCRT = [], []
for block in encrypted:
pCRT.append(pow(block, private[0], p))
qCRT.append(pow(block, private[0], q))
## Geting bitvector versions of the p * q values for their multiplicative inverses
pBV = BitVector(intVal = p)
qBV = BitVector(intVal = q)
## Xp = q * (q^-1 mod p)
## Xq = p * (p^-1 mod q)
pX = q * int(qBV.multiplicative_inverse(pBV))
qX = p * int(pBV.multiplicative_inverse(qBV))
## C^d mod n = (VpXp + VqXq) mod n
for i in range(len(encrypted)):
decrypted.append(((pCRT[i] * pX) + (qCRT[i] * qX)) % private[1])
return decrypted
示例12: createKeys
def createKeys(eVAL):
## Setup the prime generator
pg = PrimeGenerator(bits=128, debug=0)
while(True):
p = pg.findPrime()
q = pg.findPrime()
## Check p and q are different
if p == q: continue
## Check left two MSB's are 1 (bin command returns 0b appended at front)
if not (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): continue
## Check that the totients of p and q are co-prime to e
if (bgcd(p-1, eVAL) != 1) or (bgcd(q-1, eVAL) !=1): continue
break
## Calculate modulus
n = p * q
## Calculate totient of n
tn = (p - 1) * (q-1)
modBV = BitVector(intVal = tn)
eBV = BitVector(intVal = eVAL)
## Calculate multiplicative inverse
d = eBV.multiplicative_inverse(modBV)
d = int(d)
## Create public and private sets
public, private = [eVAL, n], [d, n]
## Return items
return public, private, p, q, eVAL
示例13: CRT_simplify
def CRT_simplify(data, d, n, p, q) :
Vp = binary_exp(data, d, p)
Vq = binary_exp(data, d, q)
# Set all values for chinese remainder thm as stated in notes
# for better understanding later
M = n
m1 = p
m2 = q
M1 = M / m1
M2 = M / m2
# Convert the numbers to BitVector for easy MI
m1_bv = BitVector(intVal=m1)
m2_bv = BitVector(intVal=m2)
M1_bv = BitVector(intVal=M1)
M2_bv = BitVector(intVal=M2)
M1_inv = int(M1_bv.multiplicative_inverse(m1_bv))
M2_inv = int(M2_bv.multiplicative_inverse(m2_bv))
Xp = q * M1_inv
Xq = p * M2_inv
result = (Vp*Xp + Vq*Xq) % n
return result
示例14: build_s_box
def build_s_box(encrypt_or_decrypt):
AES_modulus = BitVector(bitstring='100011011')
c = BitVector(bitstring='01100011')
d = BitVector(bitstring='00000101')
new_sub_bytes = []
if (encrypt_or_decrypt == 'e'):
for i in range(0, 256):
# Build lookup table
a = BitVector(intVal = i, size=8).gf_MI(AES_modulus, 8) if i != 0 else BitVector(intVal=0)
# Byte scrambling
a1,a2,a3,a4 = [a.deep_copy() for x in range(4)]
a ^= (a1 >> 4) ^ (a2 >> 5) ^ (a3 >> 6) ^ (a4 >> 7) ^ c
new_sub_bytes.append(int(a))
else:
for i in range(0, 256):
b = BitVector(intVal = i, size=8)
# byte scrambling
b1,b2,b3 = [b.deep_copy() for x in range(3)]
b = (b1 >> 2) ^ (b2 >> 5) ^ (b3 >> 7) ^ d
check = b.gf_MI(AES_modulus, 8)
b = check if isinstance(check, BitVector) else 0
new_sub_bytes.append(int(b))
sub_byte_table = []
for i in range(16):
sub_byte_table.append([])
for j in range(16):
sub_byte_table[i].append(new_sub_bytes[(i * 16) + j])
return sub_byte_table
示例15: gen_w4
def gen_w4(w3,ri):
w3r = w3 << 8
print ("w"+str((ri-1)*4+3)+" after one byte circular rotation")
print (w3r.get_hex_string_from_bitvector())
k_subbytes = BitVector(size = 0)
for i in range(4):
row = w3r[i*8:i*8+4].int_val()
print (row),
col = w3r[i*8+4:i*8+8].int_val()
print (col),
k_sub = BitVector(intVal = sbox[16*row+col], size = 8)
print(k_sub),
print(k_sub.get_hex_string_from_bitvector())
k_subbytes += k_sub
print ("k_subbytes")
print (k_subbytes),
print (k_subbytes.get_hex_string_from_bitvector())
rcbv = BitVector(intVal = Rcon[ri], size = 32)
print (rcbv)
kg = k_subbytes ^ rcbv
print ("kg")
print (kg),
print (kg.get_hex_string_from_bitvector())
return kg