本文整理汇总了Python中M2Crypto.BIO.MemoryBuffer方法的典型用法代码示例。如果您正苦于以下问题:Python BIO.MemoryBuffer方法的具体用法?Python BIO.MemoryBuffer怎么用?Python BIO.MemoryBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类M2Crypto.BIO
的用法示例。
在下文中一共展示了BIO.MemoryBuffer方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rsa_verify
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def rsa_verify(xml, signature, key, c14n_exc=True):
"Verify a XML document signature usign RSA-SHA1, return True if valid"
# load the public key (from buffer or filename)
if key.startswith("-----BEGIN PUBLIC KEY-----"):
bio = BIO.MemoryBuffer(key)
rsa = RSA.load_pub_key_bio(bio)
else:
rsa = RSA.load_pub_key(certificate)
# create the digital envelope
pubkey = EVP.PKey()
pubkey.assign_rsa(rsa)
# do the cryptographic validation (using the default sha1 hash digest)
pubkey.reset_context(md='sha1')
pubkey.verify_init()
# normalize and feed the signed xml to be verified
pubkey.verify_update(canonicalize(xml, c14n_exc))
ret = pubkey.verify_final(base64.b64decode(signature))
return ret == 1
示例2: x509_parse_cert
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
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
示例3: cmd_mkcert
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def cmd_mkcert(workingdir,name):
cwd = os.getcwd()
try:
common.ch_dir(workingdir,logger)
priv = read_private()
cacert = X509.load_cert('cacert.crt')
ca_pk = EVP.load_key_string(str(priv[0]['ca']))
cert,pk = ca_impl.mk_signed_cert(cacert,ca_pk,name,priv[0]['lastserial']+1)
with open('%s-cert.crt'%name, 'w') as f:
f.write(cert.as_pem())
f = BIO.MemoryBuffer()
pk.save_key_bio(f,None)
priv[0][name]=f.getvalue()
f.close()
#increment serial number after successful creation
priv[0]['lastserial']+=1
write_private(priv)
# write out the private key with password
with os.fdopen(os.open("%s-private.pem"%name,os.O_WRONLY | os.O_CREAT,0600), 'w') as f:
biofile = BIO.File(f)
pk.save_key_bio(biofile, 'aes_256_cbc', globalcb)
biofile.close()
pk.get_rsa().save_pub_key('%s-public.pem'%name)
cc = X509.load_cert('%s-cert.crt'%name)
if cc.verify(cacert.get_pubkey()):
logger.info("Created certificate for name %s successfully in %s"%(name,workingdir))
else:
logger.errro("ERROR: Cert does not validate against CA")
示例4: _set_public_key_string
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def _set_public_key_string(self, public_key_string):
# add the PKCS#8 header if it doesn't exist
if not public_key_string.startswith(PKCS8_HEADER):
public_key_string = PKCS8_HEADER + public_key_string
# break up the base64 key string into lines of max length 64, to please m2crypto
public_key_string = public_key_string.replace("\n", "")
public_key_string = "\n".join(re.findall(".{1,64}", public_key_string))
# add the appropriate PEM header/footer
public_key_string = self._add_pem_headers(public_key_string, "PUBLIC KEY")
self._public_key = M2RSA.load_pub_key_bio(M2BIO.MemoryBuffer(self.ensure_bytes(public_key_string)))
示例5: load_key
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def load_key(string):
"""load_key(string) -> key
Convert a PEM format public DSA key into
an internal representation."""
return DSA.load_pub_key_bio(BIO.MemoryBuffer(string))
示例6: verify
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def verify(self, text):
"""
verifies a signed SMIME email
returns a list of certificates used to sign
the SMIME message on success
text - string containing the SMIME signed message
>>> v = Verifier('/etc/apache/ssl.crt/ca-bundle.crt')
>>> v.verify('pippo')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "signer.py", line 23, in __init__
raise VerifierError, e
VerifierError: cannot extract payloads from message
>>>
>>> certs = v.verify(test_email)
>>> isinstance(certs, list) and len(certs) > 0
True
>>>
"""
if self._smime is None:
self._setup()
buf = BIO.MemoryBuffer(text)
try:
p7, data_bio = SMIME.smime_load_pkcs7_bio(buf)
except SystemError:
# uncaught exception in M2Crypto
raise VerifierError, "cannot extract payloads from message"
if data_bio is not None:
data = data_bio.read()
data_bio = BIO.MemoryBuffer(data)
sk3 = p7.get0_signers(X509.X509_Stack())
if len(sk3) == 0:
raise VerifierError, "no certificates found in message"
signer_certs = []
for cert in sk3:
signer_certs.append(
"-----BEGIN CERTIFICATE-----\n%s-----END CERTIFICATE-----" \
% base64.encodestring(cert.as_der()))
self._smime.set_x509_stack(sk3)
try:
if data_bio is not None:
v = self._smime.verify(p7, data_bio)
else:
v = self._smime.verify(p7)
except SMIME.SMIME_Error, e:
raise VerifierError, "message verification failed: %s" % e
if data_bio is not None and data != v:
raise VerifierContentError, \
"message verification failed: payload vs SMIME.verify output diff\n%s" % \
'\n'.join(list(unified_diff(data.split('\n'), v.split('\n'), n = 1)))
return signer_certs
示例7: cmd_init
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def cmd_init(workingdir):
cwd = os.getcwd()
try:
common.ch_dir(workingdir,logger)
rmfiles("*.pem")
rmfiles("*.crt")
rmfiles("*.zip")
rmfiles("*.der")
rmfiles("private.json")
cacert, ca_pk, _ = ca_impl.mk_cacert()
priv=read_private()
# write out keys
with open('cacert.crt', 'wb') as f:
f.write(cacert.as_pem())
f = BIO.MemoryBuffer()
ca_pk.save_key_bio(f,None)
priv[0]['ca']=f.getvalue()
f.close()
# store the last serial number created.
# the CA is always serial # 1
priv[0]['lastserial'] = 1
write_private(priv)
ca_pk.get_rsa().save_pub_key('ca-public.pem')
# generate an empty crl
crl = ca_impl.gencrl([],cacert.as_pem(),str(priv[0]['ca']))
with open('cacrl.der','wb') as f:
f.write(crl)
convert_crl_to_pem("cacrl.der","cacrl.pem")
# Sanity checks...
cac = X509.load_cert('cacert.crt')
if cac.verify():
logger.info("CA certificate created successfully in %s"%workingdir)
else:
logger.error("ERROR: Cert does not self validate")
finally:
os.chdir(cwd)
示例8: _get_digital_signers
# 需要导入模块: from M2Crypto import BIO [as 别名]
# 或者: from M2Crypto.BIO import MemoryBuffer [as 别名]
def _get_digital_signers(self):
if not self.pe:
return None
retlist = None
if HAVE_CRYPTO:
address = self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress
#check if file is digitally signed
if address == 0:
return retlist
signature = self.pe.write()[address+8:]
# BIO.MemoryBuffer expects an argument of type 'str'
if type(signature) is bytearray:
signature = str(signature)
bio = BIO.MemoryBuffer(signature)
if bio:
swig_pkcs7 = m2.pkcs7_read_bio_der(bio.bio_ptr())
if swig_pkcs7:
p7 = SMIME.PKCS7(swig_pkcs7)
xst = p7.get0_signers(X509.X509_Stack())
retlist = []
if xst:
for cert in xst:
sn = cert.get_serial_number()
sha1_fingerprint = cert.get_fingerprint('sha1').lower().rjust(40, '0')
md5_fingerprint = cert.get_fingerprint('md5').lower().rjust(32, '0')
subject_str = str(cert.get_subject())
try:
cn = subject_str[subject_str.index("/CN=")+len("/CN="):]
except:
continue
retlist.append({
"sn": str(sn),
"cn": cn,
"sha1_fingerprint": sha1_fingerprint,
"md5_fingerprint": md5_fingerprint
})
return retlist