pyopenssl
pyopenssl copied to clipboard
add encrypt and decrypt to PKCS7
In Ruby, it's simple to use PKC7 to encrypt/decrypt
public_key_pem = File.read public_key
public_key_x509 = OpenSSL::X509::Certificate.new( public_key_pem )
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
OpenSSL::PKCS7::encrypt([public_key_x509], plaintext, cipher,
It's so painful in Python. We could use M2Crypto but Python3 is not yet supported.
So, PyOpenSSL don't provide advanced features for PKCS7 and this PR will try to make it more "pythonic" and more similar to PKCS12.
To use it:
from OpenSSL.crypto import PKCS7
from OpenSSL.crypto import FILETYPE_PEM
from OpenSSL.crypto import load_privatekey, load_certificate
data = """-----BEGIN PKCS7-----
...
-----END PKCS7-----"""
public_key = "content of the certificate"
private_key = "content of the private key"
cert_obj = load_certificate(FILETYPE_PEM, public_key)
pkey_obj = load_privatekey(FILETYPE_PEM, private_key)
# From encrypted data
pkcs7_obj = PKCS7.from_data(FILETYPE_PEM, data)
pkcs7_obj.set_certificate(cert_obj)
pkcs7_obj.set_privatekey(pkey_obj)
print("decrypted", pkcs7_obj.decrypt())
('decrypted', 'PyOpenSSL is fun!')
# From clear data
pkcs7_obj = PKCS7.encrypt(cert_obj, "PyOpenSSL is fun!", 'blowfish')
pkcs7_obj.set_privatekey(pkey_obj)
print("decrypted", pkcs7_obj.decrypt())
('decrypted', 'PyOpenSSL is fun!')
print("crypted:" pkcs7_obj.get_encrypted_data())
-----BEGIN PKCS7-----
MIIBVQYJKoZIhvcNAQcDoIIBRjCCAUICAQAxgf4wgfsCAQAwZDBYMQswCQYDVQQG
EwJVUzELMAkGA1UECBMCSUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rl
c3RpbmcxGDAWBgNVBAMTD1Rlc3RpbmcgUm9vdCBDQQIIPQzE4MbeufQwDQYJKoZI
hvcNAQEBBQAEgYBMaK0ddpuFds46bacHaEu9mcvF4bNGRaqMnjXBDc+qBobzJW/B
NzQ9cTEIk59+e8MjzTT8odAooGCarvVcw3MugkEluaVAH1O6OUjfxHQ+t7+Y+YNm
i+rYGL+ltDwvj1AlL5B+RocjH5KsHd+gCHzAhLvf2MOuGs/hs/i3RTijLTA8Bgkq
hkiG9w0BBwEwFQYJKwYBBAGXVQECBAj4R8pC68gRZ4AYQeKa/KwYUy89T+Wfpvtn
xVfCFXHLKB8m
-----END PKCS7-----
Generally I suspect we'd rather have the appropriate tools for this in cryptography rather than extend PyOpenSSL to be able to do this. @reaperhulk @alex is cryptography equipped to fill this need today? If not, how much work is required to extend it?
@Lukasa PKCS7 encrypt/decrypt is not available in cryptography, I could try to make a new PR on it if pyopenssl is no longer "featured".
Yes, generally speaking x509 functionality should go into cryptography because our next big goal in pyOpenSSL is to integrate cryptography’s x509 layer so there’s no double work.
Ok, just found how to use low level binding and how to adapt this PR to cryptography. But, it's a bit confusing on where need I to put this.
Feel free to ask on IRC or the mailing list: https://cryptography.io/en/latest/community/
(Apologies we let this sit for 6 years)
We are no longer adding to the pkcs7 APIs in pyopenssl. if anyone is still interested in working on this, pyca/cryptography is the place to do it.