luc*_*ini 5 python encryption puppet
我正在用 Python 生成 puppet hieradata yml 文件。
我想用 Python 实现以下 Ruby 代码...
public_key_pem = File.read(puppet_key_file)
@public_key_x509 = OpenSSL::X509::Certificate.new( public_key_pem )
@cipher = OpenSSL::Cipher::AES.new(256, :CBC)
ciphertext = OpenSSL::PKCS7::encrypt([@public_key_x509],
plaintext,
@cipher,
OpenSSL::PKCS7::BINARY
).to_der
"ENC[PKCS7,#{Base64.encode64(ciphertext).gsub("\n", '')}]"
Run Code Online (Sandbox Code Playgroud)
在另一个模块中,我正在使用 PyOpenssl 处理证书签名和密钥生成,但我注意到加密方法没有实现......
M2Crypto 的潜在解决方案...
from M2Crypto import SMIME, X509, BIO
def encrypt(self, plaintext):
"""
Encrypt a string using the previously generated public key AES-256-CBC, SMIME PKCS7 envelop
:param plaintext: The text to encrypt
:type plaintext: str
:returns: The encrypted text
:rtype: str
"""
buf = BIO.MemoryBuffer(plaintext)
smime = SMIME.SMIME()
x509 = X509.load_cert_string(self.certificate)
certs = X509.X509_Stack()
certs.push(x509)
smime.set_x509_stack(certs)
smime.set_cipher(SMIME.Cipher('aes_256_cbc'))
encrypted = smime.encrypt(buf)
out = BIO.MemoryBuffer()
encrypted.write(out)
buf = out.read()
buf = buf.strip().replace("-----BEGIN PKCS7-----", '').replace("-----END PKCS7-----", '').replace("\n", '')
return 'ENC[PKCS7,' + buf + ']'
Run Code Online (Sandbox Code Playgroud)
并不是您问题的真正答案,而是如果您安装了 eyaml-hiera 的话的解决方法:
import subprocess
PATH = 'd:\\path\\to\\scripts\\'
EYAML = PATH + 'jruby-9.3.7.0\\bin\\eyaml.bat'
DIR = PATH + 'eyaml' # contains keys\\public_key.pkcs7.pem
def encrypt(password):
args = [EYAML, 'encrypt', '--string', password]
subprocess.run(args, timeout=10, cwd=DIR)
Run Code Online (Sandbox Code Playgroud)
(当我尝试从命令行运行时,替换被搞乱了,所以在这种情况下可以提供帮助)