def test_load_bio(self): bio = BIO.openfile('tests/x509.pem') bio2 = BIO.openfile('tests/x509.der') x509 = X509.load_cert_bio(bio) x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER) assert x509.as_text() == x5092.as_text() assert x509.as_pem() == x5092.as_pem() assert x509.as_der() == x5092.as_der() return
def x509_parse_cert(cert, binary=False): "Create a X509 certificate from binary DER, plain text PEM or filename" if binary: bio = BIO.MemoryBuffer(cert) x509 = X509.load_cert_bio(bio, X509.FORMAT_DER) elif cert.startswith("-----BEGIN CERTIFICATE-----"): bio = BIO.MemoryBuffer(cert) x509 = X509.load_cert_bio(bio, X509.FORMAT_PEM) else: x509 = X509.load_cert(cert, 1) return x509
def read(self, proxypath=None): """ reads in a proxy certificate information """ if proxypath is None: proxypath = get_proxy_filename() proxyfile = open(proxypath) bio = BIO.File(proxyfile) self._cert = X509.load_cert_bio(bio) self._key = RSA.load_key_bio(bio) self._issuer = X509.load_cert_bio(bio)
def test_load_bio(self): with BIO.openfile('tests/x509.pem') as bio: with BIO.openfile('tests/x509.der') as bio2: x509 = X509.load_cert_bio(bio) x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER) with self.assertRaises(ValueError): X509.load_cert_bio(bio2, format=45678) self.assertEqual(x509.as_text(), x5092.as_text()) self.assertEqual(x509.as_pem(), x5092.as_pem()) self.assertEqual(x509.as_der(), x5092.as_der())
def test_load_bio(self): bio = BIO.openfile('tests/x509.pem') bio2 = BIO.openfile('tests/x509.der') x509 = X509.load_cert_bio(bio) x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER) self.assertRaises(ValueError, X509.load_cert_bio, bio2, format=45678) assert x509.as_text() == x5092.as_text() assert x509.as_pem() == x5092.as_pem() assert x509.as_der() == x5092.as_der() return
def AnalizarCertificado(self, crt, binary=False): "Carga un certificado digital y extrae los campos más importantes" from M2Crypto import BIO, EVP, RSA, X509 if binary: bio = BIO.MemoryBuffer(cert) x509 = X509.load_cert_bio(bio, X509.FORMAT_DER) elif crt.startswith("-----BEGIN CERTIFICATE-----"): bio = BIO.MemoryBuffer(crt) x509 = X509.load_cert_bio(bio, X509.FORMAT_PEM) else: x509 = X509.load_cert(crt, 1) if x509: self.Identidad = x509.get_subject().as_text() self.Caducidad = x509.get_not_after().get_datetime() self.Emisor = x509.get_issuer().as_text() return True
def verify_mdm_signature(mdm_sig, req_data): '''Verify the client's supplied MDM signature and return the client certificate included in the signature.''' pkcs7_pem_sig = base64_to_pem('PKCS7', mdm_sig) p7_bio = BIO.MemoryBuffer(str(pkcs7_pem_sig)) p7 = SMIME.load_pkcs7_bio(p7_bio) p7_signers = p7.get0_signers(X509.X509_Stack()) mdm_ca = get_ca() # can probably directly use m2 certificate here ca_x509_bio = BIO.MemoryBuffer(mdm_ca.get_cacert().get_pem()) ca_x509 = X509.load_cert_bio(ca_x509_bio) cert_store = X509.X509_Store() cert_store.add_x509(ca_x509) signer = SMIME.SMIME() signer.set_x509_store(cert_store) signer.set_x509_stack(p7_signers) # NOTE: may need to do something special if we can't cleanly convert # to string from Unicode. must be byte-accurate as the signature won't # match otherwise data_bio = BIO.MemoryBuffer(req_data) # will raise an exception if verification fails # if no CA certificate we get an: # PKCS7_Error: certificate verify error signer.verify(p7, data_bio) return p7_signers[0].as_pem()
def _encrypt(self): """Use your key thing to encrypt things.""" from M2Crypto import BIO, SMIME, X509 # Iterate through the fields and pull out the ones that have a value. plaintext = 'cert_id=%s\n' % self.cert_id for name, field in self.fields.items(): value = None if name in self.initial: value = self.initial[name] elif field.initial is not None: value = field.initial if value is not None: # @@@ Make this less hackish and put it in the widget. if name == "return_url": name = "return" plaintext += u'%s=%s\n' % (name, value) plaintext = plaintext.encode('utf-8') # Begin crypto weirdness. s = SMIME.SMIME() s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read()
def _encrypt(self): """Use your key thing to encrypt things.""" from M2Crypto import BIO, SMIME, X509 CERT = self.settings.private_cert PUB_CERT = self.settings.public_cert PAYPAL_CERT = self.settings.paypal_cert CERT_ID = self.settings.cert_id # Iterate through the fields and pull out the ones that have a value. plaintext = 'cert_id=%s' % CERT_ID for name, value in self.items.iteritems(): plaintext += '\n%s=%s' % (name, value) #plaintext = plaintext.encode('utf-8') # Begin crypto weirdness. s = SMIME.SMIME() s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read()
def load_chain_from_string(self, data): """ @param data: A single string of concatenated X509 Certificates in PEM format @type data: str """ # Refer to OpenSSL crypto/x509/by_file.c # Function: X509_load_cert_file() to see how they parse a chain file and add # the certificates to a X509_Store. Below follows a similar procedure. from M2Crypto import BIO bio = BIO.MemoryBuffer(data) certs = [] try: while True: # Read one cert at a time, 'bio' stores the last location read # Exception is raised when no more cert data is available cert = X509.load_cert_bio(bio) if not cert: break certs.append(cert) except X509.X509Error, e: # This is the normal return path. # X509.load_cert_bio will throw an exception after reading all of the cert # data return certs
def createSignature(hash, signingCertificatePkcs12, signingCertificatePassword): # see also in AM: src/crypto-lib/signature.cpp / Signature::create() s = SMIME.SMIME() # M2Crypto has no support for PKCS#12, so we have to use pyopenssl here # to load the .p12. Since the internal structures are incompatible, we # have to export from pyopenssl and import to M2Crypto via PEM BIOs. pkcs12 = load_pkcs12(signingCertificatePkcs12, signingCertificatePassword) signKey = BIO.MemoryBuffer(dump_privatekey(FILETYPE_PEM, pkcs12.get_privatekey())) signCert = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, pkcs12.get_certificate())) caCerts = X509.X509_Stack() if pkcs12.get_ca_certificates(): for cert in pkcs12.get_ca_certificates(): bio = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, cert)) caCerts.push(X509.load_cert_bio(bio, X509.FORMAT_PEM)) bioHash = BIO.MemoryBuffer(hash) s.load_key_bio(signKey, signCert) s.set_x509_stack(caCerts) signature = s.sign(bioHash, SMIME.PKCS7_DETACHED + SMIME.PKCS7_BINARY) bioSignature = BIO.MemoryBuffer() signature.write(bioSignature) data = bioSignature.read_all() return data
def get_certs_from_string(self, data, log_func=None): """ @param data: A single string of concatenated X509 Certificates in PEM format @type data: str @param log_func: logging function @type log_func: function accepting a single string @return list of X509 Certificates @rtype: [M2Crypto.X509.X509] """ # Refer to OpenSSL crypto/x509/by_file.c # Function: X509_load_cert_file() to see how they parse a chain file and add # the certificates to a X509_Store. Below follows a similar procedure. bio = BIO.MemoryBuffer(data) certs = [] try: if not M2CRYPTO_HAS_CRL_SUPPORT: # Old versions of M2Crypto behave differently and would loop indefinitely over load_cert_bio return X509.load_cert_string(data) for index in range(0, self.max_num_certs_in_chain): # Read one cert at a time, 'bio' stores the last location read # Exception is raised when no more cert data is available cert = X509.load_cert_bio(bio) if not cert: # This is likely to never occur, a X509Error should always be raised break certs.append(cert) if index == (self.max_num_certs_in_chain - 1) and log_func: log_func("**WARNING** Pulp reached maximum number of <%s> certs supported in a chain." % (self.max_num_certs_in_chain)) except X509.X509Error: # This is the normal return path. return certs return certs
def __init__(self, certificate=None, key=None, callback=no_passphrase_callback): self._key = None if key: if isinstance(key, Key): self._key = key else: self._key = Key(key, callback=callback) if isinstance(certificate, str): if certificate.startswith("-----BEGIN CERTIFICATE-----"): self._certificate = X509.load_cert_string(str(certificate), X509.FORMAT_PEM) elif path.exists(certificate): certfile = open(certificate) bio = BIO.File(certfile) self._certificate = X509.load_cert_bio(bio) else: raise ValueError("WTF") else: self._certificate = X509.X509() if not key: key = Key() self._key = key self.set_pubkey(self._key)
def load_key_bio(self, keybio, certbio=None, callback=util.passphrase_callback): # type: (BIO.BIO, Optional[BIO.BIO], Callable) -> None if certbio is None: certbio = keybio self.pkey = EVP.load_key_bio(keybio, callback) self.x509 = X509.load_cert_bio(certbio)
def AnalizarCertificado(self, crt, binary=False): "Carga un certificado digital y extrae los campos más importantes" from M2Crypto import BIO, EVP, RSA, X509 if binary: bio = BIO.MemoryBuffer(cert) x509 = X509.load_cert_bio(bio, X509.FORMAT_DER) else: if not crt.startswith("-----BEGIN CERTIFICATE-----"): crt = open(crt).read() bio = BIO.MemoryBuffer(crt) x509 = X509.load_cert_bio(bio, X509.FORMAT_PEM) if x509: self.Identidad = x509.get_subject().as_text() self.Caducidad = x509.get_not_after().get_datetime() self.Emisor = x509.get_issuer().as_text() self.CertX509 = x509.as_text() return True
def load_key_bio(self, keybio, certbio=None, callback=util.passphrase_callback): if certbio is None: certbio = keybio self.pkey = EVP.load_key_bio(keybio, callback) self.x509 = X509.load_cert_bio(certbio)
def load_certs(self, bio, certs=None): if not certs: certs = [] try: cert = X509.load_cert_bio(bio) certs.append(cert) return self.load_certs(bio, certs) except X509.X509Error, e: return certs
def _get_x509_list(cert): x509_list = [] fd = BIO.openfile(cert, 'rb') cert = X509.load_cert_bio(fd) try: while True: x509_list.append(cert) log.debug("Loaded " + cert.get_subject().as_text()) cert = X509.load_cert_bio(fd) except X509.X509Error: # When there are no more certs, this is what we get, so it is fine pass except BIO.BIOError: # When there are no more certs, this is what we get, so it is fine # Python 2.4 pass del fd return x509_list
def _getChainM2Crypto(self, chain): from M2Crypto import X509, BIO cacert = None vdsmchain = '' bio = None try: bio = BIO.MemoryBuffer('\n'.join(chain).encode('utf-8')) try: cacert = X509.load_cert_bio( bio=bio, format=X509.FORMAT_PEM ).as_pem() except X509.X509Error: self.logger.debug( 'read vdsm certificate chain', exc_info=True ) raise RuntimeError(_('CA Certificate was not provided')) try: while True: vdsmchain += X509.load_cert_bio( bio=bio, format=X509.FORMAT_PEM ).as_pem() except X509.X509Error: if not vdsmchain: self.logger.debug( 'read vdsm certificate chain', exc_info=True ) raise RuntimeError( _('VDM Certificate was not provided') ) return (cacert, vdsmchain) finally: if bio is not None: bio.close()
def unpack_certificate(certificatePem): """ Unpack X509 PEM-encoded certificate. :param certificatePem: PEM encoded X509 certificate. :type certificatePem: str :returns dict -- Detailed information from the certificate. """ cert = X509.load_cert_bio(BIO.MemoryBuffer(certificatePem)) cert_pkey_fingerprint = key_fingerprint(cert.get_pubkey()) res = {} ## we include the reserialized PEM encoding (which in principle ## should be identical to certificatePem .. but who knows .. this ## is x509 crap) res["pem"] = cert.as_pem() res["text"] = cert.as_text() res["fingerprint"] = cert_fingerprint(cert) ## we convert this to dotted hex, since the version ## might be a unsigned long (8 bytes) which i.e. JavaScript ## can't consume serial = "0x%x" % cert.get_serial_number() res["serial"] = dotted(serial[2:]) res["version"] = cert.get_version() res["issuer"] = info_from_x509name(cert.get_issuer()) res["subject"] = info_from_x509name(cert.get_subject()) now = datetime.datetime.utcnow() ## we need to strip of timezone info, since we cannot compare ## datetime with/without tzinfo, and Python utcnow() for strange ## reasons does not contain tzinfo. The date returned from cert ## should be UTC anyway. before = cert.get_not_before().get_datetime() before = before.replace(tzinfo = None) after = cert.get_not_after().get_datetime() after = after.replace(tzinfo = None) UTC_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ" res["not-valid-before"] = before.strftime(UTC_TIMESTAMP_FORMAT) res["not-valid-after"] = after.strftime(UTC_TIMESTAMP_FORMAT) res["valid-now"] = before <= now and now <= after pubkey = cert.get_pubkey() res["public-key"] = {"length": pubkey.size() * 8, "fingerprint": key_fingerprint(pubkey)} res["is-selfsigned"] = True if cert.verify(pubkey) == 1 else False return res
def form_encrypted(self, data): """Return an s/mime encrypted form. Refer to http://sandbox.rulemaker.net/ngps/m2/howto.smime.html for instructions.""" from M2Crypto import BIO, SMIME, X509 certid = self.settings["PUBLIC_CERT_ID"] ret = ['CERT_ID=%s' % certid] ret.extend([u'%s=%s' % (key, val) for key, val in data.items() if val]) raw = "\n".join(ret) raw = raw.encode('utf-8') self.log_extra('Plaintext form: %s', raw) # encrypt the plaintext # make an smime object s = SMIME.SMIME() # load our public and private keys s.load_key_bio(BIO.openfile(self.localprikey), BIO.openfile(self.localpubkey)) # put the data in the buffer buf = BIO.MemoryBuffer(raw) # sign the text p7 = s.sign(buf, flags=SMIME.PKCS7_BINARY) # Load target cert to encrypt to. x509 = X509.load_cert_bio(BIO.openfile(self.paypalpubkey)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # save data to buffer tmp = BIO.MemoryBuffer() p7.write_der(tmp) # encrypt p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() # write into a new buffer p7.write(out) # read the result form = out.read() self.log_extra('Encrypted form: %s', form) return mark_safe( u"""<input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="encrypted" value="%s" /> """ % form)
def _readX509List(self, pemString): x509List = [] bio = BIO.MemoryBuffer(pemString) try: while True: cert = X509.load_cert_bio(bio) x509List.append(cert) except X509.X509Error: pass return x509List
def form_encrypted(self, data): """Return an s/mime encrypted form. Refer to http://sandbox.rulemaker.net/ngps/m2/howto.smime.html for instructions.""" from M2Crypto import BIO, SMIME, X509 certid = self.settings["PUBLIC_CERT_ID"] ret = ['CERT_ID=%s' % certid] ret.extend([u'%s=%s' % (key, val) for key, val in data.items() if val]) raw = "\n".join(ret) raw = raw.encode('utf-8') self.log_extra('Plaintext form: %s', raw) # encrypt the plaintext # make an smime object s = SMIME.SMIME() # load our public and private keys s.load_key_bio(BIO.openfile(self.localprikey), BIO.openfile(self.localpubkey)) # put the data in the buffer buf = BIO.MemoryBuffer(raw) # sign the text p7 = s.sign(buf, flags=SMIME.PKCS7_BINARY) # Load target cert to encrypt to. x509 = X509.load_cert_bio(BIO.openfile(self.paypalpubkey)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # save data to buffer tmp = BIO.MemoryBuffer() p7.write_der(tmp) # encrypt p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() # write into a new buffer p7.write(out) # read the result form = out.read() self.log_extra('Encrypted form: %s', form) return mark_safe(u"""<input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="encrypted" value="%s" /> """ % form)
def _read_X509_list(x509_pem): """ Loads the list of certificates contained in x509_pem """ x509_list = [] bio = BIO.MemoryBuffer(x509_pem) try: while bio.readable(): cert = X509.load_cert_bio(bio) x509_list.append(cert) except X509.X509Error: pass return x509_list
def _read_x509_list(x509_pem): """ Loads the list of certificates contained in x509_pem """ x509_list = [] bio = BIO.MemoryBuffer(x509_pem) try: while bio.readable(): cert = X509.load_cert_bio(bio) x509_list.append(cert) except X509.X509Error: pass return x509_list
def get_usercert(certfile=None): """ function that returns a X509 instance which is the user cert that is expected to be a ~/.globus/usercert.pem A check is performed to ensure the certificate has valid before and after times. """ if certfile is None: certfile = open(os.path.join(os.getenv("HOME"), ".globus", "usercert.pem")) else: certfile = open(certfile) bio = BIO.File(certfile) cert = X509.load_cert_bio(bio) return cert
def read(self, keyfile, certfile, passphrase=None): """ Reads key and cert, from files keyfile -- file where key is stored. Must be PEM encoded. certfile -- file where certificate is stored. Must be PEM encoded. Raises: CrendentialError -- if files can't be read, or keyfile not owned by running process """ if keyfile: st = os.stat(keyfile) dir(st) user_id = os.geteuid() if st.st_uid != user_id: raise CredentialError("Keyfile error", "Keyfile '%s' not owned by user runnig process ('%d')" % \ (keyfile, user_id)) try: key_bio = BIO.File(open(keyfile,'r')) if not passphrase: self._key = RSA.load_key_bio(key_bio, self.passwd_callback) else: self._key = RSA.load_key_bio(key_bio, lambda *args, **kw: passphrase) key_bio.close() cert_bio = BIO.File(open(certfile,'r')) self._cert = X509.load_cert_bio(cert_bio) while True: crt = X509.load_cert_bio(cert_bio) if crt.verify() == 0: # XXX look for a more elegant way break self._cert_chain.append(crt) cert_bio.close() except Exception, err: raise CredentialError("Failed read", err.__str__())
def render(self, md): # Render the dtml block. data = render_blocks(self.section.blocks, md) data_bio = BIO.MemoryBuffer(data) # Prepare to S/MIME. s = SMIME.SMIME() # Render the signer key, load into BIO. try: signer = Var(self.signer).render(md) except ParseError: raise SmimeError, ('Invalid parameter "signer".') signer_key_bio = BIO.MemoryBuffer(signer) signer_cert_bio = BIO.MemoryBuffer(signer) # XXX Kludge. # Sign the data. s.load_key_bio(signer_key_bio, signer_cert_bio) p7 = s.sign(data_bio, flags=SMIME.PKCS7_TEXT) # Recreate coz sign() has consumed the MemoryBuffer. # May be cheaper to seek to start. data_bio = BIO.MemoryBuffer(data) # Render recipients, load into BIO. try: recip = Var(self.recipients).render(md) except ParseError: raise SmimeError, ('Invalid parameter "recipients".') recip_bio = BIO.MemoryBuffer(recip) # Load recipient certificates. sk = X509.X509_Stack() sk.push(X509.load_cert_bio(recip_bio)) s.set_x509_stack(sk) # Set a cipher. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt. tmp_bio = BIO.MemoryBuffer() s.write(tmp_bio, p7) p7 = s.encrypt(tmp_bio) # Finally, return the now signed/encrypted PKCS7. out = BIO.MemoryBuffer() s.write(out, p7) return out.getvalue()
def get_usercert(certfile=None): """ function that returns a X509 instance which is the user cert that is expected to be a ~/.globus/usercert.pem A check is performed to ensure the certificate has valid before and after times. """ if certfile is None: certfile = open( os.path.join(os.getenv("HOME"), ".globus", "usercert.pem")) else: certfile = open(certfile) bio = BIO.File(certfile) cert = X509.load_cert_bio(bio) return cert
def sign(self, data, wwdrcert_data, cert_data, key_data, passphrase = None): """ https://github.com/devartis/passbook """ def passwordCallback(*args, **kwds): return passphrase wwdrcert_bio = SMIME.BIO.MemoryBuffer(wwdrcert_data) key_bio = SMIME.BIO.MemoryBuffer(key_data) cert_bio = SMIME.BIO.MemoryBuffer(cert_data) smime = SMIME.SMIME() wwdrcert = X509.load_cert_bio(wwdrcert_bio) stack = X509_Stack() stack.push(wwdrcert) smime.set_x509_stack(stack) smime.load_key_bio(key_bio, cert_bio, callback=passwordCallback) pk7 = smime.sign(SMIME.BIO.MemoryBuffer(data), flags = SMIME.PKCS7_DETACHED | SMIME.PKCS7_BINARY) pem = SMIME.BIO.MemoryBuffer() pk7.write(pem) der = ''.join(l.strip() for l in pem.read().split('----')[2].splitlines()).decode('base64') return der
def _encrypt(self): """Use your key thing to encrypt things.""" from M2Crypto import BIO, SMIME, X509 # @@@ Could we move this to conf.py? CERT = settings.PAYPAL_PRIVATE_CERT PUB_CERT = settings.PAYPAL_PUBLIC_CERT PAYPAL_CERT = settings.PAYPAL_CERT CERT_ID = self.cert_id # Iterate through the fields and pull out the ones that have a value. plaintext = 'cert_id=%s\n' % CERT_ID for name, field in self.fields.items(): value = None if name in self.initial: value = self.initial[name] elif field.initial is not None: value = field.initial if value is not None: # @@@ Make this less hackish and put it in the widget. if name == "return_url": name = "return" plaintext += u'%s=%s\n' % (name, value) plaintext = plaintext.encode('utf-8') with BIO.openfile(CERT) as cert_f, \ BIO.openfile(PUB_CERT) as pub_cert_f, \ BIO.openfile(settings.PAYPAL_CERT) as pp_cert_f: # Begin crypto weirdness. s = SMIME.SMIME() s.load_key_bio(cert_f, pub_cert_f) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(pp_cert_f) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read()
def verifySignature(signaturePkcs7, hash, chainOfTrust): # see also in AM: src/crypto-lib/signature.cpp / Signature::verify() s = SMIME.SMIME() bioSignature = BIO.MemoryBuffer(data = base64.decodestring(signaturePkcs7)) signature = SMIME.load_pkcs7_bio(bioSignature) bioHash = BIO.MemoryBuffer(data = hash) certChain = X509.X509_Store() for trustedCert in chainOfTrust: bioCert = BIO.MemoryBuffer(data = trustedCert) while len(bioCert): cert = X509.load_cert_bio(bioCert, X509.FORMAT_PEM) certChain.add_x509(cert) s.set_x509_store(certChain) s.set_x509_stack(X509.X509_Stack()) s.verify(signature, bioHash, SMIME.PKCS7_NOCHAIN)
def verifySignature(signaturePkcs7, hash, chainOfTrust): # see also in AM: src/crypto-lib/signature.cpp / Signature::verify() s = SMIME.SMIME() bioSignature = BIO.MemoryBuffer(data=base64.decodestring(signaturePkcs7)) signature = SMIME.load_pkcs7_bio(bioSignature) bioHash = BIO.MemoryBuffer(data=hash) certChain = X509.X509_Store() for trustedCert in chainOfTrust: bioCert = BIO.MemoryBuffer(data=trustedCert) while len(bioCert): cert = X509.load_cert_bio(bioCert, X509.FORMAT_PEM) certChain.add_x509(cert) s.set_x509_store(certChain) s.set_x509_stack(X509.X509_Stack()) s.verify(signature, bioHash, SMIME.PKCS7_NOCHAIN)
def _encrypt_data(self, data): """ Encrypt the form data. Refer to http://sandbox.rulemaker.net/ngps/m2/howto.smime.html """ # Don't import at top because these are only required if user wants encryption from M2Crypto import BIO, SMIME, X509 certid = self.settings["PUBLIC_CERT_ID"] # Assemble form data and encode in utf-8 raw = ["cert_id=%s" % certid] raw.extend([u"%s=%s" % (key, val) for key, val in data.items() if val]) raw = "\n".join(raw) raw = raw.encode("utf-8") self.log.debug('Encrypted Paypal data: %s' % raw) # make an smime object s = SMIME.SMIME() # load our public and private keys s.load_key_bio(BIO.openfile(self.localprikey), BIO.openfile(self.localpubkey)) # put the data in the buffer buf = BIO.MemoryBuffer(raw) # sign the text p7 = s.sign(buf, flags=SMIME.PKCS7_BINARY) # Load target cert to encrypt to. x509 = X509.load_cert_bio(BIO.openfile(self.paypalpubkey)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher("des_ede3_cbc")) # save data to buffer tmp = BIO.MemoryBuffer() p7.write_der(tmp) # encrypt p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() # write into a new buffer p7.write(out) return out.read()
def _encrypt(self): """Use your key thing to encrypt things.""" from M2Crypto import BIO, SMIME, X509 # ### ToDo: Could we move this to conf.py? CERT = settings.PAYPAL_PRIVATE_CERT PUB_CERT = settings.PAYPAL_PUBLIC_CERT PAYPAL_CERT = settings.PAYPAL_CERT CERT_ID = settings.PAYPAL_CERT_ID # Iterate through the fields and pull out the ones that have a value. plaintext = "cert_id=%s\n" % CERT_ID for name, field in self.fields.iteritems(): value = None if name in self.initial: value = self.initial[name] elif field.initial is not None: value = field.initial if value is not None: # ### Todo - make this less hackish and put it in the widget. if name == "return_url": name = "return" plaintext += u"%s=%s\n" % (name, value) plaintext = plaintext.encode("utf-8") # Begin crypto weirdness. s = SMIME.SMIME() s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher("des_ede3_cbc")) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read()
def encrypt(self, attributes): plaintext = '' for key, value in attributes.items(): plaintext += u'%s=%s\n' % (key, value) plaintext = plaintext.encode('utf-8') # Instantiate an SMIME object. s = SMIME.SMIME() # Load signer's key and cert. Sign the buffer. s.load_key_bio(BIO.openfile(PAYPAL_PRIVATE_KEY), BIO.openfile(PAYPAL_PUBLIC_KEY)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) # Load target cert to encrypt the signed message to. x509 = X509.load_cert_bio(BIO.openfile(PAYPAL_PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Create a temporary buffer. tmp = BIO.MemoryBuffer() # Write the signed message into the temporary buffer. p7.write_der(tmp) # Encrypt the temporary buffer. p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() p7.write(out) return out.read()
def encrypt(self, config): key = os.path.join(os.environ.get('MONIMI_HOME', '.'), config.get('paypal', 'key')) cert = os.path.join(os.environ.get('MONIMI_HOME', '.'), config.get('paypal', 'cert')) paypal_cert = os.path.join(os.environ.get('MONIMI_HOME', '.'), config.get('paypal', 'paypal_cert')) self['cert_id'] = config.get('paypal', 'cert_id') # Instantiate an SMIME object. s = SMIME.SMIME() # Load signer's key and cert. Sign the buffer. s.load_key_bio(BIO.openfile(key), BIO.openfile(cert)) p7 = s.sign(BIO.MemoryBuffer(self.plaintext()), flags=SMIME.PKCS7_BINARY) # Load target cert to encrypt the signed message to. x509 = X509.load_cert_bio(BIO.openfile(paypal_cert)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Create a temporary buffer. tmp = BIO.MemoryBuffer() # Write the signed message into the temporary buffer. p7.write_der(tmp) # Encrypt the temporary buffer. p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() p7.write(out) return out.read()
def _encrypt(self): """Use your key thing to encrypt things.""" warn_untested() from M2Crypto import BIO, SMIME, X509 # Iterate through the fields and pull out the ones that have a value. plaintext = 'cert_id=%s\n' % self.cert_id for name, field in self.fields.items(): value = None if name in self.initial: value = self.initial[name] elif field.initial is not None: value = field.initial if value is not None: # @@@ Make this less hackish and put it in the widget. if name == "return_url": name = "return" plaintext += u'%s=%s\n' % (name, value) plaintext = plaintext.encode('utf-8') # Begin crypto weirdness. s = SMIME.SMIME() s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read()
x.info("Got SIGTERM, closing server") self.close() def handle_accept(self): pair = self.accept() if pair is None: pass else: sock, addr = pair logging.getLogger("logger").info('Incoming connection from {0}'.format(repr(addr))) handler = HandleConnection(sock) # load the certificates caCertFile = open('OrigAppleSubCACert.der') caCert = X509.load_cert_bio(BIO.MemoryBuffer(caCertFile.read()), format=0) caCertFile.close() certFile = open('OrigAppleServerCert.der') serverCert = X509.load_cert_bio(BIO.MemoryBuffer(certFile.read()), format=0) certFile.close() #setup logging log_levels = {'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'critical':logging.CRITICAL }
self.close() def handle_accept(self): pair = self.accept() if pair is None: pass else: sock, addr = pair logging.getLogger("logger").info( 'Incoming connection from {0}'.format(repr(addr))) handler = HandleConnection(sock, self.lang) # load the certificates caCertFile = open('OrigAppleSubCACert.der') caCert = X509.load_cert_bio(BIO.MemoryBuffer(caCertFile.read()), format=0) caCertFile.close() certFile = open('OrigAppleServerCert.der') serverCert = X509.load_cert_bio(BIO.MemoryBuffer(certFile.read()), format=0) certFile.close() #setup logging log_levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL }
def load_cert_obj(self, certname): """Load cert as X509 object""" bio = self.load_cert_bio(certname) return X509.load_cert_bio(bio)
def verify_cms(self, data): """Verify a pkcs7 SMIME message""" from M2Crypto import SMIME, X509, BIO import base64, TLV_utils, os data3 = "-----BEGIN PKCS7-----\n" data3 += base64.encodestring(data) data3 += "-----END PKCS7-----" #print data3 p7_bio = BIO.MemoryBuffer(data3) # Instantiate an SMIME object. s = SMIME.SMIME() # TODO: ugly hack for M2Crypto body = TLV_utils.tlv_find_tag(TLV_utils.unpack(data), 0xA0, 1)[0][2] thecert = TLV_utils.tlv_find_tag(body, 0xA0, 2)[1][2] cert_bio = BIO.MemoryBuffer(TLV_utils.pack(thecert)) # Load the signer's cert. x509 = X509.load_cert_bio(cert_bio, format=0) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) country = str(x509.get_issuer()).split('/')[1][2:] #print country cacert = country + "-cacert.der" #print cacert msgErr = "couldn't parse certificate to determine URL for CACert, search the intertubes," msg = "download CACert (convert to DER if necessary) and save it as \n\"%s\"" % cacert if not os.path.isfile(cacert): try: v = x509.get_ext("certificatePolicies").get_value() start = v.find("CPS: ") if start != -1: url = v[start + 5:-1] print "visit %s" % url, msg else: print msgErr, msg except Exception: print msgErr, msg return "" # Load the signer's CA cert. st = X509.X509_Store() #st.load_info('main') x509CA = X509.load_cert(cacert, format=0) st.add_x509(x509CA) s.set_x509_store(st) # Load the data, verify it. #p7, data = SMIME.smime_load_pkcs7_bio(p7_bio) p7 = SMIME.load_pkcs7_bio(p7_bio) v = s.verify(p7) return v