示例#1
0
 def test_encrypt(self):
     msg = b'My private message'
     pw = b'my private key'
     pk = str(seccure.passphrase_to_pubkey(pw))
     self.assertEqual(seccure.decrypt(seccure.encrypt(msg, pk), pw), msg)
     for c in seccure.curves:
         self.assertEqual(
             seccure.decrypt(
                 seccure.encrypt(
                     msg,
                     str(seccure.passphrase_to_pubkey(pw, curve=c)),
                     curve=c),
                 pw, curve=c),
             msg)
示例#2
0
 def test_encrypt(self):
     msg = b'My private message'
     pw = b'my private key'
     pk = str(seccure.passphrase_to_pubkey(pw))
     self.assertEqual(seccure.decrypt(seccure.encrypt(msg, pk), pw), msg)
     for c in seccure.curves:
         self.assertEqual(
             seccure.decrypt(
                 seccure.encrypt(
                     msg,
                     str(seccure.passphrase_to_pubkey(pw, curve=c)),
                     curve=c),
                 pw, curve=c),
             msg)
示例#3
0
文件: helpers.py 项目: t2d/pyanotel
def asym_encrypt(plaintext, public_key):
    ''' encryption with ECIES '''
    if isinstance(plaintext, list):
        plaintext = ''.join(map(str, plaintext))
    ciphertext = seccure.encrypt(plaintext, public_key)
    encoded_ciphertext = b64encode(ciphertext)
    return encoded_ciphertext
示例#4
0
 def test_encrypt(self):
     msg = b'My private message'
     pw = b'my private key'
     self.assertEqual(
         seccure.decrypt(
             seccure.encrypt(msg, str(seccure.passphrase_to_pubkey(pw))),
             b'my private key'), msg)
示例#5
0
    def encrypt(self, message, public_key):
        """Encrypts the given message with the provided public key.

           @param message The message to encrypt.
           @param public_key The public key to use.
           @return An encrypted version of @message.
        """
        assert type(message) is bytes
        cipher = seccure.encrypt(message, public_key, mac_bytes=self.mac)
        self.logger.debug("Encrypted " + str(len(message)) + " bytes to '" + public_key.decode("utf-8") + "'")
        return cipher
def main(argv):
    if len(argv) != 4:
        print 'usage: ./icmpTest.py <OD2 IP Address> <OD1 IP Address> <TimeoutInSeconds> <src_port>'
        exit(1)
    # print argv

    timestamp = int(time.time())

    ## Encrypt someString with controller's public key
    pubkey = b'8W;>i^H0qi|J&$coR5MFpR*Vn'  ## = str(seccure.passphrase_to_pubkey(b'my private key'))

    # if(int(argv[1])<10):
    #	argv[1] = 'Siegebreak000'+argv[1]
    # elif(int(argv[1])<100):
    #	argv[1] = 'Siegebreak00'+ argv[1]
    # elif(int(argv[1])<1000):
    #	argv[1] = 'Siegebreak0'+argv[1]
    # elif(int(argv[1])<10000):
    #	argv[1] = 'Siegebreak' + argv[1]
    # else:
    #	print "Timeout value not permitted; Try again with timeout<10000"
    #	exit(0)

    # argv[1]=argv[1]+'@'+str(timestamp)
    # print argv[1]

    # encryptedString = seccure.encrypt(argv[1], pubkey)

    if (int(argv[2]) < 10):
        argv[2] = 'Siege000' + argv[2]
    elif (int(argv[2]) < 100):
        argv[2] = 'Siege00' + argv[2]
    elif (int(argv[2]) < 1000):
        argv[2] = 'Siege0' + argv[2]
    elif (int(argv[2]) < 10000):
        argv[2] = 'Siege' + argv[2]
    else:
        print "Timeout value not permitted; Try again with timeout<10000"
        exit(0)

    padding = (15 - len(argv[1]))

    argv[2] = argv[2] + '@' + argv[1] + '#' + argv[3] + '$'
    # print argv[2]
    # print argv[2]

    encryptedString = seccure.encrypt(argv[2], pubkey)
    # print len(encryptedString)
    iter = randint(1, 3)
    iter = 1
    # print iter

    sendPing(argv[0], str(encryptedString), iter)
示例#7
0
 def on_click_send(self):
     self.conn = sqlite3.connect('BankDB.db')
     self.c = self.conn.cursor()
     self.date = datetime.datetime.now()
     self.id = s.encrypt(
         self.hashTransaction(self.date.time(), self.accID).encode(),
         str(s.passphrase_to_pubkey(b'my private key')))
     self.amt = s.encrypt(self.Amount.text().encode(),
                          str(s.passphrase_to_pubkey(b'my private key')))
     print("Transaction ID : " + str(self.id))
     print("\nAmount sent : " + str(self.amt))
     self.c.execute('INSERT INTO SAMPE VALUES(?, ?, ?, ?, ?, ?, ?);',
                    [(self.accID), (self.accID),
                     (self.ReceiversID.text()), self.amt,
                     (str(self.date.time())),
                     (str(self.date.date())), self.id])
     print("\nSuccessfully Transferred")
     # self.fetchdata = self.c.execute('SELECT NETBALANCE FROM USERS where ACCOUNT_ID = ?', [(self.accID)])
     # for i in self.fetchdata:
     # self.intbalnow = i[0]
     # self.c.execute('UPDATE USERS SET NETBALANCE = ? WHERE ACCOUNT_ID =?',[(self.intbalnow - int(self.Amount.text())), (self.accID)])
     self.conn.commit()
     self.close()
示例#8
0
文件: eccpgp.py 项目: xevrem/csdm
    def encrypt(self, data, filename='no_name.file'):
        struct = self.make_eccpgp_structure()
        struct['header']['filename'] = filename

        struct['header']['hash'] = sha1(data).hexdigest()

        sc = SymCiph()
        self._skey = sc.create_key()
        self._iv = sc.create_iv()
        struct['header']['key'] = b64enc(self._skey)
        struct['header']['iv'] = b64enc(self._iv)
        crypto = sc.create_crypto(self._skey, self._iv)

        struct['payload'] = b64enc(sc.encrypt(crypto, data))

        header = json.dumps(struct['header'])
        enc_header = seccure.encrypt(header.encode(),self._epub)
        struct['header'] = b64enc(enc_header)

        return struct
示例#9
0
    def encrypt(self, data, filename='no_name.file'):
        struct = self.make_eccpgp_structure()
        struct['header']['filename'] = filename

        struct['header']['hash'] = sha1(data).hexdigest()

        sc = SymCiph()
        self._skey = sc.create_key()
        self._iv = sc.create_iv()
        struct['header']['key'] = b64enc(self._skey)
        struct['header']['iv'] = b64enc(self._iv)
        crypto = sc.create_crypto(self._skey, self._iv)

        struct['payload'] = b64enc(sc.encrypt(crypto, data))

        header = json.dumps(struct['header'])
        enc_header = seccure.encrypt(header.encode(), self._epub)
        struct['header'] = b64enc(enc_header)

        return struct
示例#10
0
 def on_click_submit(self):
     self.conn = sqlite3.connect("BankDB.db")
     self.c = self.conn.cursor()
     self.h = hashlib.sha512()
     self.h.update(self.PasswordField.text().encode())
     self.hash = self.h.digest()
     print("The message digest : " + str(self.hash))
     print("The message digest size : " + str(self.h.digest_size))
     self.publicKey = str(s.passphrase_to_pubkey(b'my private key'))
     self.date = datetime.datetime.now()
     self.c.execute(
         "INSERT INTO USERS(NAME, USERNAME, PASSWORD, ACCOUNT_ID, PubKey) VALUES(?, ?, ?, ?, ?);",
         [(self.NameField.text()), (self.User_NameField.text()),
          (self.hash), (self.Account_NumberField.text()), (self.publicKey)])
     self.c.execute(
         "INSERT INTO SAMPE VALUES(00001, 00001, ?, ?, ?, ?, ?);",
         [(self.Account_NumberField.text()),
          (s.encrypt(self.NetBalance.text().encode(), self.publicKey)),
          (str(self.date.time())), (str(self.date.date())),
          self.hash_Transaction(self.date.time(),
                                self.Account_NumberField.text())])
     self.conn.commit()
     self.conn.close()
     self.close()
示例#11
0
def cipherText(texto):
    #print ('escriba texto  a cifrar')
    #simpleText= input()
    cipher_Text = seccure.encrypt(texto.encode(),str(generatePublicKey()).encode())
   # print(cipher_Text)
    return cipher_Text
示例#12
0
 def test_encrypt(self):
     msg = b'My private message'
     pw = b'my private key'
     self.assertEqual(seccure.decrypt(seccure.encrypt(msg,
                     str(seccure.passphrase_to_pubkey(pw))),
                         b'my private key'), msg)
示例#13
0
 for y in range(7):
     r.append(random.choice(enc_list))
     enc_list.remove(r[y])
     packet[y] = packet[y] + r[y]
     #print packet[y]
 
 #private_key = '101010101101111100010110011101010'
 private_key = random.choice(string.digits)
 #print private_key
 public_key = str(seccure.passphrase_to_pubkey(private_key))
 ciphertext = []
 decrypted = []
 
 ###Encryption phase
 for z in range(7):
     ciphertext.append(seccure.encrypt(packet[z][:-3], public_key))
     #print ciphertext[z]
 t2 = time.time()
     
 ###Decryption phase
 #For benchmarking and an easier to understand algorithm we are not fetching data from the different cloud sources and combining it as our purpose here is to test the speed of this proposed encryption algorithm against RSA
 #Ideally, this would go something like this -
 #RECEIVE packet data from CLOUD 1
 #RECEIVE packet data from CLOUD 2
 #RECEIVE packet data from CLOUD 3
 #RECEIVE packet data from CLOUD 4
 #RECEIVE packet data from CLOUD 5
 #RECEIVE packet data from CLOUD 6
 #RECEIVE packet data from CLOUD 7
 #RECEIVE packet data from CLOUD 8
 #Combine packets and store in the list cyphertext in the order that they appeared
示例#14
0
def test_ec_crypto():
    q,p = seccure.generate_keypair()
    c = seccure.encrypt(b'ABC' ,  p)
    print seccure.decrypt(c , q)
示例#15
0
def mooltipassMiniInit(mooltipass_device):	
	# Check for public key
	if not os.path.isfile("publickey.bin"):
		print "Couldn't find public key!"
		return
			
	# Check for export folder
	if not os.path.isdir("export"):
		print "Couldn't find export folder"
		return
	
	# Check for update bundle
	if not os.path.isfile("updatefile.img"):
		print "Couldn't find udpate file!"
		return
			
	# Read public key
	public_key = pickle_read("publickey.bin")

	# Loop
	try:
		temp_bool = 0
		while temp_bool == 0:
			# Operation success state
			success_status = True

			# Empty set password packet
			mooltipass_password = array('B')

			# We need 62 random bytes to set them as a password for the Mooltipass
			sys.stdout.write('Step 1... ')
			sys.stdout.flush()
			#print "Getting first random half"
			mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			data = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
			mooltipass_password.extend(data[DATA_INDEX:DATA_INDEX+32])
			#print "Getting second random half"
			mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			data2 = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
			mooltipass_password.extend(data2[DATA_INDEX:DATA_INDEX+30])
			#print "Getting random number for UID & request key"
			request_key_and_uid = array('B')
			mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			request_key_and_uid.extend(mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX:DATA_INDEX+24])

			# Check that we actually received data
			if data == None or data2 == None:
				success_status = False
				print "fail!!!"
				print "likely causes: defective crystal or power supply"

			# Send our bundle
			if success_status == True:
				sys.stdout.write('Step 2... ')
				sys.stdout.flush()
				
				# Upload bundle, password is not used in that context
				success_status = mooltipass_device.uploadBundle("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "updatefile.img", False)
				
				# For the mini version this procedure doesn't check the last return packet because in normal mode the device reboots
				if success_status == True:
					if mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX] == 0x01:
						success_status = True
					else:
						success_status = False
						print "last packet fail!!!"
						print "likely causes: problem with external flash"
				else:
					success_status = False
					print "fail!!!"
					print "likely causes: problem with external flash"

			# Inform the Mooltipass that the bundle is sent so it can start functional test
			if success_status == True:
				sys.stdout.write('Step 3... ')
				sys.stdout.flush()
				magic_key = array('B')
				magic_key.append(0)
				magic_key.append(187)
				mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
				if mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX] == 0x01:
					success_status = True
					print ""
				else:
					success_status = False
					print "fail!!!"
					print "likely causes: none"
			
			# Mooltipass Mini doesn't have LEDs anymore
			#if success_status == True:
			#	# Force tester to look at the LEDs
			#	raw_input("Press enter if LED1 is on: ")
			#	magic_key = array('B')
			#	magic_key.append(0)
			#	magic_key.append(149)
			#	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
			#	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
			#	raw_input("Press enter if LED2 is on: ")
			#	magic_key = array('B')
			#	magic_key.append(0)
			#	magic_key.append(150)
			#	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
			#	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
			#	raw_input("Press enter if LED3 is on: ")
			#	magic_key = array('B')
			#	magic_key.append(0)
			#	magic_key.append(151)
			#	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
			#	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
			#	raw_input("Press enter if LED4 is on: ")
			#	magic_key = array('B')
			#	magic_key.append(0)
			#	magic_key.append(152)
			#	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
			#	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]

			# Wait for the mooltipass to inform the script that the test was successfull
			if success_status == True:
				temp_bool2 = False
				sys.stdout.write('Please follow the instructions on the mooltipass screen...')
				sys.stdout.flush()
				while temp_bool2 != True:
					test_result = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
					if test_result == None:
						sys.stdout.write('.')
						sys.stdout.flush()
					else:
						if test_result[CMD_INDEX] == CMD_FUNCTIONAL_TEST_RES and test_result[DATA_INDEX] == 0:
							success_status = True
							print " ok!"
						else:
							success_status = False
							print " fail!!!"
							print "Please look at the screen to know the cause"
						temp_bool2 = True
					
			# Send set password packet
			if success_status == True:
				sys.stdout.write('Step 4... ')
				sys.stdout.flush()
				# TO REMOVE
				#request_key_and_uid = [0]*24
				mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_UID, 24, request_key_and_uid))
				if mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX] == 0x01:
					# Update Success status
					success_status = True
				else:
					success_status = False
					print "fail!!!"
					print "likely causes: mooltipass already setup"

			# Send set password packet
			if success_status == True:
				sys.stdout.write('Step 5...\r\n')
				sys.stdout.flush()
				# TO REMOVE
				#mooltipass_password = [0]*62
				mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_BOOTLOADER_PWD, 62, mooltipass_password))
				#print mooltipass_password
				if mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX] == 0x01:
					# Set password success, ask mooltipass id
					mp_id = None
					while mp_id == None:
						try :
							mp_id = int(raw_input("Enter Mooltipass ID: MPM-"))
						except ValueError :
							mp_id = None
							print "Wrong entered value, please try again"
					# Write in file: Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write
					aes_key1 = "".join(format(x, "02x") for x in mooltipass_password[:32])
					aes_key2 = "".join(format(x, "02x") for x in mooltipass_password[32:]) + "".join(format(x, "02x") for x in request_key_and_uid[22:])
					request_uid_key = "".join(format(x, "02x") for x in request_key_and_uid[0:16])
					uid = "".join(format(x, "02x") for x in request_key_and_uid[16:22])
					string_export = str(mp_id)+"|"+ aes_key1 +"|"+ aes_key2 +"|"+ request_uid_key +"|"+ uid +"\r\n"
					#print string_export
					pickle_write(seccure.encrypt(string_export, public_key, curve='secp521r1/nistp521'), time.strftime("export/%Y-%m-%d-%H-%M-%S-Mooltipass-")+str(mp_id)+".txt")					
					# Update Success status
					success_status = True
				else:
					success_status = False
					print "fail!!!"
					print "likely causes: mooltipass already setup"

			if success_status == True:
				# Let the user know it is done
				print "Setting up Mooltipass MPM-"+str(mp_id).zfill(4)+" DONE"
				# Increment Mooltipass ID
				mp_id = mp_id + 1
			else:
				print "|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!|"
				print "|---------------------------------------------------------|"
				print "|---------------------------------------------------------|"
				print "|Setting up Mooltipass MPM-"+"XXXX"+" FAILED                  |"
				print "|                                                         |"                     
				print "|           PLEASE PUT AWAY THIS MOOLTIPASS!!!!           |"                     
				print "|---------------------------------------------------------|"
				print "|---------------------------------------------------------|"
				print "|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!|"

			# Disconnect this device
			print "\r\nPlease disconnect this Mooltipass"

			# Wait for no answer to ping
			temp_bool2 = 0
			while temp_bool2 == 0:
				try :
					# Send ping packet
					mooltipass_device.pingMooltipass()
				except usb.core.USBError as e:
					#print e
					temp_bool2 = 1
				time.sleep(.5)

			# Connect another device
			print "Connect other Mooltipass"

			# Wait for findHidDevice to return something
			temp_bool2 = False;
			while temp_bool2 == False:
				temp_bool2 = mooltipass_device.connect(False)
				time.sleep(.5)

			# Delay
			time.sleep(1)

			# New Mooltipass detected
			print "New Mooltipass detected"
			print ""
	except KeyboardInterrupt:
		print "File written, everything ok"
示例#16
0
 def encrypt(message, key):
     return seccure.encrypt(message, key)
示例#17
0
def main():
	print "Mooltipass Mass Programming Tool"
	
	# Check for public key
	if not os.path.isfile("publickey.bin"):
		print "Couldn't find public key!"
		return
	
	# Check for firmware file presence
	if not os.path.isfile("Mooltipass.hex"):
		print "Couldn't find Mooltipass.hex"
		sys.exit(0)
	
	# Check for bootloader file presence
	if not os.path.isfile("bootloader_mini.hex"):
		print "Couldn't find bootloader_mini.hex"
		sys.exit(0)
	
	# Temp vars
	prog_socket_states = [PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE]
	programming_threads = [0, 0, 0, 0, 0, 0, 0, 0, 0]
	next_available_mooltipass_id = 1
	mooltipass_ids_pending = []
	mooltipass_ids_to_take = []
	global displayed_texts
	temp_counter = 0
	
	# Random bytes buffer
	random_bytes_buffer = []
	
	# HID device constructor
	mooltipass_device = mooltipass_hid_device()	
	
	# Connect to device
	if mooltipass_device.connect(True) == False:
		sys.exit(0)
	
	# Generate a blank firmware to see if we actually can generate it and then print the hash
	return_gen = generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", 12345, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0], "/tmp/test_flash.hex", "/tmp/test_eeprom.hex", True)
	os.remove("/tmp/test_flash.hex")
	os.remove("/tmp/test_eeprom.hex")
	
	# Check the success status
	if return_gen[0] == False:
		print "Couldn't generate a template flash hex!"
		sys.exit(0)
	
	# Check for random numbers file presence
	if os.path.isfile("rng.bin"):
		try:
			random_bytes_buffer = pickle_read("rng.bin")
		except EOFError:
			# This happens when the file is corrupted
			random_bytes_buffer = []
			os.remove("rng.bin")
		
	# Set to true to export the random bytes
	if False:		
		f = open('randombytes.bin', 'wb')
		random_bytes_buffer.tofile(f)
		f.flush()
		f.close()
	
	# Check for next mooltipass id file
	if os.path.isfile("mooltipass_id.bin"):
		next_available_mooltipass_id = pickle_read("mooltipass_id.bin")
		
	# Check for available mooltipass ids file
	if os.path.isfile("mooltipass_av_ids.bin"):
		mooltipass_ids_to_take = pickle_read("mooltipass_av_ids.bin")
		
	# Check for available mooltipass ids file
	if os.path.isfile("mooltipass_pending_ids.bin"):
		mooltipass_ids_pending = pickle_read("mooltipass_pending_ids.bin")
		if len(mooltipass_ids_pending) > 0:
			os.remove("mooltipass_pending_ids.bin")
			mooltipass_ids_to_take.extend(mooltipass_ids_pending)
			print "Adding previously pending ids:", mooltipass_ids_pending
	
	# Remove possible duplicates
	mooltipass_ids_to_take = list(set(mooltipass_ids_to_take))
	print "Mooltipass IDs to take:", mooltipass_ids_to_take
	pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
			
	# Read public key
	public_key = pickle_read("publickey.bin")
	
	# Display text on screen
	add_line_on_screen(mooltipass_device, "Python Script Started")
	add_line_on_screen(mooltipass_device, return_gen[1][0:20])
	add_line_on_screen(mooltipass_device, return_gen[1][20:])
		
	# Main loop
	while True:
		time.sleep(.3)
		temp_counter = temp_counter + 1
		
		# Check if a button is pressed
		mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_BUTTON_PRESSED, 0, None))
		received_data = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
		for i in range(0,9):
			if received_data[DATA_INDEX+i] != 0:				
				# Programming button was pressed on the bench
				print "Button", i, "pressed"
				prog_socket_states[i] = PROG_SOCKET_PENDING
		
		# Get number of available random bytes
		mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_GET_RNG_B_AVAIL, 0, None))
		nb_random_bytes_available = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX]
		
		# If more than 32 bytes, fetch them
		if nb_random_bytes_available >= 32:
			mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			random_bytes = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX:DATA_INDEX+32]
			random_bytes_buffer.extend(random_bytes)
			
		# Store random bytes buffer every now and then
		if temp_counter % 30 == 0:
			pickle_write(random_bytes_buffer, "rng.bin")
			print "Random bytes buffer saved:", len(random_bytes_buffer), "bytes available"
			#print random_bytes_buffer
			
		# If we have enough random bytes and a button was pressed, program the MCU
		for socket_id in range(0, 9):
			if prog_socket_states[socket_id] == PROG_SOCKET_PENDING and len(random_bytes_buffer) >= AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH:
				print "Starting programming for socket", socket_id
				
				# Generate new mooltipass ID
				if len(mooltipass_ids_to_take) > 0:
					mooltipass_id = mooltipass_ids_to_take[0]
					del(mooltipass_ids_to_take[0])
				else:
					# No ids to take, take the next available one
					mooltipass_id = next_available_mooltipass_id
					next_available_mooltipass_id = next_available_mooltipass_id + 1
					# Store the new id in file
					pickle_write(next_available_mooltipass_id, "mooltipass_id.bin")
				
				# Generate keys from the random bytes buffer
				aes_key1 = random_bytes_buffer[0:AES_KEY_LENGTH]
				aes_key2 = random_bytes_buffer[AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH]
				uid_key = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH]
				uid = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH]
				del(random_bytes_buffer[0:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH])
				
				# Write in file: Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write					
				aes_key1_text =  "".join(format(x, "02x") for x in aes_key1)
				aes_key2_text =  "".join(format(x, "02x") for x in aes_key2)
				uid_key_text = "".join(format(x, "02x") for x in uid_key)
				uid_text = "".join(format(x, "02x") for x in uid)					
				string_export = str(mooltipass_id)+"|"+ aes_key1_text +"|"+ aes_key2_text +"|"+ uid_key_text +"|"+ uid_text+"\r\n"
				#print string_export
				try:
					pickle_file_name = time.strftime("export/%Y-%m-%d-%H-%M-%S-Mooltipass-")+str(mooltipass_id)+".txt"
					pickle_write(seccure.encrypt(string_export, public_key, curve='secp521r1/nistp521'), pickle_file_name)	
				except NameError:
					pickle_file_name = "test"
				
				# Generate programming file					
				generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", mooltipass_id, aes_key1, aes_key2, uid_key, uid, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", False)
				
				# Change state to programming
				prog_socket_states[socket_id] = PROG_SOCKET_PROGRAMMING
				
				# Display info on display
				add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": programming id "+str(mooltipass_id))
				
				# Launch a programming thread
				mooltipass_ids_pending.append(mooltipass_id)
				pickle_write(mooltipass_ids_pending, "mooltipass_pending_ids.bin")
				programming_threads[socket_id] = FuncThread(start_programming, socket_id, mooltipass_id, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", pickle_file_name)
				programming_threads[socket_id].start()
					
					
		# Check for thread end
		for socket_id in range(0, 9):
			# Check if we're currently programming
			if prog_socket_states[socket_id] == PROG_SOCKET_PROGRAMMING:
				# Check if the thread ended
				if not programming_threads[socket_id].is_alive():
					print "Thread for socket", socket_id, "ended"
					
					# Fetch the return data
					return_data = programming_threads[socket_id].join()
					
					# Delete the temporary programming files
					os.remove(return_data[2])
					os.remove(return_data[3])
					
					# Check success state
					if return_data[0] :
						print "Programming for socket", socket_id, "succeeded (mooltipass id:", str(return_data[1]) + ")"
						
						# Save our mooltipass pool in case it was an id to take
						pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
						
						# Inform programming platform of success state
						mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_PROG_DONE, 1, [socket_id]))
						mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
						add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": "+return_data[4])
					else:
						print "Programming for socket", socket_id, "failed (mooltipass id:", str(return_data[1]) + ")"
						
						# Put the mooltipass id back in the pool
						mooltipass_ids_to_take.append(return_data[1])
						pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
						
						# Delete encrypted keys file
						os.remove(return_data[5])
						
						# Inform programming platform of success state
						mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_PROG_FAILURE, 1, [socket_id]))
						mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
						add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": "+return_data[4])
						
					# Remove id from pending ones					
					mooltipass_ids_pending.remove(return_data[1])
					pickle_write(mooltipass_ids_pending, "mooltipass_pending_ids.bin")
					
					# Reset prog state
					prog_socket_states[socket_id] = PROG_SOCKET_IDLE
示例#18
0
 def accepted(self):
     self.conn = sqlite3.connect("Data.db")
     self.c = self.conn.cursor()
     # key = convertpass(self.passStringAdd)
     # iv = Random.new().read(DES3.block_size)
     # cipher_encrypt = DES3.new(key, DES3.MODE_OFB, iv)
     # passwordpadded = convertToMUL8(self.Password.text())
     private_key = self.passStringAdd
     public_key = str(seccure.passphrase_to_pubkey(private_key.encode()))
     self.c.execute("INSERT INTO PASSES VALUES(?, ?, ?, ?)", [(self.id), (self.Company.text()), (self.Username.text()), (seccure.encrypt(self.Password.text().encode(), public_key.encode()))])
     print("A New Password FIELD ADDED.")
     self.conn.commit()
     self.accept()
示例#19
0
for x in range(7):
    packet.append(byteString[(x * N):((N * (x + 1)))])
    #print packet[x]
# Step 2
for y in range(7):
    #r.append(random.choice(enc_list))
    packet[y] = packet[y] + enc_list[y]
    #enc_list.remove(r[y])
    #packet[y] = packet[y] + r[y]
    #print packet[y]
private_key = '77'  #random.choice(string.digits)
#print private_key

public_key = str(seccure.passphrase_to_pubkey(private_key))
ciphertext = []
###Encryption phase
for z in range(7):
    t1 = time.time()
    ct = seccure.encrypt(packet[z][:-3], public_key)
    #print tt
    ciphertext.append(ct)
    t2 = time.time()
    conv = {'ciphertext': ct, 'cloudNo': packet[z][-3:]}
    s = json.dumps(conv, ensure_ascii=False)
    res = requests.post("http://127.0.0.1:5000/determine_escalation/",
                        data=ct + packet[z][-3:]).json()
    print res
    encTime = encTime + (t2 - t1)
    #print ciphertext[z]
print 'Encryption Time for the iteration', encTime
示例#20
0
 def encrypt(message, key):
     public_key = Private.publickey(key)  #HACK
     return seccure.encrypt(message, public_key)
示例#21
0
文件: eccpgp.py 项目: xevrem/csdm
 def raw_enc(self, data, pubkey=''):
     return seccure.encrypt(data, pubkey)
示例#22
0
文件: app.py 项目: Anuraj99/Cyber
 def on_click_send(self):
     self.conn = sqlite3.connect('BankDB.db')
     self.c = self.conn.cursor()
     self.date = datetime.datetime.now()
     self.c.execute('INSERT INTO SAMPE VALUES(?, ?, ?, ?, ?, ?, ?);', [(self.accID), (self.accID), (self.ReceiversID.text()), (seccure.encrypt(self.Amount.text().encode(), b'8W;>i^H0qi|J&$coR5MFpR*Vn')) , (str(self.date.time())), (str(self.date.date())), (hashTransaction(self.date.time(), self.accID))])
     print("Successfully Transfered")
     # self.fetchdata = self.c.execute('SELECT NETBALANCE FROM USERS where ACCOUNT_ID = ?', [(self.accID)])
     # for i in self.fetchdata:
     # self.intbalnow = i[0]
     # self.c.execute('UPDATE USERS SET NETBALANCE = ? WHERE ACCOUNT_ID = ?',[(self.intbalnow - int(self.Amount.text())), (self.accID)])
     self.conn.commit()
     self.close()
def main():
	print "Mooltipass Programming Tool"
	rng_buf_save_armed = True
	global main_program_running
	global serial_to_program
	global serial_entered
	global ic_programmed
	
	# Delete temp .hex file that might have been left there
	commands.getstatusoutput("rm /tmp/*.hex")
	
	# Check for public key
	if not os.path.isfile("publickey.bin"):
		print "Couldn't find public key!"
		return
	
	# Check for firmware file presence
	if not os.path.isfile("Mooltipass.hex"):
		print "Couldn't find Mooltipass.hex"
		sys.exit(0)
	
	# Check for bootloader file presence
	if not os.path.isfile("bootloader_mini.hex"):
		print "Couldn't find bootloader_mini.hex"
		sys.exit(0)
		
	# Random bytes buffer
	random_bytes_buffer = []
	
	# HID device constructor
	mooltipass_device = mooltipass_hid_device()	
	
	# Connect to device
	if mooltipass_device.connect(True) == False:
		print "No Mooltipass Connected!"
		sys.exit(0)
	
	# Generate a blank firmware to see if we actually can generate it and then print the hash
	return_gen = generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", 12345, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0], "/tmp/test_flash.hex", "/tmp/test_eeprom.hex", True)
	os.remove("/tmp/test_flash.hex")
	os.remove("/tmp/test_eeprom.hex")
	
	# Check the success status
	if return_gen[0] == False:
		print "Couldn't generate a template flash hex!"
		sys.exit(0)
	
	# Check for random numbers file presence
	if os.path.isfile("rng.bin"):
		try:
			random_bytes_buffer = pickle_read("rng.bin")
		except EOFError:
			# This happens when the file is corrupted
			random_bytes_buffer = []
			os.remove("rng.bin")
		
	# Set to true to export the random bytes
	if False:		
		f = open('randombytes.bin', 'wb')
		random_bytes_buffer.tofile(f)
		f.flush()
		f.close()
				
	# Read public key
	public_key = pickle_read("publickey.bin")
	
	# Start user input thread
	user_input_thread = threading.Thread(target=user_input_loop, args=())
	user_input_thread.start()
	
	# Main loop
	last_second = int(time.time())
	while main_program_running:
		time.sleep(.1)
	
		# Our generator generates 8 bytes per second
		ts = int(time.time())
		if (ts - last_second) > 4:
			# Fetch random bytes
			mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			random_bytes = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX:DATA_INDEX+32]
			random_bytes_buffer.extend(random_bytes)
			last_second = ts
			
		# Store buffer every minute
		if datetime.now().second == 0:
			if rng_buf_save_armed:
				#print "Random bytes buffer saved:", len(random_bytes_buffer), "bytes available"
				pickle_write(random_bytes_buffer, "rng.bin")
				rng_buf_save_armed = False
		else:
			rng_buf_save_armed = True
		
		# If a serial number was entered
		if serial_entered == True and len(random_bytes_buffer) >= AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH:
			# Store serial number to program
			mooltipass_id = serial_to_program
			
			# Generate keys from the random bytes buffer
			aes_key1 = random_bytes_buffer[0:AES_KEY_LENGTH]
			aes_key2 = random_bytes_buffer[AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH]
			uid_key = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH]
			uid = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH]
			del(random_bytes_buffer[0:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH])
			
			# Write in file: Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write					
			aes_key1_text =  "".join(format(x, "02x") for x in aes_key1)
			aes_key2_text =  "".join(format(x, "02x") for x in aes_key2)
			uid_key_text = "".join(format(x, "02x") for x in uid_key)
			uid_text = "".join(format(x, "02x") for x in uid)					
			string_export = str(mooltipass_id)+"|"+ aes_key1_text +"|"+ aes_key2_text +"|"+ uid_key_text +"|"+ uid_text+"\r\n"
			#print string_export
			pickle_file_name = time.strftime("export/%Y-%m-%d-%H-%M-%S-Mooltipass-")+str(mooltipass_id)+".txt"
			pickle_write(seccure.encrypt(string_export, public_key, curve='secp521r1/nistp521'), pickle_file_name)	
			
			# Generate programming file					
			generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", mooltipass_id, aes_key1, aes_key2, uid_key, uid, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", False)
			
			# Start programming 
			return_data = start_programming(mooltipass_id, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", pickle_file_name)
			
			# Check success state
			if return_data[0] :
				print "Programming succeeded (mooltipass id:", str(return_data[1]) + ")"
			else:
				print "Programming failed (mooltipass id:", str(return_data[1]) + ")"				
				# Delete encrypted keys file
				os.remove(return_data[5])
			
			# Free waiting thread
			serial_entered = False
			ic_programmed = True
示例#24
0
def mooltipassMiniInit(mooltipass_device):
    # Check for public key
    if not os.path.isfile("publickey.bin"):
        print "Couldn't find public key!"
        return

    # Check for export folder
    if not os.path.isdir("export"):
        print "Couldn't find export folder"
        return

    # Check for update bundle
    if not os.path.isfile("updatefile.img"):
        print "Couldn't find udpate file!"
        return

    # Read public key
    public_key = pickle_read("publickey.bin")

    # Loop
    try:
        temp_bool = 0
        while temp_bool == 0:
            # Operation success state
            success_status = True

            # Empty set password packet
            mooltipass_password = array('B')

            # We need 62 random bytes to set them as a password for the Mooltipass
            sys.stdout.write('Step 1... ')
            sys.stdout.flush()
            #print "Getting first random half"
            mooltipass_device.getInternalDevice().sendHidPacket(
                mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
            data = mooltipass_device.getInternalDevice(
            ).receiveHidPacketWithTimeout()
            mooltipass_password.extend(data[DATA_INDEX:DATA_INDEX + 32])
            #print "Getting second random half"
            mooltipass_device.getInternalDevice().sendHidPacket(
                mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
            data2 = mooltipass_device.getInternalDevice(
            ).receiveHidPacketWithTimeout()
            mooltipass_password.extend(data2[DATA_INDEX:DATA_INDEX + 30])
            #print "Getting random number for UID & request key"
            request_key_and_uid = array('B')
            mooltipass_device.getInternalDevice().sendHidPacket(
                mpmInitGetPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
            request_key_and_uid.extend(mooltipass_device.getInternalDevice(
            ).receiveHidPacketWithTimeout()[DATA_INDEX:DATA_INDEX + 24])

            # Check that we actually received data
            if data == None or data2 == None:
                success_status = False
                print "fail!!!"
                print "likely causes: defective crystal or power supply"

            # Send our bundle
            if success_status == True:
                sys.stdout.write('Step 2... ')
                sys.stdout.flush()

                # Upload bundle, password is not used in that context
                success_status = mooltipass_device.uploadBundle(
                    "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
                    "updatefile.img", False)

                # For the mini version this procedure doesn't check the last return packet because in normal mode the device reboots
                if success_status == True:
                    if mooltipass_device.getInternalDevice(
                    ).receiveHidPacketWithTimeout()[DATA_INDEX] == 0x01:
                        success_status = True
                    else:
                        success_status = False
                        print "last packet fail!!!"
                        print "likely causes: problem with external flash"
                else:
                    success_status = False
                    print "fail!!!"
                    print "likely causes: problem with external flash"

            # Inform the Mooltipass that the bundle is sent so it can start functional test
            if success_status == True:
                sys.stdout.write('Step 3... ')
                sys.stdout.flush()
                magic_key = array('B')
                magic_key.append(0)
                magic_key.append(187)
                mooltipass_device.getInternalDevice().sendHidPacket(
                    mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2,
                                               magic_key))
                if mooltipass_device.getInternalDevice().receiveHidPacket(
                )[DATA_INDEX] == 0x01:
                    success_status = True
                    print ""
                else:
                    success_status = False
                    print "fail!!!"
                    print "likely causes: none"

            # Mooltipass Mini doesn't have LEDs anymore
            #if success_status == True:
            #	# Force tester to look at the LEDs
            #	raw_input("Press enter if LED1 is on: ")
            #	magic_key = array('B')
            #	magic_key.append(0)
            #	magic_key.append(149)
            #	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
            #	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
            #	raw_input("Press enter if LED2 is on: ")
            #	magic_key = array('B')
            #	magic_key.append(0)
            #	magic_key.append(150)
            #	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
            #	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
            #	raw_input("Press enter if LED3 is on: ")
            #	magic_key = array('B')
            #	magic_key.append(0)
            #	magic_key.append(151)
            #	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
            #	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]
            #	raw_input("Press enter if LED4 is on: ")
            #	magic_key = array('B')
            #	magic_key.append(0)
            #	magic_key.append(152)
            #	mooltipass_device.getInternalDevice().sendHidPacket(mpmInitGetPacketForCommand(CMD_SET_MOOLTIPASS_PARM, 2, magic_key))
            #	mooltipass_device.getInternalDevice().receiveHidPacket()[DATA_INDEX]

            # Wait for the mooltipass to inform the script that the test was successfull
            if success_status == True:
                temp_bool2 = False
                sys.stdout.write(
                    'Please follow the instructions on the mooltipass screen...'
                )
                sys.stdout.flush()
                while temp_bool2 != True:
                    test_result = mooltipass_device.getInternalDevice(
                    ).receiveHidPacketWithTimeout()
                    if test_result == None:
                        sys.stdout.write('.')
                        sys.stdout.flush()
                    else:
                        if test_result[
                                CMD_INDEX] == CMD_FUNCTIONAL_TEST_RES and test_result[
                                    DATA_INDEX] == 0:
                            success_status = True
                            print " ok!"
                        else:
                            success_status = False
                            print " fail!!!"
                            print "Please look at the screen to know the cause"
                        temp_bool2 = True

            # Send set password packet
            if success_status == True:
                sys.stdout.write('Step 4... ')
                sys.stdout.flush()
                # TO REMOVE
                #request_key_and_uid = [0]*24
                mooltipass_device.getInternalDevice().sendHidPacket(
                    mpmInitGetPacketForCommand(CMD_SET_UID, 24,
                                               request_key_and_uid))
                if mooltipass_device.getInternalDevice().receiveHidPacket(
                )[DATA_INDEX] == 0x01:
                    # Update Success status
                    success_status = True
                else:
                    success_status = False
                    print "fail!!!"
                    print "likely causes: mooltipass already setup"

            # Send set password packet
            if success_status == True:
                sys.stdout.write('Step 5...\r\n')
                sys.stdout.flush()
                # TO REMOVE
                #mooltipass_password = [0]*62
                mooltipass_device.getInternalDevice().sendHidPacket(
                    mpmInitGetPacketForCommand(CMD_SET_BOOTLOADER_PWD, 62,
                                               mooltipass_password))
                #print mooltipass_password
                if mooltipass_device.getInternalDevice().receiveHidPacket(
                )[DATA_INDEX] == 0x01:
                    # Set password success, ask mooltipass id
                    mp_id = None
                    while mp_id == None:
                        try:
                            mp_id = int(raw_input("Enter Mooltipass ID: MPM-"))
                        except ValueError:
                            mp_id = None
                            print "Wrong entered value, please try again"
                    # Write in file: Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write
                    aes_key1 = "".join(
                        format(x, "02x") for x in mooltipass_password[:32])
                    aes_key2 = "".join(
                        format(x, "02x")
                        for x in mooltipass_password[32:]) + "".join(
                            format(x, "02x") for x in request_key_and_uid[22:])
                    request_uid_key = "".join(
                        format(x, "02x") for x in request_key_and_uid[0:16])
                    uid = "".join(
                        format(x, "02x") for x in request_key_and_uid[16:22])
                    string_export = str(
                        mp_id
                    ) + "|" + aes_key1 + "|" + aes_key2 + "|" + request_uid_key + "|" + uid + "\r\n"
                    #print string_export
                    pickle_write(
                        seccure.encrypt(string_export,
                                        public_key,
                                        curve='secp521r1/nistp521'),
                        time.strftime("export/%Y-%m-%d-%H-%M-%S-Mooltipass-") +
                        str(mp_id) + ".txt")
                    # Update Success status
                    success_status = True
                else:
                    success_status = False
                    print "fail!!!"
                    print "likely causes: mooltipass already setup"

            if success_status == True:
                # Let the user know it is done
                print "Setting up Mooltipass MPM-" + str(mp_id).zfill(
                    4) + " DONE"
                # Increment Mooltipass ID
                mp_id = mp_id + 1
            else:
                print "|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!|"
                print "|---------------------------------------------------------|"
                print "|---------------------------------------------------------|"
                print "|Setting up Mooltipass MPM-" + "XXXX" + " FAILED                  |"
                print "|                                                         |"
                print "|           PLEASE PUT AWAY THIS MOOLTIPASS!!!!           |"
                print "|---------------------------------------------------------|"
                print "|---------------------------------------------------------|"
                print "|!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!|"

            # Disconnect this device
            print "\r\nPlease disconnect this Mooltipass"

            # Wait for no answer to ping
            temp_bool2 = 0
            while temp_bool2 == 0:
                try:
                    # Send ping packet
                    mooltipass_device.pingMooltipass()
                except usb.core.USBError as e:
                    #print e
                    temp_bool2 = 1
                time.sleep(.5)

            # Connect another device
            print "Connect other Mooltipass"

            # Wait for findHidDevice to return something
            temp_bool2 = False
            while temp_bool2 == False:
                temp_bool2 = mooltipass_device.connect(False)
                time.sleep(.5)

            # Delay
            time.sleep(1)

            # New Mooltipass detected
            print "New Mooltipass detected"
            print ""
    except KeyboardInterrupt:
        print "File written, everything ok"
def doEccEncrypt(rsa_value, publicKey):
    return seccure.encrypt(rsa_value, publicKey)
示例#26
0
def seccure_get_encrypted_content(plain_text , public_key):
    cipher_text = seccure.encrypt(plain_text, public_key)
    return base64.encodestring(cipher_text)
#
#
# using elliptic curve cryptography to encrypt messages. 
#
# use with seccure: https://github.com/MeeSeongIm/py-seccure
#
#



import seccure

str(seccure.passphrase_to_pubkey(b'my private key'))  # devive the public key 

ciphertext = seccure.encrypt(b'This is a secret message.\n', b'8W;>i^H0qi|J&$coR5MFpR*Vn')

print(ciphertext)

seccure.decrypt(ciphertext, b'my private key')

seccure.sign(b'This will be a signed message.\n', b'my private key') 

seccure.verify(b'This will be a signed message.\n', b'', b'8W;>i^H0qi|J&$coR5MFpR*Vn')  # to verify the signature

示例#28
0
def main():
	print "Mooltipass Mass Programming Tool"
	
	# Check for public key
	if not os.path.isfile("publickey.bin"):
		print "Couldn't find public key!"
		return
	
	# Check for firmware file presence
	if not os.path.isfile("Mooltipass.hex"):
		print "Couldn't find Mooltipass.hex"
		sys.exit(0)
	
	# Check for bootloader file presence
	if not os.path.isfile("bootloader_mini.hex"):
		print "Couldn't find bootloader_mini.hex"
		sys.exit(0)
	
	# Temp vars
	prog_socket_states = [PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE, PROG_SOCKET_IDLE]
	programming_threads = [0, 0, 0, 0, 0, 0, 0, 0, 0]
	next_available_mooltipass_id = 1
	mooltipass_ids_pending = []
	mooltipass_ids_to_take = []
	global displayed_texts
	temp_counter = 0
	
	# Random bytes buffer
	random_bytes_buffer = []
	
	# HID device constructor
	mooltipass_device = mooltipass_hid_device()	
	
	# Connect to device
	if mooltipass_device.connect(True) == False:
		sys.exit(0)
	
	# Generate a blank firmware to see if we actually can generate it and then print the hash
	return_gen = generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", 12345, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0], "/tmp/test_flash.hex", "/tmp/test_eeprom.hex", True)
	os.remove("/tmp/test_flash.hex")
	os.remove("/tmp/test_eeprom.hex")
	
	# Check the success status
	if return_gen[0] == False:
		print "Couldn't generate a template flash hex!"
		sys.exit(0)
	
	# Check for random numbers file presence
	if os.path.isfile("rng.bin"):
		try:
			random_bytes_buffer = pickle_read("rng.bin")
		except EOFError:
			# This happens when the file is corrupted
			random_bytes_buffer = []
			os.remove("rng.bin")
		
	# Set to true to export the random bytes
	if False:		
		f = open('randombytes.bin', 'wb')
		random_bytes_buffer.tofile(f)
		f.flush()
		f.close()
	
	# Check for next mooltipass id file
	if os.path.isfile("mooltipass_id.bin"):
		next_available_mooltipass_id = pickle_read("mooltipass_id.bin")
		
	# Check for available mooltipass ids file
	if os.path.isfile("mooltipass_av_ids.bin"):
		mooltipass_ids_to_take = pickle_read("mooltipass_av_ids.bin")
		
	# Check for available mooltipass ids file
	if os.path.isfile("mooltipass_pending_ids.bin"):
		mooltipass_ids_pending = pickle_read("mooltipass_pending_ids.bin")
		if len(mooltipass_ids_pending) > 0:
			os.remove("mooltipass_pending_ids.bin")
			mooltipass_ids_to_take.extend(mooltipass_ids_pending)
			print "Adding previously pending ids:", mooltipass_ids_pending
	
	# Remove possible duplicates
	mooltipass_ids_to_take = list(set(mooltipass_ids_to_take))
	print "Mooltipass IDs to take:", mooltipass_ids_to_take
	pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
			
	# Read public key
	public_key = pickle_read("publickey.bin")
	
	# Display text on screen
	add_line_on_screen(mooltipass_device, "Python Script Started")
	add_line_on_screen(mooltipass_device, return_gen[1][0:20])
	add_line_on_screen(mooltipass_device, return_gen[1][20:])
		
	# Main loop
	while True:
		time.sleep(.3)
		temp_counter = temp_counter + 1
		
		# Check if a button is pressed
		mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_BUTTON_PRESSED, 0, None))
		received_data = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
		for i in range(0,9):
			if received_data[DATA_INDEX+i] != 0:				
				# Programming button was pressed on the bench
				print "Button", i, "pressed"
				prog_socket_states[i] = PROG_SOCKET_PENDING
		
		# Get number of available random bytes
		mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_GET_RNG_B_AVAIL, 0, None))
		nb_random_bytes_available = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX]
		
		# If more than 32 bytes, fetch them
		if nb_random_bytes_available >= 32:
			mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_GET_RANDOM_NUMBER, 0, None))
			random_bytes = mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()[DATA_INDEX:DATA_INDEX+32]
			random_bytes_buffer.extend(random_bytes)
			
		# Store random bytes buffer every now and then
		if temp_counter % 30 == 0:
			pickle_write(random_bytes_buffer, "rng.bin")
			print "Random bytes buffer saved:", len(random_bytes_buffer), "bytes available"
			#print random_bytes_buffer
			
		# If we have enough random bytes and a button was pressed, program the MCU
		for socket_id in range(0, 9):
			if prog_socket_states[socket_id] == PROG_SOCKET_PENDING and len(random_bytes_buffer) >= AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH:
				print "Starting programming for socket", socket_id
				
				# Generate new mooltipass ID
				if len(mooltipass_ids_to_take) > 0:
					mooltipass_id = mooltipass_ids_to_take[0]
					del(mooltipass_ids_to_take[0])
				else:
					# No ids to take, take the next available one
					mooltipass_id = next_available_mooltipass_id
					next_available_mooltipass_id = next_available_mooltipass_id + 1
					# Store the new id in file
					pickle_write(next_available_mooltipass_id, "mooltipass_id.bin")
				
				# Generate keys from the random bytes buffer
				aes_key1 = random_bytes_buffer[0:AES_KEY_LENGTH]
				aes_key2 = random_bytes_buffer[AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH]
				uid_key = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH]
				uid = random_bytes_buffer[AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH]
				del(random_bytes_buffer[0:AES_KEY_LENGTH+AES_KEY_LENGTH+UID_REQUEST_KEY_LENGTH+UID_KEY_LENGTH])
				
				# Write in file: Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write					
				aes_key1_text =  "".join(format(x, "02x") for x in aes_key1)
				aes_key2_text =  "".join(format(x, "02x") for x in aes_key2)
				uid_key_text = "".join(format(x, "02x") for x in uid_key)
				uid_text = "".join(format(x, "02x") for x in uid)					
				string_export = str(mooltipass_id)+"|"+ aes_key1_text +"|"+ aes_key2_text +"|"+ uid_key_text +"|"+ uid_text+"\r\n"
				#print string_export
				try:
					pickle_file_name = time.strftime("export/%Y-%m-%d-%H-%M-%S-Mooltipass-")+str(mooltipass_id)+".txt"
					pickle_write(seccure.encrypt(string_export, public_key, curve='secp521r1/nistp521'), pickle_file_name)	
				except NameError:
					pickle_file_name = "test"
				
				# Generate programming file					
				generateFlashAndEepromHex("Mooltipass.hex", "bootloader_mini.hex", mooltipass_id, aes_key1, aes_key2, uid_key, uid, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", False)
				
				# Change state to programming
				prog_socket_states[socket_id] = PROG_SOCKET_PROGRAMMING
				
				# Display info on display
				add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": programming id "+str(mooltipass_id))
				
				# Launch a programming thread
				mooltipass_ids_pending.append(mooltipass_id)
				pickle_write(mooltipass_ids_pending, "mooltipass_pending_ids.bin")
				programming_threads[socket_id] = FuncThread(start_programming, socket_id, mooltipass_id, "/tmp/flash_"+str(mooltipass_id)+".hex", "/tmp/eeprom_"+str(mooltipass_id)+".hex", pickle_file_name)
				programming_threads[socket_id].start()
					
					
		# Check for thread end
		for socket_id in range(0, 9):
			# Check if we're currently programming
			if prog_socket_states[socket_id] == PROG_SOCKET_PROGRAMMING:
				# Check if the thread ended
				if not programming_threads[socket_id].is_alive():
					print "Thread for socket", socket_id, "ended"
					
					# Fetch the return data
					return_data = programming_threads[socket_id].join()
					
					# Delete the temporary programming files
					os.remove(return_data[2])
					os.remove(return_data[3])
					
					# Check success state
					if return_data[0] :
						print "Programming for socket", socket_id, "succeeded (mooltipass id:", str(return_data[1]) + ")"
						
						# Save our mooltipass pool in case it was an id to take
						pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
						
						# Inform programming platform of success state
						mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_PROG_DONE, 1, [socket_id]))
						mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
						add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": "+return_data[4])
					else:
						print "Programming for socket", socket_id, "failed (mooltipass id:", str(return_data[1]) + ")"
						
						# Put the mooltipass id back in the pool
						mooltipass_ids_to_take.append(return_data[1])
						pickle_write(mooltipass_ids_to_take, "mooltipass_av_ids.bin")
						
						# Delete encrypted keys file
						os.remove(return_data[5])
						
						# Inform programming platform of success state
						mooltipass_device.getInternalDevice().sendHidPacket(mooltipass_device.getPacketForCommand(CMD_PROG_FAILURE, 1, [socket_id]))
						mooltipass_device.getInternalDevice().receiveHidPacketWithTimeout()
						add_line_on_screen(mooltipass_device, "#"+str(socket_id)+": "+return_data[4])
						
					# Remove id from pending ones					
					mooltipass_ids_pending.remove(return_data[1])
					pickle_write(mooltipass_ids_pending, "mooltipass_pending_ids.bin")
					
					# Reset prog state
					prog_socket_states[socket_id] = PROG_SOCKET_IDLE
示例#29
0
 def raw_enc(self, data, pubkey=''):
     return seccure.encrypt(data, pubkey)