Search code examples
linuxbashshellencryptiongnupg

GPG with triple pipe and keyfile


I want to tar, compress with xz and then encrypt symmetrically with gpg using a key file. I could to this with a for loop, but would rather like to do it by piping.

I tried the following, but it didn't work because of "Ambiguous input redirect":

tar cvf /home/user/backupdir | xz -1 | gpg -c --batch --passphrase-fd 0 --yes --symmetric --cipher-algo TWOFISH --digest-algo SHA512 -o backupdir.tar.xz.gpg < keyfile

Could someone help me maybe out with that, encryption and decryption by piping?

Thank you!


Solution

  • You are basically doing:

    tar | xz | gpg <file
    

    In this chain you tell gpg to get input both from file and from the previous command.

    There is only one STDIN you cannot read from two sources.

    The man page gives a few solutions:

       --passphrase-fd n
              Read the passphrase from file descriptor n. Only the first line will
              be  read  from file descriptor n. If you use 0 for n, the passphrase
              will be read  from  STDIN.  This  can  only  be  used  if  only  one
              passphrase  is  supplied.  Note that this passphrase is only used if
              the option --batch has also been given.  This is different from gpg.
    
       --passphrase-file file
              Read the passphrase from file file. Only the first line will be read
              from file file. This can only be used if only one passphrase is sup‐
              plied. Obviously, a passphrase stored in a file is  of  questionable
              security if other users can read this file. Don't use this option if
              you can avoid it.  Note that this passphrase is  only  used  if  the
              option --batch has also been given.  This is different from gpg.
    
       --passphrase string
              Use  string  as  the  passphrase.  This can only be used if only one
              passphrase is supplied. Obviously,  this  is  of  very  questionable
              security  on  a  multi-user system. Don't use this option if you can
              avoid it.  Note that this passphrase is  only  used  if  the  option
              --batch has also been given.  This is different from gpg.
    

    Since you already have the passphrase in a file, the second option looks good for you.

    If the second option is not available or not working at your gpg version, you can use the first option instead:

    gpg --passphrase-fd 3 3<keyfile
    

    In this case gpg will get the data on STDIN and the keyfile on file descriptor 3.