Python中的Eyaml字符串加密

时间:2017-04-03 13:35:40

标签: 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", '')}]"

在另一个模块中,我使用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 + ']'

0 个答案:

没有答案