def certificateRequest(self, distinguishedName,
format=crypto.FILETYPE_ASN1,
digestAlgorithm='md5'):
"""Create a certificate request signed with this key.
@return: a string, formatted according to the 'format' argument.
"""
return self.requestObject(distinguishedName, digestAlgorithm).dump(format)
python类md5()的实例源码
def signCertificateRequest(self,
issuerDistinguishedName,
requestData,
verifyDNCallback,
serialNumber,
requestFormat=crypto.FILETYPE_ASN1,
certificateFormat=crypto.FILETYPE_ASN1,
secondsToExpiry=60 * 60 * 24 * 365, # One year
digestAlgorithm='md5'):
"""
Given a blob of certificate request data and a certificate authority's
DistinguishedName, return a blob of signed certificate data.
If verifyDNCallback returns a Deferred, I will return a Deferred which
fires the data when that Deferred has completed.
"""
hlreq = CertificateRequest.load(requestData, requestFormat)
dn = hlreq.getSubject()
vval = verifyDNCallback(dn)
def verified(value):
if not value:
raise VerifyError("DN callback %r rejected request DN %r" % (verifyDNCallback, dn))
return self.signRequestObject(issuerDistinguishedName, hlreq,
serialNumber, secondsToExpiry, digestAlgorithm).dump(certificateFormat)
if isinstance(vval, Deferred):
return vval.addCallback(verified)
else:
return verified(vval)
def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this.
return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest()))
def respond(challenge, password):
"""Respond to a challenge.
This is useful for challenge/response authentication.
"""
m = md5.new()
m.update(password)
hashedPassword = m.digest()
m = md5.new()
m.update(hashedPassword)
m.update(challenge)
doubleHashedPassword = m.digest()
return doubleHashedPassword
def checkPassword(self, password):
return self.checkMD5Password(md5.md5(password).digest())
# IUsernameMD5Password
def checkMD5Password(self, md5Password):
md = md5.new()
md.update(md5Password)
md.update(self.challenge)
correct = md.digest()
return self.response == correct
def getUidl(self, i):
"""Return a unique identifier for a message
This is done using the basename of the filename.
It is globally unique because this is how Maildirs are designed.
"""
# Returning the actual filename is a mistake. Hash it.
base = os.path.basename(self.list[i])
return md5.md5(base).hexdigest()
def getUidl(self, i):
return md5.new(self.msgs[i]).hexdigest()
def H(val):
return md5(val).hexdigest()
def generate_response(chaldict,uri,username,passwd,method='GET',cnonce=None):
"""
Generate an authorization response dictionary. chaldict should contain the digest
challenge in dict form. Use fetch_challenge to create a chaldict from a HTTPResponse
object like this: fetch_challenge(res.getheaders()).
returns dict (the authdict)
Note. Use build_authorization_arg() to turn an authdict into the final Authorization
header value.
"""
authdict = {}
qop = chaldict.get('qop')
nonce = chaldict.get('nonce')
algorithm = chaldict.get('algorithm','MD5')
realm = chaldict.get('realm','MD5')
nc = "00000001"
if not cnonce:
cnonce = H(str(random.randint(0,10000000)))[:16]
if algorithm.lower()=='md5-sess':
a1 = A1(username,realm,passwd,nonce,cnonce)
else:
a1 = A1(username,realm,passwd)
a2 = A2(method,uri)
secret = H(a1)
data = '%s:%s:%s:%s:%s' % (nonce,nc,cnonce,qop,H(a2))
authdict['username'] = '"%s"' % username
authdict['realm'] = '"%s"' % realm
authdict['nonce'] = '"%s"' % nonce
authdict['uri'] = '"%s"' % uri
authdict['response'] = '"%s"' % KD(secret,data)
authdict['qop'] = '"%s"' % qop
authdict['nc'] = nc
authdict['cnonce'] = '"%s"' % cnonce
return authdict
def PRF(secret, label, seed, length):
#Split the secret into left and right halves
S1 = secret[ : int(math.ceil(len(secret)/2.0))]
S2 = secret[ int(math.floor(len(secret)/2.0)) : ]
#Run the left half through P_MD5 and the right half through P_SHA1
p_md5 = P_hash(md5, S1, concatArrays(stringToBytes(label), seed), length)
p_sha1 = P_hash(sha, S2, concatArrays(stringToBytes(label), seed), length)
#XOR the output values and return the result
for x in range(length):
p_md5[x] ^= p_sha1[x]
return p_md5
def PRF_SSL(secret, seed, length):
secretStr = bytesToString(secret)
seedStr = bytesToString(seed)
bytes = createByteArrayZeros(length)
index = 0
for x in range(26):
A = chr(ord('A')+x) * (x+1) # 'A', 'BB', 'CCC', etc..
input = secretStr + sha.sha(A + secretStr + seedStr).digest()
output = md5.md5(input).digest()
for c in output:
if index >= length:
return bytes
bytes[index] = ord(c)
index += 1
return bytes
def __init__(self, key, msg = None, digestmod = None):
"""Create a new MAC_SSL object.
key: key for the keyed hash object.
msg: Initial input for the hash, if provided.
digestmod: A module supporting PEP 247. Defaults to the md5 module.
"""
if digestmod is None:
import md5
digestmod = md5
if key == None: #TREVNEW - for faster copying
return #TREVNEW
self.digestmod = digestmod
self.outer = digestmod.new()
self.inner = digestmod.new()
self.digest_size = digestmod.digest_size
ipad = "\x36" * 40
opad = "\x5C" * 40
self.inner.update(key)
self.inner.update(ipad)
self.outer.update(key)
self.outer.update(opad)
if msg is not None:
self.update(msg)
def _handshakeStart(self, client):
self._client = client
self._handshake_md5 = md5.md5()
self._handshake_sha = sha.sha()
self._handshakeBuffer = []
self.allegedSharedKeyUsername = None
self.allegedSrpUsername = None
self._refCount = 1
def hash(self, clientRandom, serverRandom):
oldCipherSuite = self.cipherSuite
self.cipherSuite = None
try:
bytes = clientRandom + serverRandom + self.write()[4:]
s = bytesToString(bytes)
return stringToBytes(md5.md5(s).digest() + sha.sha(s).digest())
finally:
self.cipherSuite = oldCipherSuite
def encrypt(self, user_pwd, owner_pwd = None, use_128bit = True):
import time, random
if owner_pwd == None:
owner_pwd = user_pwd
if use_128bit:
V = 2
rev = 3
keylen = 128 / 8
else:
V = 1
rev = 2
keylen = 40 / 8
# permit everything:
P = -1
O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))
ID_1 = md5(repr(time.time())).digest()
ID_2 = md5(repr(random.random())).digest()
self._ID = ArrayObject((ByteStringObject(ID_1), ByteStringObject(ID_2)))
if rev == 2:
U, key = _alg34(user_pwd, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)
encrypt = DictionaryObject()
encrypt[NameObject("/Filter")] = NameObject("/Standard")
encrypt[NameObject("/V")] = NumberObject(V)
if V == 2:
encrypt[NameObject("/Length")] = NumberObject(keylen * 8)
encrypt[NameObject("/R")] = NumberObject(rev)
encrypt[NameObject("/O")] = ByteStringObject(O)
encrypt[NameObject("/U")] = ByteStringObject(U)
encrypt[NameObject("/P")] = NumberObject(P)
self._encrypt = self._addObject(encrypt)
self._encrypt_key = key
##
# Writes the collection of pages added to this object out as a PDF file.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
# @param stream An object to write the file to. The object must support
# the write method, and the tell method, similar to a file object.
def signature(self):
try:
from hashlib import md5
except ImportError:
from md5 import md5
try:
sig = md5()
if self.start:
sig.update(self.start.encode('latin-1'))
if self.prec:
sig.update("".join(["".join(p) for p in self.prec]).encode('latin-1'))
if self.tokens:
sig.update(" ".join(self.tokens).encode('latin-1'))
for f in self.pfuncs:
if f[3]:
sig.update(f[3].encode('latin-1'))
except (TypeError,ValueError):
pass
return sig.digest()
# -----------------------------------------------------------------------------
# validate_file()
#
# This method checks to see if there are duplicated p_rulename() functions
# in the parser module file. Without this function, it is really easy for
# users to make mistakes by cutting and pasting code fragments (and it's a real
# bugger to try and figure out why the resulting parser doesn't work). Therefore,
# we just do a little regular expression pattern matching of def statements
# to try and detect duplicates.
# -----------------------------------------------------------------------------
def _hash_xml_dict(self, d):
return md5.md5(json.dumps(
[(k, d.get(k, '')) for k in RCVA_DATA.keys()])).hexdigest()
def _hash_text(s):
return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest()
# Table of hash values for escaped characters: