在Python中,需要保持OpenSSL的活力并继续命令



我在此处使用以下实现尝试了一种方法:

from subprocess import PIPE, Popen
process = Popen(['/usr/bin/openssl', 'enc', '-aes-256-cbc', '-a', '-pass', 'pass:asdf'], stdin=PIPE, stdout=PIPE)
process.stdin.write('Hello this is it')
process.stdin.flush()
print(repr(process.stdout.readline()))

,但它卡在 readline()上,尽管我已经写了并冲洗了。我还尝试了此处提到的非阻滞方法,但这也在 readline()上阻止。以下是我以后方法的代码:

import sys
import time
from subprocess import PIPE, Popen
from threading import Thread
from Queue import Queue, Empty
def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()
def write_to_stdin(process):
    process.stdin.write(b'Hello this is it')
p = Popen(['/usr/bin/openssl', 'enc', '-aes-256-cbc', '-a', '-pass', 'pass:asdf'], stdin=PIPE, stdout=PIPE, bufsize=-1, close_fds=ON_POSIX)
q = Queue()
t2 = Thread(target=write_to_stdin, args=(p,))
t2.daemon = True
t2.start()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True  # thread dies with the program
t.start()
try:
    line = q.get(timeout=3) # or q.get(timeout=.1)
except Empty:
    print('no output yet')
else:
    print line

i获得尚未输出作为输出。

使用的唯一方法是使用:

process.communicate

但这关闭了过程,我们必须再次重新打开该过程。要加密大量消息,这需要花费太多时间,我试图避免包括任何用于完成此任务的外部软件包。任何帮助都将不胜感激。

process.stdin.close()替换process.stdin.flush(),如下:

from subprocess import PIPE, Popen
process = Popen(['/usr/bin/openssl', 'enc', '-aes-256-cbc', '-a', '-pass', 'pass:asdf'], stdin=PIPE, stdout=PIPE)
process.stdin.write('Hello this is it')
process.stdin.close()
print(repr(process.stdout.readline()))

readline()不再阻止。

解释是openssl enc等到其标准输入结束,仅在呼叫过程关闭管道时才能到达。

使用ctypescrypto在Linux中找到了另一种方法。这不需要任何其他外部依赖项(只需在您的代码中包括所有给定的源文件,因为许可证允许我们这样做),就性能而言,它应该很快,因为可用的功能已编译为C <<

在Linux上 test.py 我们必须替换:

crypto_dll = os.path.join(r'C:Python24', 'libeay32.dll')
libcrypto = cdll.LoadLibrary(crypto_dll)

with:

from ctypes.util import find_library
crypto_dll = find_library('crypto')  # In my case its 'libcrypto.so.1.0.0'
libcrypto = cdll.LoadLibrary(crypto_dll)

更改以下示例可行:

import cipher
from ctypes import cdll
from base64 import b64encode
from base64 import b64decode
libcrypto = cdll.LoadLibrary('libcrypto.so.1.0.0')
libcrypto.OpenSSL_add_all_digests()
libcrypto.OpenSSL_add_all_ciphers()
# Encryption
c = cipher.CipherType(libcrypto, 'AES-256', 'CBC')
ce = cipher.Cipher(libcrypto, c, '11111111111111111111111111111111', '1111111111111111', encrypt=True)
encrypted_text = b64encode(ce.finish("Four Five Six"))
print encrypted_text

# Decryption
cd = cipher.Cipher(libcrypto, c, '11111111111111111111111111111111', '1111111111111111', encrypt=False)
plain_text = cd.finish(b64decode(encrypted_text))
print plain_text

最新更新