biometry_hash.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. print ("\nHash/Decryption")
  212. AESmenu(EncDec)
  213. if choice1 == "2":
  214. print ("\nMain Menu")
  215. main()
  216. def encrypt(key, filename):
  217. chunksize = 64*1024
  218. #print filename
  219. #print "4th time: ", key
  220. outputFile = "(encrypted)"+filename
  221. filesize = str(os.path.getsize(filename)).zfill(16)
  222. IV = ''
  223. for i in range(16):
  224. IV += chr(random.randint(0, 0xFF))
  225. encryptor = AES.new(key, AES.MODE_CBC, IV)
  226. with open(filename, 'rb') as infile:
  227. with open(outputFile, 'wb') as outfile:
  228. outfile.write(filesize)
  229. outfile.write(IV)
  230. while True:
  231. chunk = infile.read(chunksize)
  232. if len(chunk) == 0:
  233. break
  234. elif len(chunk) % 16 != 0:
  235. chunk += ' ' * (16 - (len(chunk) % 16))
  236. outfile.write(encryptor.encrypt(chunk))
  237. def decrypt(key, filename):
  238. chunksize = 64*1024
  239. outputFile = filename[11:]
  240. with open(filename, 'rb') as infile:
  241. filesize = long(infile.read(16))
  242. IV = infile.read(16)
  243. decryptor = AES.new(key, AES.MODE_CBC, IV)
  244. with open(outputFile, 'wb') as outfile:
  245. while True:
  246. chunk = infile.read(chunksize)
  247. if len(chunk) == 0:
  248. break
  249. outfile.write(decryptor.decrypt(chunk))
  250. outfile.truncate(filesize)
  251. """def getKey(password):
  252. hasher = SHA256.new(password)
  253. return hasher.digest()"""
  254. def file_check(filename):
  255. try:
  256. open(filename, 'r')
  257. return 1
  258. except:
  259. print ("This file doesnt exist")
  260. return 0
  261. def AESmenu(EncDec):
  262. choice = raw_input("Would you like to (E)ncrypt or (D)ecrypt?: ")
  263. f_in = raw_input("Insert the filename with extension: ")
  264. fileblob = file_check(f_in)
  265. while fileblob == 0:
  266. f_in = raw_input("insert the filename with extensions")
  267. fileblob = file_check(f_in)
  268. print( f_in )
  269. #print "3rd time: ", EncDec
  270. if choice == 'E':
  271. #filename = raw_input("File to encrypt: ")
  272. encrypt(EncDec, f_in)
  273. print ("Done.")
  274. elif choice == 'D':
  275. decrypt(EncDec, f_in)
  276. print( "Done.")
  277. else:
  278. print ("No Option selected, closing...")
  279. def main ():
  280. decision = get_decision()
  281. while decision is not "quit" and decision is not "2":
  282. print( "Please choose form the following.")
  283. choice = ""
  284. 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":
  285. choice = raw_input()
  286. if choice == "1":
  287. print ("\nBiometric Enrollment")
  288. hashcode = enroll()
  289. print (hashcode)
  290. AES_full(hashcode)
  291. if choice == "2":
  292. print( "\nShow Biometric Index")
  293. index()
  294. if choice == "3":
  295. print ("\nSearch Index Using Biometrics")
  296. fp_search()
  297. if choice == "4":
  298. print ("\nDownload Biometric Image")
  299. fp_download()
  300. if choice == "5":
  301. print ("\nDelete Biometric Image")
  302. delete()
  303. '''
  304. print "The message inserted was: %s " % message
  305. ciphertext = encrypt(message , m)
  306. print "Lets apply RC4 with salt for security"
  307. cipherplay = ''.join(ciphertext)
  308. RC = encryptRC(cipherplay, matrix_key)
  309. print "Message with RC4 with salt"
  310. print RC
  311. print "Do you want to save the message to a file? (Y/N)"
  312. answer = raw_input()
  313. while answer is not "Y" and answer is not "y" and answer is not "N" and answer is not "n":
  314. print "Do you want to save the message to a file? (Y/N)"
  315. answer = raw_input()
  316. if answer == "Y" or answer == "y":
  317. fout = open('Encrypted.txt', 'w')
  318. fout.write(RC)
  319. fout.close()
  320. print "Message save to file Encrypted.txt on the folder of this program\n"
  321. print "Press Enter to continue:"
  322. raw_input()
  323. else:
  324. print "Press enter to continue"
  325. raw_input()
  326. decision = get_decision()
  327. elif choice == "2":
  328. ch_enc = ""
  329. print "\nMessage Decryption:"
  330. print "1 - Open a custom file"
  331. print "2 - Copy the encrypted message"
  332. ch_enc = raw_input()
  333. if ch_enc == "1":
  334. print "Insert the filename with extension"
  335. f_in = raw_input()
  336. file = file_check(f_in)
  337. while file == 0:
  338. print "Insert the filename with the extension"
  339. f_in = raw_input()
  340. file = file_check(f_in)
  341. fin = open(f_in, 'U')
  342. RCmessage = fin.read()
  343. fin.close()
  344. elif ch_enc == "2":
  345. print "Insert the encripted message:"
  346. RCmessage = raw_input()
  347. print "You inserted ", RCmessage
  348. ms = decryptRC(RCmessage, matrix_key)
  349. message = get_message(ms)
  350. plaintext = decrypt(message, m)
  351. print "\nPress enter to continue"
  352. raw_input()
  353. decision = get_decision()
  354. else:
  355. print "Wrong Choice"
  356. print "Thanks for using the software \nGood Bye"
  357. raw_input()
  358. '''
  359. if __name__ == "__main__":
  360. main()