Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2015
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #/usr/bin/python
  2.  
  3. import sys
  4. import argparse
  5. import nacl.secret
  6. import nacl.utils
  7.  
  8. #dependency: pyNaCl and libsodium
  9. #usage -- python filecrypt.py -f <enc/dec> -i <input_filename> -o <output_filename> -k <key>
  10.  
  11. def main():
  12. key, input_file, output_file, flag = get_args()
  13. enc_dec(key,input_file,output_file,flag)
  14.  
  15. def get_args():
  16. # Getting arguments from the command line.
  17.  
  18. parser = argparse.ArgumentParser(description = 'This is a command line program for file encryption/decryption')
  19.  
  20. parser.add_argument('-f', '--flag', type=str, help='enc/dec', required = True)
  21. parser.add_argument('-i', '--inp_file', type=str, required = True)
  22. parser.add_argument('-o', '--out_file', type=str, required = True)
  23. parser.add_argument('-k', '--key', type=str, help='KEY for encryption/decryption', required = True)
  24.  
  25. args = parser.parse_args()
  26.  
  27. key = args.key
  28. input_file = args.inp_file
  29. output_file = args.out_file
  30. flag = args.flag
  31.  
  32. return key, input_file, output_file, flag
  33.  
  34. def enc_dec(key,input_file,output_file,flag):
  35. #Main encryption/ decryption function
  36.  
  37. try:
  38. box = nacl.secret.SecretBox(key) # using the same keysize as defined by NaCl (32 bytes)
  39. except ValueError:
  40. print "key must be equal to exactly 32 bytes long"
  41. sys.exit(2)
  42.  
  43. try:
  44. inp_stream = open(input_file,"rb").read()
  45.  
  46. if flag == "enc":
  47. nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) # random nonce for file encryption
  48. out_stream= box.encrypt(inp_stream,nonce)
  49. elif flag == "dec":
  50. out_stream = box.decrypt(inp_stream)
  51. else:
  52. print "Only enc or dec options are available"
  53. sys.exit(2)
  54. except IOError:
  55. print "Unable to find the file <",input_file,">. Please check the file name"
  56. sys.exit(2)
  57.  
  58. try:
  59. file=open(output_file, "wb")
  60. except IOError:
  61. print " Unable to create output file on disk"
  62. else:
  63. file.write(out_stream)
  64. file.close()
  65.  
  66.  
  67. if __name__ == '__main__':
  68. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement