Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8193599
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:31:54+00:00 2026-06-07T04:31:54+00:00

I’m trying to remote control gpg through a python program via POpen . I

  • 0

I’m trying to remote control gpg through a python program via POpen.
I have a file that contains encrypted data which I want to decrypt, modify and write back to disk re-encrypted.
Currently I am storing the decrypted information in a temporary file (which I shred when the program ends). Then I perform my modifications to that file and then re-encrypt it using a function, which pipes the passphrase through stdin.
The code for this is as follows:

def encrypt(source, dest, passphrase, cipher=None):
  """Encrypts the source file.
  @param source Source file, that should be encrypted.
  @param dest Destination file.
  @param passphrase Passphrase to be used.
  @param cipher Cipher to use. If None or empty string gpg's default cipher is
  used.
  """
  phraseecho = Popen(("echo", passphrase), stdout=subprocess.PIPE)

  gpgargs = [
          "gpg",
          "-c",
          "--passphrase-fd", "0", # read passphrase from stdin
          "--output", dest,
          "--batch",
          "--force-mdc"]
  if not cipher is None and len(cipher) > 0:
      gpgargs.extend(("--cipher-algo", cipher))

  gpgargs.append(source)

  encrypter = Popen(
          gpgargs,
          stdin=phraseecho.stdout,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE)
  stdout, stderr = encrypter.communicate()
  rc = encrypter.returncode
  if not rc == 0:
      raise RuntimeError(
              "Calling gpg failed with return code %d: %s" % (rc, stderr))

This works perfectly well, but I’m fairly sure that storing potentionally sensitive, decrypted data in a temporary file is a rather big security flaw.
So I want to rewrite my encryption/decryption functions in a way, that enables them to work completely in memory without storing sensitive data on disk.
Decryption works straight forward by also piping the passphrase via stdin and capturing stdout for the decrypted data.

Encryption on the other hand drives me mad, since I can’t just pipe the passphrase AND the message to `stdin’…at least

encrypter.stdin.write("%s\n%s" % (passphrase, message))

didn’t work.
My next best guess is to supply the file-descriptor of some kind of in-memory file/pipe/socket or whatever as --passphrase-fd argument. The thing is: I don’t know if there even is a thing such as in-memory files or if sockets would apply, since I never used them.

Can anybody help out or point me to a better solution for my problem?
The solution does not have to be portable – I’m totally fine with Linux only approaches.

Thanks in advance…

Edit:
Thanks a lot to both of you, Lars and ryran. Both solutions work perfectly! Unfortunately I can only accept one

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T04:31:55+00:00Added an answer on June 7, 2026 at 4:31 am

    Below is the code I use in Obnam to run gpg,
    perhaps it can be of some assistance to you.

    def _gpg_pipe(args, data, passphrase):
        '''Pipe things through gpg.
    
        With the right args, this can be either an encryption or a decryption
        operation.
    
        For safety, we give the passphrase to gpg via a file descriptor.
        The argument list is modified to include the relevant options for that.
    
        The data is fed to gpg via a temporary file, readable only by
        the owner, to avoid congested pipes.
    
        '''
    
        # Open pipe for passphrase, and write it there. If passphrase is
        # very long (more than 4 KiB by default), this might block. A better
        # implementation would be to have a loop around select(2) to do pipe
        # I/O when it can be done without blocking. Patches most welcome.
    
        keypipe = os.pipe()
        os.write(keypipe[1], passphrase + '\n')
        os.close(keypipe[1])
    
        # Actually run gpg.
    
        argv = ['gpg', '--passphrase-fd', str(keypipe[0]), '-q', '--batch'] + args
        tracing.trace('argv=%s', repr(argv))
        p = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        out, err = p.communicate(data)
    
        os.close(keypipe[0])
    
        # Return output data, or deal with errors.
        if p.returncode: # pragma: no cover
            raise obnamlib.Error(err)
    
        return out
    
    
    def encrypt_symmetric(cleartext, key):
        '''Encrypt data with symmetric encryption.'''
        return _gpg_pipe(['-c'], cleartext, key)
    
    
    def decrypt_symmetric(encrypted, key):
        '''Decrypt encrypted data with symmetric encryption.'''
        return _gpg_pipe(['-d'], encrypted, key)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to loop through a bunch of documents I have to put
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to create an if statement in PHP that prevents a single post
I have a reasonable size flat file database of text documents mostly saved in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.