Python: Using openssl via subprocess to decrypt with a variable password

Viewed 931

I am trying to use subprocess to run an openssl command via a python script to decrypt an already encrypted file with the known password.

The code I have works, but I want to be able to save a password as a variable, i.e. pass = 'password' and input that variable into the subprocess call rather than have it statically as pass:password . Without worrying about how I get the password saved to the variable, and just focusing on passing it as a variable to the subprocess call, is this possible?

I was reading the PASS PHRASE ARGUEMENTS section of the OpenSSL man page, so I'm curious if I should be using one of the other options (env:var, file:pathname, fd:number, or stdin). However it's hard to find examples of them in use, so I'm not sure.

Here is what I have so far:

def decryptfile():
decryptFile = subprocess.Popen(["openssl", "aes-256-cbc", "-d", "-a", "-in", "pw.txt", 
                                "-out", "pw.dec.txt", "-pass", "pass:password"]
)
2 Answers

I have worked with python for quite some time now, and I know how to store output from the subprocess module into a user defined variable as follows

import subprocess

value = subprocess.getoutput("Your Command")
print("The variable value is holding: {}".format(value))

As far as getting the password as a variable try splitting the data from the subprocess output (now stored in variable) into a list. You can also format that list to what you need. You can set a password variable with a value equivalent to a value inside of that list by indexing that lists values, example:

hello = subprocess.getoutput("echo hello")
list_hello = list(hello)
# print the index value of 1 to return hello
# use string interpolation
print("Second value in subprocess call is : {}".format(list_hello[1]))
# store the value of "hello" in "echo hello"
# to a variable
hello_str = str(list_hello[1])
# you should cast the variable to a string
# data type just to be safe
print("The value of hello_str is: {}".format(hello_str))

Use string interpolation

value = "my_value"
subprocess.call("commands {}".format(value), shell=True)

Use that string interpolation method to call/include your variable with your ssl command (password)

Related