Guest User

Untitled

a guest
May 13th, 2013
13
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import struct
  3. from Crypto import Random
  4. from Crypto.Hash import SHA256
  5. from Crypto.Cipher import AES
  6.  
  7. random_generator_file = Random.new()
  8.  
  9. # format
  10. # -----header------
  11. # iv <- 16bytes
  12. # chunksize <- <Q
  13. # -----------------
  14. # ------chunk------
  15. # size <- <Q
  16. # data <- chunksize
  17. # -----------------
  18.  
  19. def encrypt(key, infile, outfile, chunksize=1024):
  20. iv = random_generator_file.read(16)
  21. encryptor = AES.new(key, AES.MODE_CBC, iv)
  22. outfile.write(iv)
  23. outfile.write(struct.pack('<Q', chunksize))
  24.  
  25. while True:
  26. chunk = infile.read(chunksize)
  27. outfile.write(struct.pack('<Q', len(chunk)))
  28. if len(chunk) == 0:
  29. break
  30. elif len(chunk) % chunksize != 0:
  31. chunk += 'M' * (chunksize - len(chunk) % chunksize)
  32. outfile.write(encryptor.encrypt(chunk))
  33.  
  34. def decrypt(key, infile, outfile):
  35. iv = infile.read(16)
  36. decryptor = AES.new(key, AES.MODE_CBC, iv)
  37. chunksize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
  38.  
  39. while True:
  40. size = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
  41. if size == 0:
  42. break
  43. chunk = infile.read(chunksize)
  44. outfile.write(decryptor.decrypt(chunk)[:size])
  45.  
  46. mode = sys.argv[2]
  47. hashkey = SHA256.new()
  48. hashkey.update(sys.argv[1])
  49. key = hashkey.digest()
  50.  
  51. if mode == "encrypt":
  52. encrypt(key, sys.stdin, sys.stdout)
  53. elif mode == "decrypt":
  54. decrypt(key, sys.stdin, sys.stdout)
RAW Paste Data