Error while creating a self signed certificate using pyopenssl - python-3.x

from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
CERT_FILE = "selfsigned.crt"
KEY_FILE = "private.key"
def create_self_signed_cert():
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "UK"
cert.get_subject().ST = "London"
cert.get_subject().L = "London"
cert.get_subject().O = "Dummy Company Ltd"
cert.get_subject().OU = "Dummy Company Ltd"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(CERT_FILE, "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
create_self_signed_cert()
I am trying to create self certificate but its displaying error :
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
TypeError: write() argument must be str, not bytes
please help me.

I think os.write() will be able to write the buffer returned by crypto.dump_certificate :
import os
f = os.open(CERT_FILE)
os.write(f, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
os.close(f)

In python 3 I used decode
open(CERT_FILE, "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode())
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode())

You may use "write binary" file open mode
by replacing the value "wt" with "wb" in open(FILE, "wt").

Related

Decrypt data using cryptography package giving error "ValueError: Encryption/decryption failed."

import base64
import os.path
from shutil import copyfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.backends.openssl.rsa import _RSAPublicKey, _RSAPrivateKey
from asym_crypto_yaml import (decrypt_value, encrypt_value, Encrypted,
load_private_key_from_file, load_public_key_from_file,
generate_new_private_key, generate_new_public_key,
load, dump, NUMBER_OF_BYTES_PER_ENCRYPTED_CHUNK, KEY_CHUNK_SIZE,
SUPPORTED_KEY_SIZES, generate_private_key_to_file, generate_private_key_to_file, generate_public_key_to_file,
encrypt_value_and_print ,add_secret_to_yaml_file, decrypt_yaml_file_and_write_encrypted_file_to_disk,
reencrypt_secrets_and_write_to_yaml_file)
from functools import reduce
def test_add_secret_to_yaml_file():
private_key_output_filename = "/home/asy/private_key.private"
public_key_output_filename = "/home/asy/public_key.public"
private_key = generate_private_key_to_file(private_key_output_filename)
public_key = generate_public_key_to_file(private_key_output_filename, public_key_output_filename)
yaml_file_fixture = "/home/asy/saml.yml"
yaml_file_to_append_to = "/home/asy/saml_du.yml"
test_key_to_encrypt = ['FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET', 'AWS_S3_BUCKET', 'SECRET_TOKEN', 'TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET',
'TWITTER_OAUTH_TOKEN', 'TWITTER_OAUTH_TOKEN_SECRET', 'LINKEDIN_API_KEY', 'LINKEDIN_SECRET_KEY']
print ("################################ENCRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
# Encrypt data in yml file
for test_key in test_key_to_encrypt:
print ('Encrypted key is:', test_key)
print ('Encrypted value is:', before_dict[test_key])
add_secret_to_yaml_file(test_key, before_dict[test_key], public_key_output_filename, yaml_file_to_append_to)
print ("################################DECRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
# Decrypt data from yml file (Using same function)
for test_key_value in test_key_to_encrypt:
print ('key is', before_dict[test_key_value])
test_encrypted_key_value = decrypt_value(before_dict[test_key_value], private_key)
print ("decrypt data", test_encrypted_key_value)
#
def decrypt_data():
private_key_output_filename = "/home/asy/private_key.private"
public_key_output_filename = "/home/asy/public_key.public"
private_key = generate_private_key_to_file(private_key_output_filename)
public_key = generate_public_key_to_file(private_key_output_filename, public_key_output_filename)
yaml_file_to_append_to = "/home/asy/saml_du.yml"
test_key_to_encrypt = ['FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET', 'AWS_S3_BUCKET', 'SECRET_TOKEN', 'TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET',
'TWITTER_OAUTH_TOKEN', 'TWITTER_OAUTH_TOKEN_SECRET', 'LINKEDIN_API_KEY', 'LINKEDIN_SECRET_KEY']
print ("################################DECRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
for test_key_value in test_key_to_encrypt:
print ('key is', test_key_value)
print ('value is', before_dict[test_key_value])
test_encrypted_key_value = decrypt_value(before_dict[test_key_value], private_key)
print ("decrypt data", test_encrypted_key_value)
if __name__ == "__main__":
test_add_secret_to_yaml_file()
# decrypt_data()
sample yml file:
SECRET_TOKEN: "d4e5783de1c74c7a4e3a27578df6gdgf6g786g8df7g6g87d6fgb709"
FACEBOOK_APP_ID: "35864341"
FACEBOOK_APP_SECRET: "759a1e7sd7fvyfsd473"
TWITTER_CONSUMER_KEY: "1UrRKJDF8SD7FSDF3S"
TWITTER_CONSUMER_SECRET: "5W7TE8KJJk787bnG0s"
TWITTER_OAUTH_TOKEN: "716397744-3rHXFkFkjKjkjK78PQ5"
TWITTER_OAUTH_TOKEN_SECRET: "DuDJKFSD89SDFD"
LINKEDIN_API_KEY: "2vjkJKjk4"
LINKEDIN_SECRET_KEY: "5KLSJDFsE"
GMAIL_USERNAME: "username#gmail.com"
GMAIL_PASSWORD: "PASSWORD"
AWS_ACCESS_KEY_ID: "ASDKLSDJFIA"
AWS_SECRET_ACCESS_KEY: "7ASDFJksdfjskdlf87sdfKb"
AWS_S3_BUCKET: "bucket"
development:
MAILER_HOST: "localhost:3000"
test:
MAILER_HOST: "localhost:3000"
production:
MAILER_HOST: "domain.com"
I am using "asym_crypto_yaml" yaml package to write encrypted value in .yml file.
I am not able to decrypt value from different decrypt function (decrypt_data()).
Above code only decrypt value if I execute code first time. But from second time its giving "encryption/decryption error".
My objective is to decrypt data from yml file. Little help will be appreciated.
The error is triggered because the private key used in decrypt_data() for decryption does not belong to the public key used in test_add_secret_to_yaml_file() to perform the encryption. Therefore, decryption with this private key fails.
The problem can be solved by using in decrypt_data() the private key of the key pair generated in test_add_secret_to_yaml_file(). To do this, remove the generate_private_key_to_file() and generate_public_key_to_file() calls (to generate and store a key pair) in decrypt_data(). The required private key can be loaded with load_private_key_from_file() from the file where it was stored in test_add_secret_to_yaml_file().
This ValueError: Encryption/decryption failed. Error is also thrown by the hazmat class when the data you want to encrypt is too large for the size of key that you generated. Try again by using larger key size like this.
private_key = rsa.generate_private_key(public_exponent=65537, key_size = 4096)
but keep in mind it will increase time to generate key, that is one of the biggest disadvantage of RSA encryption algorithm.

Export RSA Keys to stunnel.key [duplicate]

I followed this url to create a X509 certificate. And the code is:
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
CERT_FILE = "selfsigned.crt"
KEY_FILE = "private.key"
def create_self_signed_cert():
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_<wbr>RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "UK"
cert.get_subject().ST = "London"
cert.get_subject().L = "London"
cert.get_subject().O = "Dummy Company Ltd"
cert.get_subject().OU = "Dummy Company Ltd"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60)
cert.set_issuer(cert.get_<wbr>subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(CERT_FILE, "wt").write(
crypto.dump_certificate(<wbr>crypto.FILETYPE_PEM, cert))
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.<wbr>FILETYPE_PEM, k))
create_self_signed_cert()
But there is something wrong with the code when I run it. Could someone tell me what the meaning of <wbr>? There is a SyntaxError in cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60). Thx.
A version which works with python3
from OpenSSL import crypto, SSL
def cert_gen(
emailAddress="emailAddress",
commonName="commonName",
countryName="NT",
localityName="localityName",
stateOrProvinceName="stateOrProvinceName",
organizationName="organizationName",
organizationUnitName="organizationUnitName",
serialNumber=0,
validityStartInSeconds=0,
validityEndInSeconds=10*365*24*60*60,
KEY_FILE = "private.key",
CERT_FILE="selfsigned.crt"):
#can look at generated file using openssl:
#openssl x509 -inform pem -in selfsigned.crt -noout -text
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = countryName
cert.get_subject().ST = stateOrProvinceName
cert.get_subject().L = localityName
cert.get_subject().O = organizationName
cert.get_subject().OU = organizationUnitName
cert.get_subject().CN = commonName
cert.get_subject().emailAddress = emailAddress
cert.set_serial_number(serialNumber)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(validityEndInSeconds)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha512')
with open(CERT_FILE, "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
with open(KEY_FILE, "wt") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
cert_gen()
Just remove <wbr>. So stupid I am.
This is a really useful question; as the referenced link is now dead; and this is one of the first results for searching for "python create ssl certificate".
I would add to it though, that "open(xxx, "wt").write()" is asking for problems later. By not explicitly closing the file, you may find that the garbage collector hasn't run when you try to actually use the file - resulting in a failure.
it's better to use:
with open(xxx, "w") as f:
f.write()
which will ensure that the file is closed when you're done.

this decryption code use already-given encrypted private key to decrypt the AES (session) key. an error occurred

code looks something like this:
from Crypto.Cipher import AES
import os
import base64
def decryption(encryptedString):
PADDING ='{'
DecodeAES=lambda c, e:c.decrypt(base64.b64decode(e)).rstrip(PADDING)
a = open('private_key0.pem','rb')
key = a.read()
print(key)
cipher = AES.new(key)
decoded = DecodeAES(cipher,encryptedString)
print (decoded)
a.close()
s = open('session_key0.eaes','rb')
cipher_text = s.read()
print(cipher_text)
s.close()
decryption(cipher_text)
error is in line cipher = AES.new(key) and decryption(cipher_text) saying missing mode.Do i need to encrypt the already excrypted files or what?

Chrome NET::err_cert_common_name_invalid error while creating my own certificate using Python's cryptography module

I am creating a certificate signed by own self-signed root authority. This is used to serve a domain hosted as a local app, which is mapped to a localhost address by /etc/hosts file. When the website is requested inside the browser my local app (written in flask) serves the app content while supplying the self-signed certificates I created for the domain. I have code written in Python's Cryptography module, and it follows these basic steps:
a) create a self-signed root authority with its own .CRT and .KEY
b) generate a CSR corresponding to my domain name after generating a separate private key for it
c) have my certificate authority sign the CSR and generate the certificate.
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.serialization import load_der_private_key
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
import datetime
import uuid
import os
import sys
import subprocess
def generate_root_CA():
"""
a) generate rootCA key
b) generate rootCA crt
"""
##generating root key
root_private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
##self-sign and generate the root certificate
root_public_key = root_private_key.public_key()
builder = x509.CertificateBuilder()
builder = builder.subject_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'Test CA'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org'),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Testing unit'),
]))
builder = builder.issuer_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'Test CA'),
]))
builder = builder.not_valid_before(datetime.datetime.today() - datetime.timedelta(days=1))
builder = builder.not_valid_after(datetime.datetime(2019, 12, 31))
builder = builder.serial_number(int(uuid.uuid4()))
builder = builder.public_key(root_public_key)
builder = builder.add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=True,)
root_certificate = builder.sign(
private_key=root_private_key, algorithm=hashes.SHA256(),
backend=default_backend()
)
##write to disk
with open("rootCA.key", "wb") as f:
f.write(root_private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase")
))
with open("rootCA.crt", "wb") as f:
f.write(root_certificate.public_bytes(
encoding=serialization.Encoding.PEM,
))
return root_private_key, root_certificate
def generate_key():
"""
a) generate key for the certificate being created
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
return key
def generate_csr(key, domain_name):
"""
generate csr for the client certificate
"""
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
# Provide various details about who we are.
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"MA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Boston"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Org"),
x509.NameAttribute(NameOID.COMMON_NAME, domain_name),
])).add_extension(
x509.SubjectAlternativeName([
x509.DNSName(domain_name),
x509.DNSName(u"www." + domain_name),
]),
critical=False,
# Sign the CSR with our private key.
).sign(key, hashes.SHA256(), default_backend())
# Write our CSR out to disk.
with open(domain_name + ".csr", "wb") as f:
f.write(csr.public_bytes(serialization.Encoding.PEM))
return csr
def sign_certificate_request(csr, rootkey, rootcrt, client_key, domain_name):
"""
generate the certificate based on the csr created
"""
crt = x509.CertificateBuilder().subject_name(
csr.subject
).issuer_name(
rootcrt.subject
).public_key(
csr.public_key()
).serial_number(
uuid.uuid4().int # pylint: disable=no-member
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=2)
).add_extension(
extension=x509.KeyUsage(
digital_signature=True, key_encipherment=True, content_commitment=True,
data_encipherment=False, key_agreement=False, encipher_only=False, decipher_only=False, key_cert_sign=False, crl_sign=False
),
critical=True
).add_extension(
extension=x509.BasicConstraints(ca=False, path_length=None),
critical=True
).add_extension(
extension=x509.AuthorityKeyIdentifier.from_issuer_public_key(rootkey.public_key()),
critical=False
).sign(
private_key=rootkey,
algorithm=hashes.SHA256(),
backend=default_backend()
)
with open(domain_name + ".crt", 'wb') as f:
f.write(crt.public_bytes(encoding=serialization.Encoding.PEM))
def main():
domain_name = "domain.org"
root_key, root_crt = generate_root_CA()
domain_key = generate_key()
csr = generate_csr(domain_key, domain_name)
sign_certificate_request(csr, root_key, root_crt, domain_key, domain_name)
if __name__ == "__main__":
main()
In Chrome, however I am getting the 'ERR: CERT_COMMON_NAME_INVALID' error. Reading up online, it seems that for this to go away, one needs to specify ones domain name within the Subject Alternative Field inside the CSR request, and it has to match the Common Name. That, however, is being already done inside the code (as can be seen in the generate_csr function). Additionally, I've imported the root certificate inside Chrome's root store. Could anyone help what could be the error over here?
Extensions in the CSR are not automatically copied into the certificate. You'll need to explicitly call add_extension with the SubjectAlternativeName object again in sign_certificate_request.

SMIME.smime_load_pkcs7 (_bio): M2Crypto.SMIME.SMIME_Error: no content type

I have problems loading a pkcs#7 file and ask your help to figure out what I'm doing wrong.
I run M2Crypto-0.21.1 with OpenSSL 0.9.8g (as present in Ubuntu 9.4) and built with SWIG 1.3.36 and python 2.6.2.
"python setup.py test --test-suite=tests.test_smime" runs 15 tests with exit status "OK"; so the installation seems to be ok.
I created a pkcs#7 file in PEM format with a digital signature program and tested it with OpenSSL from the command line:
openssl smime -verify -inform PEM -in mandato-PEM.p7m -noverify
which prints the content contained in the envelope (a text file that I signed) and "Verification successful". So OpenSSL (same version as used by M2Crypto) seems to like my file.
However, when I try the same in M2Crypto, it chocks right in the beginning on:
p7, data = SMIME.smime_load_pkcs7('mandato-PEM.p7m')
I get the following exception:
Traceback (most recent call last):
File "./sign.py", line 110, in <module>
p7, data = SMIME.smime_load_pkcs7('mandato-PEM.p7m')
File "/usr/local/lib/python2.6/dist-packages/M2Crypto-0.21.1-py2.6-linux-i686.egg/M2Crypto/SMIME.py", line 91, in smime_load_pkcs7
p7_ptr, bio_ptr = m2.smime_read_pkcs7(bio)
M2Crypto.SMIME.SMIME_Error: no content type
While I have found information of a problem in Ubuntu (https://lists.ubuntu.com/archives/ubuntu-server-bugs/2010-July/038683.html), it seems to me that this cannot apply here since I built the latest M2Crypto manually and the test suite works fine.
Any help in resolving my problem would be highly appreciated!
many thanks
-bud
After a lot of sweat, here the solution for others who run into the same issue.
I was following the recipe http://code.activestate.com/recipes/285211/ and found many discussions on the web that just "verify(p7)" [method of SMIME] wasn't correct and "verify(p7, data)" was the right thing to do.
This applies only to SMIME documents where the signature is detached. My pkcs#7 file, and all other Italian digitally signed documents, are pkcs#7 envelopes that contain both the signature and the file content (in DER format).
Enveloped p7m files have to be verified as follows:
s=SMIME.SMIME()
st = X509.X509_Store()
st.load_info(trustedCAsPEMfileName)
s.set_x509_store(st)
p7bio = BIO.MemoryBuffer(p7strPEM)
p7 = SMIME.load_pkcs7_bio(p7bio)
certStack = p7.get0_signers(X509.X509_Stack())
s.set_x509_stack(certStack)
try:
docContent = s.verify(p7)
except SMIME.PKCS7_Error, e:
print "An exception occurred!!!!"
print e
To test that this works, I edited the p7m file such that the signature doesn't verify anymore and it correctly prints out "digest failure".
You can also verify a .p7m file (attached DER format) directly but you need to load PKCS #7 object from DER format by m2 direct call to OpenSSL (m2.pkcs7_read_bio_der(input_bio._ptr())) because there is no function for this inside M2Crypto SMIME module. For a proposed patch see Small patch to SMIME.py.
Here a sample code:
import logging
from M2Crypto import SMIME, X509, m2, BIO
certstore_path = "/etc/ssl/certs/ca-certificates.crt"
file_descriptor = open('test_file.p7m', 'rb')
input_bio = BIO.File(file_descriptor)
signer = SMIME.SMIME()
cert_store = X509.X509_Store()
cert_store.load_info(certstore_path)
signer.set_x509_store(cert_store)
try:
p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(input_bio._ptr()), 1)
except SMIME.SMIME_Error, e:
logging.error('load pkcs7 error: ' + str(e))
sk3 = p7.get0_signers(X509.X509_Stack())
signer.set_x509_stack(sk3)
data_bio = None
try:
v = signer.verify(p7, data_bio)
except SMIME.SMIME_Error, e:
logging.error('smime error: ' + str(e))
except SMIME.PKCS7_Error, e:
logging.error('pkcs7 error: ' + str(e))
Code Source: pysmime core
If you only want to extract the original file from the .p7m one (without verifying it), you need to install M2Crypto with pip install M2Crypto (you must probably run sudo apt-get install libssl-dev before) and then run this Python code:
from M2Crypto import BIO, SMIME, X509
# Load file in memory just to showcase BIO usage
with open('file.p7m', 'rb') as file:
p7m = file.read()
smime = SMIME.SMIME()
smime.set_x509_store(X509.X509_Store())
smime.set_x509_stack(X509.X509_Stack())
original_file_content = smime.verify(
SMIME.load_pkcs7_bio_der(BIO.MemoryBuffer(p7m)),
flags=SMIME.PKCS7_NOVERIFY
)
You can use SMIME.load_pkcs7, SMIME.load_pkcs7_bio, SMIME.load_pkcs7_der instead of SMIME.load_pkcs7_bio_der according to your use case: in-memory (_bio) or on file system .p7m file, and PEM or DER (_der) format.
The best reference I found to sign and unsign is the M2Crypto tests here:
http://svn.osafoundation.org/m2crypto/trunk/tests/test_smime.py
def test_sign(self):
buf = BIO.MemoryBuffer(self.cleartext)
s = SMIME.SMIME()
s.load_key('tests/signer_key.pem', 'tests/signer.pem')
p7 = s.sign(buf, SMIME.PKCS7_DETACHED)
assert len(buf) == 0
assert p7.type() == SMIME.PKCS7_SIGNED, p7.type()
assert isinstance(p7, SMIME.PKCS7), p7
out = BIO.MemoryBuffer()
p7.write(out)
buf = out.read()
assert buf[:len('-----BEGIN PKCS7-----')] == '-----BEGIN PKCS7-----'
buf = buf.strip()
assert buf[-len('-----END PKCS7-----'):] == '-----END PKCS7-----', buf[-len('-----END PKCS7-----'):]
assert len(buf) > len('-----END PKCS7-----') + len('-----BEGIN PKCS7-----')
s.write(out, p7, BIO.MemoryBuffer(self.cleartext))
return out
def test_verify(self):
s = SMIME.SMIME()
x509 = X509.load_cert('tests/signer.pem')
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
st = X509.X509_Store()
st.load_info('tests/ca.pem')
s.set_x509_store(st)
p7, data = SMIME.smime_load_pkcs7_bio(self.signed)
assert isinstance(p7, SMIME.PKCS7), p7
v = s.verify(p7, data)
assert v == self.cleartext
t = p7.get0_signers(sk)
assert len(t) == 1
assert t[0].as_pem() == x509.as_pem(), t[0].as_text()
Be carefull with the documentation (http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html) because it is not updated.
See this patch:
https://bugzilla.osafoundation.org/show_bug.cgi?id=13020

Resources