"Fossies" - the Fresh Open Source Software Archive

Member "Tardis-1.2.1/tools/encryptFile.py" (9 Jun 2021, 5040 Bytes) of package /linux/privat/Tardis-1.2.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "encryptFile.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.1.5_vs_1.2.1.

    1 #! /usr/bin/env python3
    2 # vim: set et sw=4 sts=4 fileencoding=utf-8:
    3 #
    4 # Tardis: A Backup System
    5 # Copyright 2013-2020, Eric Koldinger, All Rights Reserved.
    6 # kolding@washington.edu
    7 #
    8 # Redistribution and use in source and binary forms, with or without
    9 # modification, are permitted provided that the following conditions are met:
   10 #
   11 #     * Redistributions of source code must retain the above copyright
   12 #       notice, this list of conditions and the following disclaimer.
   13 #     * Redistributions in binary form must reproduce the above copyright
   14 #       notice, this list of conditions and the following disclaimer in the
   15 #       documentation and/or other materials provided with the distribution.
   16 #     * Neither the name of the copyright holder nor the
   17 #       names of its contributors may be used to endorse or promote products
   18 #       derived from this software without specific prior written permission.
   19 #
   20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   21 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   24 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   25 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   26 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   27 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   28 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   29 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   30 # POSSIBILITY OF SUCH DAMAGE.
   31 
   32 from Tardis import Defaults, Util, TardisDB, TardisCrypto, CacheDir, librsync, Regenerator, Config, CompressedBuffer
   33 import sqlite3
   34 import argparse, logging
   35 import os.path
   36 import os
   37 import sys
   38 import base64
   39 import hashlib
   40 import sys
   41 import progressbar
   42 import uuid
   43 import json
   44 import shutil
   45 import traceback
   46 
   47 logger = None
   48 
   49 class FileSender:
   50     def __init__(self, output):
   51         if isinstance(output, str):
   52             self.output = file(output, "rw")
   53         else:
   54             self.output = output
   55 
   56     def sendMessage(self, message, raw=True):
   57         if not isinstance(message, dict):
   58             self.output.write(message)
   59 
   60 def processArgs():
   61     parser = argparse.ArgumentParser(description='Encrypt files for a backup database', add_help = False)
   62 
   63     (_, remaining) = Config.parseConfigOptions(parser)
   64     Config.addCommonOptions(parser)
   65     Config.addPasswordOptions(parser)
   66 
   67     parser.add_argument('--output', '-o', dest='output', required=True, help="Output directory")
   68     parser.add_argument('--json', '-j', default=None, dest='input', help='JSON input file')
   69     parser.add_argument('--signature', '-s', default=False, action='store_true', dest='signature', help='Generate signature file')
   70     parser.add_argument('--compress-data',  '-Z',   dest='compress', const='zlib', default=None, nargs='?', choices=CompressedBuffer.getCompressors(),
   71                         help='Compress files')
   72     parser.add_argument('names',          nargs='*', help="List of pathnames to decrypt")
   73     parser.add_argument('--help', '-h',   action='help');
   74 
   75     Util.addGenCompletions(parser)
   76 
   77     args = parser.parse_args(remaining)
   78 
   79     return args
   80 
   81 def processFile(outdir, crypto, name, compress='none', signature=False):
   82     outname = str(uuid.uuid1())
   83     outpath = os.path.join(outdir, outname)
   84     outfile = open(outpath, "wb")
   85     s = FileSender(outfile)
   86     infile = open(name, "rb")
   87     size, ck, sig = Util.sendData(s, infile, crypto.getContentEncryptor(), hasher=crypto.getHash(), signature=True, compress=compress)
   88     infile.close()
   89     outfile.close()
   90     newpath = os.path.join(outdir, ck)
   91     print(name, size, ck, outpath)
   92     os.rename(outpath, newpath)
   93 
   94     if signature:
   95         outpath = os.path.join(outdir, ck + ".sig")
   96         with open(outpath, "wb") as sigfile:
   97             shutil.copyfileobj(sig, sigfile)
   98 
   99 def main():
  100     global logger
  101     progressbar.streams.wrap_stderr()
  102     logging.basicConfig(level=logging.INFO)
  103     logger = logging.getLogger('')
  104     args = processArgs()
  105     password = Util.getPassword(args.password, args.passwordfile, args.passwordprog, allowNone=False)
  106 
  107     (db, cacheDir, crypto) = Util.setupDataConnection(args.database, args.client, password, args.keys, args.dbname, args.dbdir)
  108 
  109     if args.input:
  110         files = json.load(open(args.input, "r"))
  111         for x in files:
  112             try:
  113                 processFile(args.output, crypto, x, args.compress, args.signature)
  114             except Exception as e:
  115                 print(f"----> {str(e)} Processing {files[x]}")
  116                 traceback.print_exc()
  117 
  118     for name in args.names:
  119         try:
  120             processFile(args.output, crypto, name, args.compress, args.signature)
  121         except Exception as e:
  122             print(f"----> {str(e)} Processing {name}")
  123             traceback.print_exc()
  124 
  125 
  126 if __name__ == "__main__":
  127     main()