biometry_hash.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. #usr/share/doc/python-fingerprint
  2. #!/usr/bin/env python
  3. # -*- coding: utf-8 -*-
  4. import hashlib
  5. import os
  6. import tempfile
  7. import time
  8. from pyfingerprint.pyfingerprint import PyFingerprint
  9. import os, random
  10. from Crypto.Cipher import AES
  11. from Crypto.Hash import SHA256
  12. def enroll():
  13. ## Enrolls new finger
  14. ##
  15. ## Tries to initialize the sensor
  16. try:
  17. f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
  18. if ( f.verifyPassword() == False ):
  19. raise ValueError('The given fingerprint sensor password is wrong!')
  20. except Exception as e:
  21. print('The fingerprint sensor could not be initialized!')
  22. print('Exception message: ' + str(e))
  23. exit(1)
  24. ## Gets some sensor information
  25. print('Currently stored templates: ' + str(f.getTemplateCount()))
  26. ## Tries to enroll new finger
  27. try:
  28. print('Waiting for finger...')
  29. ## Wait that finger is read
  30. while ( f.readImage() == False ):
  31. pass
  32. ## Converts read image to characteristics and stores it in charbuffer 1
  33. f.convertImage(0x01)
  34. ## Checks if finger is already enrolled
  35. result = f.searchTemplate()
  36. positionNumber = result[0]
  37. ## Gets new position number (the counting starts at 0, so we do not need to increment)
  38. #positionNumber = f.getTemplateCount()
  39. if ( positionNumber >= 0 ):
  40. f.loadTemplate(positionNumber, 0x01)
  41. characterics = str(f.downloadCharacteristics(0x01))
  42. passhashes = hashlib.sha256(characterics).hexdigest()
  43. passhash = passhashes[0:32]
  44. print('Template already exists at position #' + str(positionNumber))
  45. return passhash
  46. print('Remove finger...')
  47. time.sleep(2)
  48. print('Waiting for same finger again...')
  49. ## Wait that finger is read again
  50. while ( f.readImage() == False ):
  51. pass
  52. ## Converts read image to characteristics and stores it in charbuffer 2
  53. f.convertImage(0x02)
  54. ## Compares the charbuffers and creates a template
  55. f.createTemplate()
  56. ## Gets new position number (the counting starts at 0, so we do not need to increment)
  57. positionNumber = f.getTemplateCount()
  58. ## Saves template at new position number
  59. if ( f.storeTemplate(positionNumber) == True ):
  60. print('Finger enrolled successfully!')
  61. print('New template position #' + str(positionNumber))
  62. ## Hashes characteristics of template
  63. characterics = str(f.downloadCharacteristics(0x01))
  64. passhashes = hashlib.sha256(characterics).hexdigest()
  65. passhash = passhashes[0:32]
  66. ## Hashes characteristics of template
  67. print('SHA-2 hash of template: ' + passhash)
  68. return passhash
  69. except Exception as e:
  70. print('Operation failed!')
  71. print('Exception message: ' + str(e))
  72. exit(1)
  73. #print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())
  74. def index():
  75. ## Shows the template index table
  76. ##
  77. ## Tries to initialize the sensor
  78. try:
  79. f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
  80. if ( f.verifyPassword() == False ):
  81. raise ValueError('The given fingerprint sensor password is wrong!')
  82. except Exception as e:
  83. print('The fingerprint sensor could not be initialized!')
  84. print('Exception message: ' + str(e))
  85. exit(1)
  86. ## Gets some sensor information
  87. print('Currently stored templates: ' + str(f.getTemplateCount()))
  88. ## Tries to show a template index table page
  89. try:
  90. page = raw_input('Please enter the index page (0, 1, 2, 3) you want to see: ')
  91. page = int(page)
  92. tableIndex = f.getTemplateIndex(page)
  93. for i in range(0, len(tableIndex)):
  94. print('Template at position #' + str(i) + ' is used: ' + str(tableIndex[i]))
  95. except Exception as e:
  96. print('Operation failed!')
  97. print('Exception message: ' + str(e))
  98. exit(1)
  99. def fp_download():
  100. ## Reads image and download it
  101. ## Tries to initialize the sensor
  102. try:
  103. f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
  104. if ( f.verifyPassword() == False ):
  105. raise ValueError('The given fingerprint sensor password is wrong!')
  106. except Exception as e:
  107. print('The fingerprint sensor could not be initialized!')
  108. print('Exception message: ' + str(e))
  109. exit(1)
  110. ## Gets some sensor information
  111. print('Currently stored templates: ' + str(f.getTemplateCount()))
  112. ## Tries to read image and download it
  113. try:
  114. print('Waiting for finger...')
  115. ## Wait that finger is read
  116. while ( f.readImage() == False ):
  117. pass
  118. print('Downloading image (this take a while)...')
  119. imageDestination = tempfile.gettempdir() + '/fingerprint.bmp'
  120. f.downloadImage(imageDestination)
  121. print('The image was saved to "' + imageDestination + '".')
  122. except Exception as e:
  123. print('Operation failed!')
  124. print('Exception message: ' + str(e))
  125. exit(1)
  126. def delete():
  127. from pyfingerprint.pyfingerprint import PyFingerprint
  128. ## Deletes a finger from sensor
  129. ##
  130. ## Tries to initialize the sensor
  131. try:
  132. f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
  133. if ( f.verifyPassword() == False ):
  134. raise ValueError('The given fingerprint sensor password is wrong!')
  135. except Exception as e:
  136. print('The fingerprint sensor could not be initialized!')
  137. print('Exception message: ' + str(e))
  138. exit(1)
  139. ## Gets some sensor information
  140. print('Currently stored templates: ' + str(f.getTemplateCount()))
  141. ## Tries to delete the template of the finger
  142. try:
  143. positionNumber = raw_input('Please enter the template position you want to delete: ')
  144. positionNumber = int(positionNumber)
  145. if ( f.deleteTemplate(positionNumber) == True ):
  146. print('Template deleted!')
  147. except Exception as e:
  148. print('Operation failed!')
  149. print('Exception message: ' + str(e))
  150. exit(1)
  151. def fp_search():
  152. """
  153. PyFingerprint
  154. Copyright (C) 2015 Bastian Raschke <bastian.raschke@posteo.de>
  155. All rights reserved.
  156. @author: Bastian Raschke <bastian.raschke@posteo.de>
  157. """
  158. ## Search for a finger
  159. ##
  160. ## Tries to initialize the sensor
  161. try:
  162. f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
  163. if ( f.verifyPassword() == False ):
  164. raise ValueError('The given fingerprint sensor password is wrong!')
  165. except Exception as e:
  166. print('The fingerprint sensor could not be initialized!')
  167. print('Exception message: ' + str(e))
  168. exit(1)
  169. ## Gets some sensor information
  170. print('Currently stored templates: ' + str(f.getTemplateCount()))
  171. ## Tries to search the finger and calculate hash
  172. try:
  173. print('Waiting for finger...')
  174. ## Wait that finger is read
  175. while ( f.readImage() == False ):
  176. pass
  177. ## Converts read image to characteristics and stores it in charbuffer 1
  178. f.convertImage(0x01)
  179. ## Searchs template
  180. result = f.searchTemplate()
  181. positionNumber = result[0]
  182. accuracyScore = result[1]
  183. if ( positionNumber == -1 ):
  184. print('No match found!')
  185. exit(0)
  186. else:
  187. print('Found template at position #' + str(positionNumber))
  188. print('The accuracy score is: ' + str(accuracyScore))
  189. ## OPTIONAL stuff
  190. ##
  191. ## Loads the found template to charbuffer 1
  192. f.loadTemplate(positionNumber, 0x01)
  193. ## Downloads the characteristics of template loaded in charbuffer 1
  194. characterics = str(f.downloadCharacteristics(0x01))
  195. ## Hashes characteristics of template
  196. print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())
  197. except Exception as e:
  198. print('Operation failed!')
  199. print('Exception message: ' + str(e))
  200. exit(1)
  201. def get_decision():#initial message at the start at the program
  202. decision = ""
  203. decision = raw_input()
  204. return decision
  205. def AES_full(passhash):
  206. EncDec = passhash
  207. choice1 = ""
  208. while choice1 is not "1" and choice1 is not "2" :
  209. choice1 = raw_input()
  210. if choice1 == "1":
  211. <<<<<<< HEAD
  212. print ("\nEncryption/Decryption")
  213. =======
  214. print ("\nHash/Decryption")
  215. >>>>>>> c7f56cb0b54d04e8c4eb2ced24023454d0721d31
  216. AESmenu(EncDec)
  217. if choice1 == "2":
  218. print ("\nMain Menu")
  219. main()
  220. def encrypt(key, filename):
  221. chunksize = 64*1024
  222. #print filename
  223. #print "4th time: ", key
  224. outputFile = "(encrypted)"+filename
  225. filesize = str(os.path.getsize(filename)).zfill(16)
  226. IV = ''
  227. for i in range(16):
  228. IV += chr(random.randint(0, 0xFF))
  229. encryptor = AES.new(key, AES.MODE_CBC, IV)
  230. with open(filename, 'rb') as infile:
  231. with open(outputFile, 'wb') as outfile:
  232. outfile.write(filesize)
  233. outfile.write(IV)
  234. while True:
  235. chunk = infile.read(chunksize)
  236. if len(chunk) == 0:
  237. break
  238. elif len(chunk) % 16 != 0:
  239. chunk += ' ' * (16 - (len(chunk) % 16))
  240. outfile.write(encryptor.encrypt(chunk))
  241. def decrypt(key, filename):
  242. chunksize = 64*1024
  243. outputFile = filename[11:]
  244. with open(filename, 'rb') as infile:
  245. filesize = long(infile.read(16))
  246. IV = infile.read(16)
  247. decryptor = AES.new(key, AES.MODE_CBC, IV)
  248. with open(outputFile, 'wb') as outfile:
  249. while True:
  250. chunk = infile.read(chunksize)
  251. if len(chunk) == 0:
  252. break
  253. outfile.write(decryptor.decrypt(chunk))
  254. outfile.truncate(filesize)
  255. """def getKey(password):
  256. hasher = SHA256.new(password)
  257. return hasher.digest()"""
  258. def file_check(filename):
  259. try:
  260. open(filename, 'r')
  261. return 1
  262. except:
  263. print ("This file doesnt exist")
  264. return 0
  265. def AESmenu(EncDec):
  266. choice = raw_input("Would you like to (E)ncrypt or (D)ecrypt?: ")
  267. f_in = raw_input("Insert the filename with extension: ")
  268. fileblob = file_check(f_in)
  269. while fileblob == 0:
  270. f_in = raw_input("insert the filename with extensions")
  271. fileblob = file_check(f_in)
  272. print( f_in )
  273. #print "3rd time: ", EncDec
  274. if choice == 'E':
  275. #filename = raw_input("File to encrypt: ")
  276. encrypt(EncDec, f_in)
  277. print ("Done.")
  278. elif choice == 'D':
  279. decrypt(EncDec, f_in)
  280. print( "Done.")
  281. else:
  282. print ("No Option selected, closing...")
  283. def main ():
  284. decision = get_decision()
  285. while decision is not "quit" and decision is not "2":
  286. print( "Please choose form the following.")
  287. choice = ""
  288. while choice is not "1" and choice is not "2" and choice is not "3" and choice is not "4" and choice is not "5":
  289. choice = raw_input()
  290. if choice == "1":
  291. print ("\nBiometric Enrollment")
  292. hashcode = enroll()
  293. print (hashcode)
  294. AES_full(hashcode)
  295. if choice == "2":
  296. print( "\nShow Biometric Index")
  297. index()
  298. if choice == "3":
  299. print ("\nSearch Index Using Biometrics")
  300. fp_search()
  301. if choice == "4":
  302. print ("\nDownload Biometric Image")
  303. fp_download()
  304. if choice == "5":
  305. print ("\nDelete Biometric Image")
  306. delete()
  307. '''
  308. print "The message inserted was: %s " % message
  309. ciphertext = encrypt(message , m)
  310. print "Lets apply RC4 with salt for security"
  311. cipherplay = ''.join(ciphertext)
  312. RC = encryptRC(cipherplay, matrix_key)
  313. print "Message with RC4 with salt"
  314. print RC
  315. print "Do you want to save the message to a file? (Y/N)"
  316. answer = raw_input()
  317. while answer is not "Y" and answer is not "y" and answer is not "N" and answer is not "n":
  318. print "Do you want to save the message to a file? (Y/N)"
  319. answer = raw_input()
  320. if answer == "Y" or answer == "y":
  321. fout = open('Encrypted.txt', 'w')
  322. fout.write(RC)
  323. fout.close()
  324. print "Message save to file Encrypted.txt on the folder of this program\n"
  325. print "Press Enter to continue:"
  326. raw_input()
  327. else:
  328. print "Press enter to continue"
  329. raw_input()
  330. decision = get_decision()
  331. elif choice == "2":
  332. ch_enc = ""
  333. print "\nMessage Decryption:"
  334. print "1 - Open a custom file"
  335. print "2 - Copy the encrypted message"
  336. ch_enc = raw_input()
  337. if ch_enc == "1":
  338. print "Insert the filename with extension"
  339. f_in = raw_input()
  340. file = file_check(f_in)
  341. while file == 0:
  342. print "Insert the filename with the extension"
  343. f_in = raw_input()
  344. file = file_check(f_in)
  345. fin = open(f_in, 'U')
  346. RCmessage = fin.read()
  347. fin.close()
  348. elif ch_enc == "2":
  349. print "Insert the encripted message:"
  350. RCmessage = raw_input()
  351. print "You inserted ", RCmessage
  352. ms = decryptRC(RCmessage, matrix_key)
  353. message = get_message(ms)
  354. plaintext = decrypt(message, m)
  355. print "\nPress enter to continue"
  356. raw_input()
  357. decision = get_decision()
  358. else:
  359. print "Wrong Choice"
  360. print "Thanks for using the software \nGood Bye"
  361. raw_input()
  362. '''
  363. if __name__ == "__main__":
  364. main()