当前位置: 首页>>代码示例>>Python>>正文


Python BitVector.close_file_object方法代码示例

本文整理汇总了Python中BitVector.close_file_object方法的典型用法代码示例。如果您正苦于以下问题:Python BitVector.close_file_object方法的具体用法?Python BitVector.close_file_object怎么用?Python BitVector.close_file_object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BitVector的用法示例。


在下文中一共展示了BitVector.close_file_object方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: messwithfile

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
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
开发者ID:igalfsg,项目名称:ECE404,代码行数:29,代码来源:Average_flegmann.py

示例2: EncryptFile

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
def EncryptFile(inputFileName, outputFileName, roundKeyList, KeyPermutation1_List, KeyPermutation2_List, SBoxes_Dict_List, PBox_List, ShiftInfoDict, modeChar):
	#open output file for writing and create BV instance of input file
	outputTextFile = open(outputFileName, "wb")
	inputFile_bv = BitVector(filename = inputFileName)
	nullByte_bv = BitVector(size = 8)
	nullChar = chr(int('00000000',2))
	#If decrypting --> retrieve size of output file (to aid with stripping of null bytes at end)
	if (modeChar == 'D'):
		fileSize = os.path.getsize(inputFileName)
	byteCount = 0

	#Scan in 64-Bit blocks of file at a time
	while (inputFile_bv.more_to_read):
		bitBlock_bv = inputFile_bv.read_bits_from_file(64)
		if bitBlock_bv.length() > 0:
			#Pad bit block with trailing zeros if necessary
			if (bitBlock_bv.length() != 64):
				bitBlock_bv.pad_from_right(64-bitBlock_bv.length())
				# bytesShort = (64 - bitBlock_bv.length())/8
				# bytesShort_bv = BitVector(int = bytesShort)
				# for ind in range(0, bytesShort):
				# 	bitBlock_bv = bitBlock_bv + bytesShort_bv

			#Split Bit Vector into 2-32Bit halves
			[lBV, rBV] = bitBlock_bv.divide_into_two()

			#Perform 1st Round of Encryption
			[lBV, rBV] = Encrypt_64Bit_Block(lBV, rBV, roundKeyList[0], SBoxes_Dict_List, PBox_List)

			#Perform Remaining 15 Rounds of Encryption
			for roundNum in range(1,16):
				#Retrieve Round Key
				round_key = roundKeyList[roundNum]
				#Call 64-bit Block Encryption Function
				[lBV, rBV] = Encrypt_64Bit_Block(lBV, rBV, round_key, SBoxes_Dict_List, PBox_List)

			#Concatenate Left and Right Halves of 64-Bit Block
			encryptedBitBlock_bv = rBV + lBV
			
			#Check for Padded NULL bytes if in "Decrypt" Mode
			ind = 0
			outputText = encryptedBitBlock_bv.getTextFromBitVector()
			if (modeChar == 'D'):
				byteCount = byteCount + 8
				if (byteCount > (fileSize - 8)):
					outputText = outputText.strip(nullChar) 

			#Write Output To Output File
			#print outputText
			outputTextFile.write(outputText)

	#Close Files
	outputTextFile.close()
	inputFile_bv.close_file_object()
	return
开发者ID:timtrippel,项目名称:Encryption-Tools,代码行数:57,代码来源:DES_ttrippel.py

示例3: calculateHash

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
def calculateHash(filename):
	size = os.path.getsize(filename)
	size=size-1
	input_len=size*8	
	binary = BitVector(filename=filename)
	bv1 = binary.read_bits_from_file(8 * size)
	#padding and appending size
	rem=len(bv1)%1024
	if (rem==0):
	        newblock=BitVector(intVal=0, size=896)
	        newblock[0]=1
	        in_len=BitVector(intVal=input_len, size=128)
	        newblock=newblock+in_len
	        bv1=bv1+newblock	
	elif (rem<=896):
		one=BitVector(intVal=1)
	        zero=BitVector(intVal=0, size=1)
	        bv1=bv1+one
	        while len(bv1)%1024!=896:
	        	bv1=bv1+zero
	        in_len=BitVector(intVal=input_len, size=128)
	        bv1=bv1+in_len

	elif (rem>896) and (rem<1024):
		one=BitVector(intVal=1)
	        zero=BitVector(intVal=0, size=1)
	        bv1=bv1+one
	        while (len(bv1)%1024)!=0:
	        	bv1=bv1+zero
	        newblock=BitVector(intVal=0, size=896)
	        newblock[0]=1
	        bvlen=BitVector(intVal=input_len, size=128)
	        newblock=newblock+bvlen
	        bv1=bv1+newblock
	
	binary.close_file_object()
	K_init() #initialize K.
	iv=initVec_init()
	block=[]
	counter=0
	for i in range(0, len(bv1)):
		block.append(bv1[i])
		counter=counter+1
		if counter==1024:
			counter=0
			iv=f(block, iv)
			block=[]
        hash=[hex(iv[0]),hex(iv[1]),hex(iv[2]),hex(iv[3]),hex(iv[4]),hex(iv[5]),hex(iv[6]),hex(iv[7])]
	hash=striphex(hash)
	final_hash="" #final hash in CSV form
	for i in hash:
		final_hash=final_hash+i+","
	final_hash=final_hash[0:len(final_hash)-1]	
	return final_hash
开发者ID:CrocKim,项目名称:Introduction-to-Computer-Security-ECE404,代码行数:56,代码来源:hw8.py

示例4: init_des

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
def init_des():
	# Check use of program
	if (len(sys.argv) != 5):
		input_file = get_input_file()
		output_file = get_output_file()
		encrypt_or_decrypt = get_encrypt_or_decrypt()
		nkey = get_encryption_key()
	else:
		input_file = sys.argv[1]
		output_file = sys.argv[2]
		
		with open(sys.argv[3]) as fp:
			key = [x.strip('\n') for x in fp.readlines()]
			key = ''.join(key)
			if (len(key) != 8):
				sys.exit("Error: Encryption key must be 8 characters long. Please modify your key file and try again.")
			user_key_bv = BitVector(textstring = key)
			nkey = user_key_bv.permute(key_permutation_1)	

		encrypt_or_decrypt = sys.argv[4][1]

		if (encrypt_or_decrypt != 'e') and (encrypt_or_decrypt != 'd'):
			sys.exit("Usage: python DES_Price.py <input_file> <output_file> <key_file> -e/d")

	# Initialize input file as bit vector
	bv_input = BitVector(filename = input_file)
	file_out = open(output_file, 'wb')
	result_bv = BitVector(size = 0)

	sboxs = assemble_sboxes("s-box-tables.txt")

	if (encrypt_or_decrypt == "e"):
		print("Implementing DES encryption on '%s'..." % input_file)
	else:
		print("Implementing DES decryption on '%s'..." % input_file)

	# Begin either encryption/decryption
	result_bv = des(encrypt_or_decrypt, bv_input, result_bv, nkey, sboxs)

	if (encrypt_or_decrypt == "e"):
		print("Writing cipher-text to '%s'..." % output_file)
	else:
		print("Writing plain-text to '%s'..." % output_file)

	result_bv.write_to_file(file_out)

	print("DES complete!")

	bv_input.close_file_object()
	file_out.close()
开发者ID:michael-pr,项目名称:Security,代码行数:52,代码来源:des_block.py

示例5: init_des

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
def init_des():
	if (len(sys.argv) != 5):
		input_file = get_input_file()
		output_file = get_output_file()
		encrypt_or_decrypt = get_encrypt_or_decrypt()
		nkey = get_encryption_key()
	else:
		input_file = sys.argv[1]
		output_file = sys.argv[2]
		
		with open(sys.argv[3]) as fp:
			nkey = [x.strip('\n') for x in fp.readlines()]
			nkey = ''.join(nkey)
			if (len(nkey) != 8):
				sys.exit("Error: Encryption key must be 8 characters long. Please modify your key file and try again.")

		if (sys.argv[4] == "-e"):
			encrypt_or_decrypt = "e"
		elif (sys.argv[4] == "-d"):
			encrypt_or_decrypt = "d"
		else:
			sys.exit("Usage: python DES_Price.py <input_file> <output_file> <key_file> -e/d")

	sboxs = assemble_sboxes()
	rkeys = generate_round_keys(nkey)

	# Initialize input file as bit vector
	bv_input = BitVector(filename = input_file)
	file_out = open(output_file, 'wb')
	result_bv = BitVector(size = 0)

	if (encrypt_or_decrypt == "e"):
		print("Implementing DES encryption on '%s'..." % input_file)
	else:
		print("Implementing DES decryption on '%s'..." % input_file)

	result_bv = des(encrypt_or_decrypt, bv_input, result_bv, sboxs, rkeys)

	if (encrypt_or_decrypt == "e"):
		print("Writing cipher-text to '%s'..." % output_file)
	else:
		print("Writing plain-text to '%s'..." % output_file)

	result_bv.write_to_file(file_out)

	print("DES complete!")

	bv_input.close_file_object()
	file_out.close()
开发者ID:michael-pr,项目名称:Security,代码行数:51,代码来源:hw_backup_2.py

示例6: HashbyGhost

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
def HashbyGhost():
	dirScan = glob('input/*.*')
	fileCount = 0
	while(fileCount < len(dirScan)):
		bv = BitVector(filename = dirScan[fileCount])
		
		myHash = BitVector(size = 32)
		
		while (bv.more_to_read):
			bv1 = bv.read_bits_from_file(8)
			myHash[0:8] = bv1 ^ myHash[0:8]
			myHash << 8
		
		bv.close_file_object()
		myHexHash = myHash.getHexStringFromBitVector()
		dumpFile = open('output/output.txt', 'a')
		dumpFile.write('\n')
		dumpFile.write(dirScan[fileCount])
		dumpFile.write(":")
		dumpFile.write(myHexHash)
		dumpFile.close()
		fileCount += 1
开发者ID:sethukrishna,项目名称:hashbyghost,代码行数:24,代码来源:Hash.py

示例7: print

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
    "\nDisplay bit vectors written out to file and read back from the file and their respective lengths:")
print(str(bv1) + " " + str(bv3))
print(str(len(bv1)) + " " + str(len(bv3)))
os.remove(fpath)

print("\nExperiments with reading a file from the beginning to end:")
bv = BitVector(filename=testinput4)
print("\nHere are all the bits read from the file:")
while (bv.more_to_read):
    bv_read = bv.read_bits_from_file(64)
    print(bv_read)
print("\n")

print(
    "\nExperiment with closing a file object and start extracting bit vectors from the file from the beginning again:")
bv.close_file_object()
bv = BitVector(filename=testinput4)
bv1 = bv.read_bits_from_file(64)
print(
    "\nHere are all the first 64 bits read from the file again after the file object was closed and opened again:")
print(bv1)
FILEOUT = open(testinput5, 'wb')
bv1.write_to_file(FILEOUT)
FILEOUT.close()

print(
    "\nExperiment in 64-bit permutation and unpermutation of the previous 64-bit bitvector:")
print(
    "The permutation array was generated separately by the Fisher-Yates shuffle algorithm:")
bv2 = bv1.permute([22, 47, 33, 36, 18, 6, 32, 29, 54, 62, 4,
                   9, 42, 39, 45, 59, 8, 50, 35, 20, 25, 49,
开发者ID:gsnedders,项目名称:BitVector,代码行数:33,代码来源:BitVectorDemo.py

示例8: cases

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
# Create test cases (modified encryption keys) *Assuming number of test cases does not overflow 8 character key
key_bv = BitVector(textstring = key)
modified_keys = []
for i in range(NUM_TEST_CASES):
	new_key_bv = key_bv[:]
	new_key_bv[i] = 1 if (new_key_bv[i] == 0) else 0
	modified_keys.append(new_key_bv)

# Create cipher texts with modified key values
key_cipher_text_test_cases = []
for i in range(NUM_TEST_CASES):
	empty_bv = BitVector(size = 0)
	test_case_bv_fp = BitVector(filename = input_filename)
	new_encrypted_bv = DES_Price.des('e', test_case_bv_fp, empty_bv, modified_keys[i], sboxs)
	key_cipher_text_test_cases.append(new_encrypted_bv)
	test_case_bv_fp.close_file_object()

# (Optional) Write new cipher-text's to files for storaging

# Compare original cipher-text to modified key value cipher-text's
num_changed_bits_per_key_test = []

for i in range(NUM_TEST_CASES):
	num_changed_bits_per_key_test.append(0)

length_of_cipher_text = len(key_cipher_text_test_cases[0])
for i in range(NUM_TEST_CASES):
	for j in range(length_of_cipher_text):
		num_changed_bits_per_key_test[i] += 1 if (key_cipher_text_test_cases[i][j] != original_encrypted_bv[j]) else 0

confusion_average = 0
开发者ID:michael-pr,项目名称:Security,代码行数:33,代码来源:analysis.py

示例9: BitVector

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
	hb4 = BitVector(intVal=(int(hb4) + int(e))%(2**64), size=64)
	hb5 = BitVector(intVal=(int(hb5) + int(f))%(2**64), size=64)
	hb6 = BitVector(intVal=(int(hb6) + int(g))%(2**64), size=64)
	hb7 = BitVector(intVal=(int(hb7) + int(h))%(2**64), size=64)

#Output Hash Value
message_hash_code = hb0 + hb1 + hb2 + hb3 + hb4 + hb5 + hb6 + hb7
outputTextFile.write("%s" % (message_hash_code.get_hex_string_from_bitvector()))

#Check if Hash Value is Correct
sha_512 = hashlib.sha512(inputString)
hex_dig = sha_512.hexdigest()
if (message_hash_code.get_hex_string_from_bitvector() == hex_dig): print "SUCCESS"

#Close Files
inputFile_bv.close_file_object()
outputTextFile.close()
sys.exit(0)

#----------------------------------------------------------------------------
#Sample Output:
#----------------------------------------------------------------------------
#Input Message (new line characters added to increase readability):
#----------------------------------------------------------------------------
# We the people of the United States, 
# in order to form a more perfect union, 
# establish justice, insure domestic tranquility, 
# provide for the common defense, 
# promote the general welfare, and secure the 
# blessings of liberty to ourselves and our posterity, 
# do ordain and establish this Constitution 
开发者ID:timtrippel,项目名称:Encryption-Tools,代码行数:33,代码来源:SHA512.py

示例10: RSA

# 需要导入模块: import BitVector [as 别名]
# 或者: from BitVector import close_file_object [as 别名]
class RSA():
	def __init__(self, public_key, private_key, p_val, q_val, inputFileName, outputFileName, modSize):
		self.e = public_key[0]
		self.d = private_key[0]
		self.n = public_key[1]
		self.p = p_val
		self.q = q_val
		self.p_bv = BitVector(intVal = self.p)
		self.q_bv = BitVector(intVal = self.q)
		self.modSize = modSize
		self.blockSize = self.modSize / 2
		self.inputFileName = inputFileName
		self.outputFileName = outputFileName
		self.inputFile_bv = None
		self.outputFile = None

	def OpenFiles(self):
		self.inputFile_bv = BitVector(filename = self.inputFileName)
		self.outputFile = open(self.outputFileName, "wb")
		return

	def CloseFiles(self):
		self.inputFile_bv.close_file_object()
		self.outputFile.close()
		return

	def ModExpo(self, a, b, mod):
		result = 1
		while(b > 0):
			if (b&1):
				result = (result * a) % mod
			b = b >> 1
			a = (a * a) % mod
		return result

	def CRT(self, nextBitBlock_bv):
		#Implementation of Chinese Remainder Theorem (CRT) to speed-up modular exponentiation
		q_MI = self.q_bv.multiplicative_inverse(self.p_bv)
		p_MI = self.p_bv.multiplicative_inverse(self.q_bv)
		Xp = self.q * int(q_MI)
		Xq = self.p * int(p_MI)
		#Using Fermat's Little Theorem --> Calculate Vp and Vq
		v_p = self.d % (self.p-1)
		v_q = self.d % (self.q-1)
		#Calculate Vp and Vq for CRT
		Vp = self.ModExpo(int(nextBitBlock_bv), v_p, self.p)
		Vq = self.ModExpo(int(nextBitBlock_bv), v_q, self.q)
		#Recover Plain-Text Bit Block
		plain_text = ((Vp*Xp) + (Vq*Xq)) % self.n
		plain_text_bv = BitVector(intVal = plain_text, size = 256)
		return plain_text_bv

	def encrypt_RSA(self):
		self.OpenFiles() #Open I/O files
		#scan in bits from input file and perform encryption algorithm
		while(self.inputFile_bv.more_to_read):
			nextBitBlock_bv = self.inputFile_bv.read_bits_from_file(self.blockSize) #Scan in bit block
			if (nextBitBlock_bv.length() != self.blockSize):
				#Append newline characters to end of bit block
				num_NL_chars = (self.blockSize - nextBitBlock_bv.length()) / 8
				inputBitBlockText = nextBitBlock_bv.get_hex_string_from_bitvector()
				inputBitBlockText = inputBitBlockText + "0a"*num_NL_chars
				nextBitBlock_bv = BitVector(hexstring = inputBitBlockText)
			nextBitBlock_bv.pad_from_left(self.blockSize) #Pad bit block with zeros
			cipher_text = self.ModExpo(int(nextBitBlock_bv), self.e, self.n) #generate cipher-text "integer" using modular exponentiation
			outputBitBlock_bv = BitVector(intVal = cipher_text, size = self.modSize) #generate 256-bit bit-vector of cipher-text "integer"
			outputBitBlock_bv.write_to_file(self.outputFile) #Write cipher text to output file
		self.CloseFiles() #Close I/O Files
		return

	def decrypt_RSA(self):
		fileSize = os.path.getsize(self.inputFileName) #determine size of input file to be decrypted
		numBitBlocks = fileSize / (self.modSize / 8) #determine size of decryption bit blocks
		bitBlockInd = 1 #bit block index counter to know when to check for new line characters to be stripped from decrypted text
		self.OpenFiles() #Open I/O files
		#scan in bits from input file and perform decryption algorithm
		while(self.inputFile_bv.more_to_read):
			nextBitBlock_bv = self.inputFile_bv.read_bits_from_file(self.modSize)	#Scan in bit block
			nextBitBlock_bv = self.CRT(nextBitBlock_bv) #Perform modular exponentiation using CRT to speed up process
			[zeros_pad, nextBitBlock_bv] = nextBitBlock_bv.divide_into_two() #remove padded zeros
			if (bitBlockInd == numBitBlocks):
				#Strip appended new line characters
				outputTextHex = nextBitBlock_bv.get_hex_string_from_bitvector()
				outputTextHex = outputTextHex.strip("0a")
				nextBitBlock_bv = BitVector(hexstring = outputTextHex)
			nextBitBlock_bv.write_to_file(self.outputFile) #write bit block to output file
			bitBlockInd = bitBlockInd + 1 #increment bit block index counter
		self.CloseFiles() #Close I/O Files
		return
开发者ID:timtrippel,项目名称:Encryption-Tools,代码行数:91,代码来源:RSA256.py


注:本文中的BitVector.close_file_object方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。