Python md5 模块,md5() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用md5.md5()

项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_file_win32(fname):
    try:
        fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
    except OSError:
        raise IOError('Cannot read from %r' % fname)
    f = os.fdopen(fd, 'rb')
    m = md5()
    try:
        while fname:
            fname = f.read(200000)
            m.update(fname)
    finally:
        f.close()
    return m.digest()

# always save these
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_file_win32(fname):
    try:
        fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
    except OSError:
        raise IOError('Cannot read from %r' % fname)
    f = os.fdopen(fd, 'rb')
    m = md5()
    try:
        while fname:
            fname = f.read(200000)
            m.update(fname)
    finally:
        f.close()
    return m.digest()

# always save these
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_file_win32(fname):
    try:
        fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
    except OSError:
        raise IOError('Cannot read from %r' % fname)
    f = os.fdopen(fd, 'rb')
    m = md5()
    try:
        while fname:
            fname = f.read(200000)
            m.update(fname)
    finally:
        f.close()
    return m.digest()

# always save these
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def mangleData(self, data, index):
        self.sha1_offset = 208
        self.md5_offset = 256
        self.header_offset = 360
        self.filedata_offset = 3170

        data = MangleFile.mangleData(self, data, index)

        if USE_HACHOIR:
            #data.tofile(open('/tmp/oops', 'wb'))
            hachoir_config.quiet = True
            data_str = data.tostring()
            parser = guessParser(StringInputStream(data_str))
            if parser:
                self.useHachoirParser(parser)

        summary_data = data[self.header_offset:].tostring()
        checksum = md5(summary_data).digest()
        data[self.md5_offset:self.md5_offset+16] = array('B', checksum)

        summary_data = data[self.header_offset:self.filedata_offset].tostring()
        checksum = sha(summary_data).hexdigest()
        data[self.sha1_offset:self.sha1_offset+40] = array('B', checksum)

        return data
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def signRequestObject(self,
                          issuerDistinguishedName,
                          requestObject,
                          serialNumber,
                          secondsToExpiry=60 * 60 * 24 * 365, # One year
                          digestAlgorithm='md5'):
        """
        Sign a CertificateRequest instance, returning a Certificate instance.
        """
        req = requestObject.original
        dn = requestObject.getSubject()
        cert = crypto.X509()
        issuerDistinguishedName._copyInto(cert.get_issuer())
        cert.set_subject(req.get_subject())
        cert.set_pubkey(req.get_pubkey())
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(secondsToExpiry)
        cert.set_serial_number(serialNumber)
        cert.sign(self.original, digestAlgorithm)
        return Certificate(cert)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def DigestCalcHA1(
    pszAlg,
    pszUserName,
    pszRealm,
    pszPassword,
    pszNonce,
    pszCNonce,
):
    m = md5.md5()
    m.update(pszUserName)
    m.update(":")
    m.update(pszRealm)
    m.update(":")
    m.update(pszPassword)
    HA1 = m.digest()
    if pszAlg == "md5-sess":
        m = md5.md5()
        m.update(HA1)
        m.update(":")
        m.update(pszNonce)
        m.update(":")
        m.update(pszCNonce)
        HA1 = m.digest()
    return HA1.encode('hex')
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def _alg33_1(password, rev, keylen):
    # 1. Pad or truncate the owner password string as described in step 1 of
    # algorithm 3.2.  If there is no owner password, use the user password
    # instead.
    password = (password + _encryption_padding)[:32]
    # 2. Initialize the MD5 hash function and pass the result of step 1 as
    # input to this function.
    m = md5(password)
    # 3. (Revision 3 or greater) Do the following 50 times: Take the output
    # from the previous MD5 hash and pass it as input into a new MD5 hash.
    md5_hash = m.digest()
    if rev >= 3:
        for i in range(50):
            md5_hash = md5(md5_hash).digest()
    # 4. Create an RC4 encryption key using the first n bytes of the output
    # from the final MD5 hash, where n is always 5 for revision 2 but, for
    # revision 3 or greater, depends on the value of the encryption
    # dictionary's /Length entry.
    key = md5_hash[:keylen]
    return key

# Implementation of algorithm 3.4 of the PDF standard security handler,
# section 3.5.2 of the PDF 1.6 reference.
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def _alg33_1(password, rev, keylen):
    # 1. Pad or truncate the owner password string as described in step 1 of
    # algorithm 3.2.  If there is no owner password, use the user password
    # instead.
    password = b_((password + str_(_encryption_padding))[:32])
    # 2. Initialize the MD5 hash function and pass the result of step 1 as
    # input to this function.
    m = md5(password)
    # 3. (Revision 3 or greater) Do the following 50 times: Take the output
    # from the previous MD5 hash and pass it as input into a new MD5 hash.
    md5_hash = m.digest()
    if rev >= 3:
        for i in range(50):
            md5_hash = md5(md5_hash).digest()
    # 4. Create an RC4 encryption key using the first n bytes of the output
    # from the final MD5 hash, where n is always 5 for revision 2 but, for
    # revision 3 or greater, depends on the value of the encryption
    # dictionary's /Length entry.
    key = md5_hash[:keylen]
    return key


# Implementation of algorithm 3.4 of the PDF standard security handler,
# section 3.5.2 of the PDF 1.6 reference.
项目:scipy-lecture-notes-zh-CN    作者:jayleicn    | 项目源码 | 文件源码
def latex2html(node, source):
    inline = isinstance(node.parent, nodes.TextElement)
    latex = node['latex']
    name = 'math-%s' % md5(latex).hexdigest()[-10:]
    dest = '_static/%s.png' % name
    depth = latex2png(latex, dest, node['fontset'])

    path = '_static'
    count = source.split('/doc/')[-1].count('/')
    for i in range(count):
        if os.path.exists(path): break
        path = '../'+path
    path = '../'+path #specifically added for matplotlib
    if inline:
        cls = ''
    else:
        cls = 'class="center" '
    if inline and depth != 0:
        style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
    else:
        style = ''

    return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
项目:easyATT    作者:InfiniteSamuel    | 项目源码 | 文件源码
def compute_encryption_key(self, password):
        # Algorithm 3.2
        password = (password + self.PASSWORD_PADDING)[:32]  # 1
        hash = md5.md5(password)  # 2
        hash.update(self.o)  # 3
        hash.update(struct.pack('<l', self.p))  # 4
        hash.update(self.docid[0])  # 5
        if self.r >= 4:
            if not self.encrypt_metadata:
                hash.update(b'\xff\xff\xff\xff')
        result = hash.digest()
        n = 5
        if self.r >= 3:
            n = self.length // 8
            for _ in range(50):
                result = md5.md5(result[:n]).digest()
        return result[:n]
项目:easyATT    作者:InfiniteSamuel    | 项目源码 | 文件源码
def authenticate_owner_password(self, password):
        # Algorithm 3.7
        password = (password + self.PASSWORD_PADDING)[:32]
        hash = md5.md5(password)
        if self.r >= 3:
            for _ in range(50):
                hash = md5.md5(hash.digest())
        n = 5
        if self.r >= 3:
            n = self.length // 8
        key = hash.digest()[:n]
        if self.r == 2:
            user_password = ARC4.new(key).decrypt(self.o)
        else:
            user_password = self.o
            for i in range(19, -1, -1):
                k = b''.join(chr(ord(c) ^ i) for c in key)
                user_password = ARC4.new(k).decrypt(user_password)
        return self.authenticate_user_password(user_password)
项目:oabot    作者:dissemin    | 项目源码 | 文件源码
def __init__(self, tpl, page):
        """
        :param tpl: a mwparserfromhell template: the original template
                that we want to change
        """
        self.template = tpl
        self.orig_string = unicode(self.template)
        r = md5.md5()
        r.update(self.orig_string.encode('utf-8'))
        self.orig_hash = r.hexdigest()
        self.classification = None
        self.conflicting_value = ''
        self.proposed_change = ''
        self.proposed_link = None
        self.index = None
        self.page = page
        self.proposed_link_policy = None
        self.issn = None
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def signRequestObject(self,
                          issuerDistinguishedName,
                          requestObject,
                          serialNumber,
                          secondsToExpiry=60 * 60 * 24 * 365, # One year
                          digestAlgorithm='md5'):
        """
        Sign a CertificateRequest instance, returning a Certificate instance.
        """
        req = requestObject.original
        dn = requestObject.getSubject()
        cert = crypto.X509()
        issuerDistinguishedName._copyInto(cert.get_issuer())
        cert.set_subject(req.get_subject())
        cert.set_pubkey(req.get_pubkey())
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(secondsToExpiry)
        cert.set_serial_number(serialNumber)
        cert.sign(self.original, digestAlgorithm)
        return Certificate(cert)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def DigestCalcHA1(
    pszAlg,
    pszUserName,
    pszRealm,
    pszPassword,
    pszNonce,
    pszCNonce,
):
    m = md5.md5()
    m.update(pszUserName)
    m.update(":")
    m.update(pszRealm)
    m.update(":")
    m.update(pszPassword)
    HA1 = m.digest()
    if pszAlg == "md5-sess":
        m = md5.md5()
        m.update(HA1)
        m.update(":")
        m.update(pszNonce)
        m.update(":")
        m.update(pszCNonce)
        HA1 = m.digest()
    return HA1.encode('hex')
项目:poc-exp    作者:v1cker    | 项目源码 | 文件源码
def _audit_sniff(self, url, head, data):
        __opid = Scan_ThreadLocal.__pid

        for OO0O0 in self._sniff_plugins:

            Day_time_1 = time.time() * 1000
            try:

                Scan_ThreadLocal.__pid = OO0O0

                self._sniff_plugins[OO0O0].audit(url, head, data)

            except:
                Logging_Obj.exception('[M:%d] %s' % (OO0O0, repr(url)))

            Day_time_2 = time.time() * 1000

            Mysql_table_insert('auditlog', uuid=md5.md5(url).hexdigest(), plugin_id=OO0O0, type=1, arg=repr(url),
                               time=int(Day_time_2 - Day_time_1))

        Scan_ThreadLocal.__pid = __opid
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def _check_final_md5(self, key, etag):
        """
        Checks that etag from server agrees with md5 computed before upload.
        This is important, since the upload could have spanned a number of
        hours and multiple processes (e.g., gsutil runs), and the user could
        change some of the file and not realize they have inconsistent data.
        """
        if key.bucket.connection.debug >= 1:
            print 'Checking md5 against etag.'
        if key.md5 != etag.strip('"\''):
            # Call key.open_read() before attempting to delete the
            # (incorrect-content) key, so we perform that request on a
            # different HTTP connection. This is neededb because httplib
            # will return a "Response not ready" error if you try to perform
            # a second transaction on the connection.
            key.open_read()
            key.close()
            key.delete()
            raise ResumableUploadException(
                'File changed during upload: md5 signature doesn\'t match etag '
                '(incorrect uploaded object deleted)',
                ResumableTransferDisposition.ABORT)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def H(self, data):
        return md5.md5(data).hexdigest()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def _createNonce(self):
        return md5.md5("%d:%s" % (time.time(), self.realm)).hexdigest()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def hashPassword(password, salt):
    p1 = md5.md5(password).hexdigest() + '.' + salt.strip()
    hashedpass = md5.md5(p1).hexdigest()
    return hashedpass
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_file(fname):
    """
    Compute a hash value for a file by using md5. This method may be replaced by
    a faster version if necessary. The following uses the file size and the timestamp value::

        import stat
        from waflib import Utils
        def h_file(fname):
            st = os.stat(fname)
            if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
            m = Utils.md5()
            m.update(str(st.st_mtime))
            m.update(str(st.st_size))
            m.update(fname)
            return m.digest()
        Utils.h_file = h_file

    :type fname: string
    :param fname: path to the file to hash
    :return: hash of the file contents
    """
    f = open(fname, 'rb')
    m = md5()
    try:
        while fname:
            fname = f.read(200000)
            m.update(fname)
    finally:
        f.close()
    return m.digest()
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_list(lst):
    """
    Hash lists. For tuples, using hash(tup) is much more efficient,
    except on python >= 3.3 where hash randomization assumes everybody is running a web application.

    :param lst: list to hash
    :type lst: list of strings
    :return: hash of the list
    """
    m = md5()
    m.update(str(lst).encode())
    return m.digest()
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_file(fname):
    """
    Compute a hash value for a file by using md5. This method may be replaced by
    a faster version if necessary. The following uses the file size and the timestamp value::

        import stat
        from waflib import Utils
        def h_file(fname):
            st = os.stat(fname)
            if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
            m = Utils.md5()
            m.update(str(st.st_mtime))
            m.update(str(st.st_size))
            m.update(fname)
            return m.digest()
        Utils.h_file = h_file

    :type fname: string
    :param fname: path to the file to hash
    :return: hash of the file contents
    """
    f = open(fname, 'rb')
    m = md5()
    try:
        while fname:
            fname = f.read(200000)
            m.update(fname)
    finally:
        f.close()
    return m.digest()
项目:SoCFoundationFlow    作者:mattaw    | 项目源码 | 文件源码
def h_list(lst):
    """
    Hash lists. For tuples, using hash(tup) is much more efficient,
    except on python >= 3.3 where hash randomization assumes everybody is running a web application.

    :param lst: list to hash
    :type lst: list of strings
    :return: hash of the list
    """
    m = md5()
    m.update(str(lst).encode())
    return m.digest()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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.
    # -----------------------------------------------------------------------------
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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.
    # -----------------------------------------------------------------------------
项目:macholib    作者:secmobi    | 项目源码 | 文件源码
def download_setuptools(packagename, to_dir):
    # making sure we use the absolute path
    to_dir = os.path.abspath(to_dir)
    try:
        from urllib.request import urlopen
    except ImportError:
        from urllib2 import urlopen

    chksum, url = get_pypi_src_download(packagename)
    tgz_name = os.path.basename(url)
    saveto = os.path.join(to_dir, tgz_name)

    src = dst = None
    if not os.path.exists(saveto):  # Avoid repeated downloads
        try:
            log.warn("Downloading %s", url)
            src = urlopen(url)
            # Read/write all in one block, so we don't create a corrupt file
            # if the download is interrupted.
            data = src.read()

            if chksum is not None:
                data_sum = md5(data).hexdigest()
                if data_sum != chksum:
                    raise RuntimeError("Downloading %s failed: corrupt checksum"%(url,))


            dst = open(saveto, "wb")
            dst.write(data)
        finally:
            if src:
                src.close()
            if dst:
                dst.close()
    return os.path.realpath(saveto)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def digest(self, method='md5'):
        """
        Return a digest hash of this certificate using the specified hash
        algorithm.

        @param method: One of C{'md5'} or C{'sha'}.
        @rtype: C{str}
        """
        return self.original.digest(method)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def certificateRequest(self, format=crypto.FILETYPE_ASN1,
                           digestAlgorithm='md5'):
        return self.privateKey.certificateRequest(
            self.getSubject(),
            format,
            digestAlgorithm)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def signRequestObject(self, certificateRequest, serialNumber,
                          secondsToExpiry=60 * 60 * 24 * 365, # One year
                          digestAlgorithm='md5'):
        return self.privateKey.signRequestObject(self.getSubject(),
                                                 certificateRequest,
                                                 serialNumber,
                                                 secondsToExpiry,
                                                 digestAlgorithm)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def keyHash(self):
        """
        MD5 hex digest of signature on an empty certificate request with this
        key.
        """
        return md5.md5(self._emptyReq).hexdigest()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this.
    return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest()))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def checkPassword(self, password):
        return self.checkMD5Password(md5.md5(password).digest())

    # IUsernameMD5Password
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def checkMD5Password(self, md5Password):
        md = md5.new()
        md.update(md5Password)
        md.update(self.challenge)
        correct = md.digest()
        return self.response == correct
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def getUidl(self, i):
        return md5.new(self.msgs[i]).hexdigest()
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
def H(val):
    return md5(val).hexdigest()
项目:vspheretools    作者:devopshq    | 项目源码 | 文件源码
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
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
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.
项目:SwiftKitten    作者:johncsnyder    | 项目源码 | 文件源码
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.
    # -----------------------------------------------------------------------------
项目:gennotes    作者:madprime    | 项目源码 | 文件源码
def _hash_xml_dict(self, d):
        return md5.md5(json.dumps(
            [(k, d.get(k, '')) for k in RCVA_DATA.keys()])).hexdigest()
项目:awesome-python3-webapp    作者:syusonn    | 项目源码 | 文件源码
def _hash_text(s):
    return 'md5-' + md5(SECRET_SALT + s.encode("utf-8")).hexdigest()

# Table of hash values for escaped characters: