当前位置: 首页>>代码示例>>Python>>正文


Python Hash.MD4类代码示例

本文整理汇总了Python中Crypto.Hash.MD4的典型用法代码示例。如果您正苦于以下问题:Python MD4类的具体用法?Python MD4怎么用?Python MD4使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MD4类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: otp

def otp(password, seed, sequence):
    """
    Calculates a one-time password hash using the given password, seed, and
    sequence number and returns it.
    Uses the MD4/sixword algorithm as supported by TACACS+ servers.

    :type  password: str
    :param password: A password.
    :type  seed: str
    :param seed: A cryptographic seed.
    :type  sequence: int
    :param sequence: A sequence number.
    :rtype:  string
    :return: A hash.
    """
    if len(password) not in list(range(4, 64)):
        raise ValueError('passphrase length')
    if len(seed) not in list(range(1, 17)):
        raise ValueError('seed length')
    for x in seed:
        if not x in _VALIDSEEDCHARACTERS:
            raise ValueError('seed composition')
    if sequence < 0:
        raise ValueError('sequence')

    # Discard the first <sequence> keys
    thehash = MD4.new(seed + password).digest()
    thehash = _fold_md4_or_md5(thehash)
    for i in range(0, sequence):
        thehash = _fold_md4_or_md5(MD4.new(thehash).digest())

    # Generate the result
    return _sixword_from_raw(thehash)
开发者ID:cnooye,项目名称:exscript,代码行数:33,代码来源:crypt.py

示例2: RenFile

    def RenFile(self, fname, new_fname):
        '''
        Rename one file. This cannot be undone, so be careful! \n\
        '''
        ti = clock()
        if not validFileName(new_fname):
            self._log(2, 'Func RenFile: a filename cannot contain any of the following characters '\
                ' \\ / : * ? " < > |')
            return -1

        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4
        md4 = MD4.new(new_fname)
        new_filename = 't'+md4.hexdigest()
        del md4

        # Check file existence.
        if self.c.execute('select file from _files_ where file = ?', [new_fname]).fetchone():
            self._log(2, 'Func RenFile: there is already a file called "%s"!' % new_fname)
            return -1

        try:
            self.c.execute('alter table %s rename to %s' % (filename, new_filename))
            self.c.execute('update _files_ set file = ? where file = ?', [new_fname, fname])
            self.c.execute('update _statistics_ set file = ? where file = ?', [new_fname, fname])
            self.conn.commit()
            self._log(1, 'Renaming from "%s" into "%s" took %.4f sec.' % (fname, new_fname, clock()-ti))
            return 0
        except:
            self._log(2, 'Func RenFile: cannot find the file called "%s"!' % fname)
            return -1
开发者ID:croqaz,项目名称:private-briefcase,代码行数:32,代码来源:briefcase.py

示例3: CopyIntoNew

    def CopyIntoNew(self, fname, version, new_fname):
        '''
        Copy one version of one file, into a new file, that will have version 1. \n\
        The password will be the same as in the original file. \n\
        '''
        ti = clock()
        if not validFileName(new_fname):
            self._log(2, 'Func CopyIntoNew: a file name cannot contain any of the following '\
                'characters  \\ / : * ? " < > |')
            return -1

        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4
        md4 = MD4.new(new_fname)
        new_filename = 't'+md4.hexdigest()
        del md4

        if version < 0 : version = 0

        # If new file name already exists, exit.
        if self.c.execute('select file from _files_ where file="%s"' % (new_fname)).fetchone():
            self._log(2, 'Func CopyIntoNew: there is already a file called "%s"!' % new_fname)
            return -1

        # Try to extract specified version.
        try:
            self.c.execute('select version from %s' % filename).fetchone()
        except:
            self._log(2, 'Func CopyIntoNew: there is no such file called "%s"!' % fname)
            return -1

        # If version was specified, get that version.
        if version:
            data = self.c.execute('select raw, hash, size from %s where version=%i' % \
                (filename, version)).fetchone()
        # Else, get the latest version.
        else:
            data = self.c.execute('select raw, hash, size from %s order by version desc' % \
                filename).fetchone()

        self.c.execute('create table %s (version integer primary key asc, raw BLOB, hash TEXT,'
            'size INTEGER, date TEXT, user TEXT)' % new_filename)
        self.c.execute(('insert into %s (raw, hash, size, date, user) values (?,?,?,?,?)' % new_filename),
            [data[0], data[1], data[2], strftime("%Y-%b-%d %H:%M:%S"), os.getenv('USERNAME')])

        # Use original password and labels of file.
        more = self.c.execute('select pwd, labels from _files_ where file=?', [fname]).fetchone()

        self.c.execute('insert into _files_ (file, pwd, labels) values (?,?,?)', (new_fname,)+more)
        self.FileStatistics(new_fname)
        self.conn.commit()

        self._log(1, 'Copying file "%s" into "%s" took %.4f sec.' % (fname, new_fname, clock()-ti))
        return 0
开发者ID:croqaz,项目名称:private-briefcase,代码行数:55,代码来源:briefcase.py

示例4: generateSessionKeyV1

def generateSessionKeyV1(password, lmhash, nthash):
    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(NTOWFv1(password, lmhash, nthash))
    return hash.digest()
开发者ID:Hormazd,项目名称:impacket,代码行数:7,代码来源:ntlm.py

示例5: compute_password_nt_hash

def compute_password_nt_hash(pw):
    """Compute NT password hash.

    In practice, this is an MD4 of a password.  For details, see:

      * http://en.wikipedia.org/wiki/NTLM
      * http://tools.ietf.org/html/rfc2433
      * http://tools.ietf.org/html/rfc2759

    Note that the MD4 is computed over the UNICODE version of the
    password.  And this UNICODE version is *little endian*!
    """

    from Crypto.Hash import MD4

    pw = unicode(pw)  # if not already unicode

    # little endian unicode buffer
    t = ''
    for c in pw:
        o = ord(c)
        t += chr(o & 0xff)         # lo
        t += chr((o >> 8) & 0xff)  # hi

    return MD4.new(t).digest()
开发者ID:nakedible,项目名称:vpnease-l2tp,代码行数:25,代码来源:helpers.py

示例6: test

def test(nb_chunks, chunk_size):
  h = MD4.new()
  f = open('test.txt', 'rb')
  for i in range(nb_chunks):
    h.update(f.read(chunk_size))
  f.close()
  d = h.hexdigest()
开发者ID:laurentluce,项目名称:blog,代码行数:7,代码来源:md4.py

示例7: ed2k

def ed2k(handle):
    """
    ED2K is a rudimentary tree hash, with a depth of 1 and a leaf size of
    9,728,000 bytes. The hash is MD4, which is not natively available in
    Python, so I use PyCrypto's version instead.
    """

    buf = ''
    hashl = []
    while True:
        buf = handle.read(9728000)
        if buf == '':
            break
        hashl.append(MD4.new(buf).digest())
    hashed = MD4.new(''.join(hashl)).hexdigest()
    return hashed
开发者ID:MostAwesomeDude,项目名称:pyrite,代码行数:16,代码来源:hashing.py

示例8: DelFile

    def DelFile(self, fname, version=0):
        '''
        If version is a positive number, only that version of the file is deleted. \n\
        Else, the entire table is dropped. \n\
        This cannot be undone, so be careful. \n\
        '''
        ti = clock()
        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4

        if version > 0:
            self.c.execute('delete from %s where version=%s' % (filename, version))
            self.c.execute('reindex %s' % filename)
            self.conn.commit()
            self._log(1, 'Deleting file "%s" version "%i" took %.4f sec.' % (fname, version, clock()-ti))
            return 0
        else:
            try:
                self.c.execute('drop table %s' % filename)
                self.c.execute('delete from _files_ where file="%s"' % fname)
                self.c.execute('delete from _statistics_ where file="%s"' % fname)
                self.conn.commit()
                self._log(1, 'Deleting file "%s" took %.4f sec.' % (fname, clock()-ti))
                return 0
            except:
                self._log(2, 'Func DelFile: cannot find the file called "%s"!' % fname)
                return -1
开发者ID:croqaz,项目名称:private-briefcase,代码行数:28,代码来源:briefcase.py

示例9: check_signature

    def check_signature(self, cacert):
        """Verifies that the certificate is signed by cacert.

        Args:
        cacert: Certificate object which is suspected to be the parent
        of this one in the trust chain.

        Returns:
        True if this certificate was signed by cacert, false
        otherwise.
        """

        cakey = cacert.get_pub_key()
        cahash = None

        if self._algo == _OID_RSA_SHA1:
            cahash = SHA.new(self._certdata)
        elif self._algo == _OID_RSA_MD4:
            cahash = MD4.new(self._certdata)
        elif self._algo == _OID_RSA_MD2:
            cahash = MD2.new(self._certdata)
        elif self._algo == _OID_RSA_MD5:
            cahash = MD5.new(self._certdata)
        elif self._algo == _OID_RSA_SHA256:
            cahash = SHA256.new(self._certdata)
        else:
            raise X509SignatureAlgorithmUnsupported(
                "No algorithm known for " + self._algo)

        verifier = PKCS1_v1_5.new(cakey)
        return verifier.verify(cahash, self._signature)
开发者ID:tonnerre,项目名称:py-ancientsolutions-crypttools,代码行数:31,代码来源:x509.py

示例10: compute_nthash

def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    password = unicode(password).encode('utf_16le')
    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(password)
    return hash.digest()
开发者ID:Hormazd,项目名称:impacket,代码行数:9,代码来源:ntlm.py

示例11: FileStatistics

    def FileStatistics(self, fname, silent=True):
        '''
        Generate/ return a dictionary containing the following key-value pairs : \n\
        fileName, firstSize, lastSize, firstFileDate, lastFileDate, biggestSize,
        firstFileUser, lastFileUser, fileLabels, versions. \n\
        If the file has 1 version, firstSize==lastSize and firstFileDate==lastFileDate and
        firstFileUser==lastFileUser. \n\
        On error, it returns an empty dictionary. \n\
        '''
        ti = clock()
        md4 = MD4.new(fname)
        filename = 't'+md4.hexdigest()
        del md4

        # Check file existence.
        if not self.c.execute('select file from _files_ where file = ?', [fname]).fetchone():
            self._log(2, 'Func FileStatistics: there is no such file called "%s"!' % fname)
            return {}

        # Size.
        biggestSize = self.c.execute('select size from %s order by size desc' %
            filename).fetchone()[0]
        firstFileSize = self.c.execute('select size from %s order by version asc' %
            filename).fetchone()[0]
        lastFileSize = self.c.execute('select size from %s order by version desc' %
            filename).fetchone()[0]
        # Date added.
        firstFileDate = self.c.execute('select date from %s order by version asc' %
            filename).fetchone()[0]
        lastFileDate = self.c.execute('select date from %s order by version desc' %
            filename).fetchone()[0]
        # User added.
        firstFileUser = self.c.execute('select user from %s order by version asc' %
            filename).fetchone()[0]
        lastFileUser = self.c.execute('select user from %s order by version desc' %
            filename).fetchone()[0]
        labels = self.c.execute('select labels from _files_ where file="%s"' %
            fname).fetchone()[0]
        versions = len( self.c.execute('select version from %s' % filename).fetchall() )

        self.c.execute('insert or replace into _statistics_ (file, size0, size, sizeB, '
            'date0, date, user0, user, labels) values (?,?,?,?,?,?,?,?,?)', [fname,
            firstFileSize, lastFileSize, biggestSize, firstFileDate, lastFileDate,
            firstFileUser, lastFileUser, labels])

        if not silent:
            self._log(1, 'Get properties for file "%s" took %.4f sec.' % (fname, clock()-ti))
        return {'fileName':fname, 'internFileName':filename, 'biggestSize':biggestSize,
            'firstFileSize':firstFileSize, 'lastFileSize':lastFileSize,
            'firstFileDate':firstFileDate, 'lastFileDate':lastFileDate,
            'firstFileUser':firstFileUser, 'lastFileUser':lastFileUser,
            'labels':labels, 'versions':versions}
开发者ID:croqaz,项目名称:private-briefcase,代码行数:52,代码来源:briefcase.py

示例12: compute_nthash

def compute_nthash(password):
    # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html)
    try:
        password = unicode(password).encode('utf_16le')
    except UnicodeDecodeError:
        import sys
        password = password.decode(sys.getfilesystemencoding()).encode('utf_16le')

    if POW:
        hash = POW.Digest(POW.MD4_DIGEST)
    else:        
        hash = MD4.new()
    hash.update(password)
    return hash.digest()
开发者ID:root9b,项目名称:impacket,代码行数:14,代码来源:ntlm.py

示例13: findPassword

def findPassword(CCH16, CCR24):

	# Prepare arguments for processing
	CCH16 = HexToByte(CCH16)
	CCR24 = CCR24.replace(':', ' ')
	CCR24 = CCR24.upper()
	timer = 0
	print "\n--< This may take a while..."
	print "--< Each dot below represents 10,000 attempted passwords."
	print "\n--< Cracking",
		
	for guess in dictionary:

		# Track/display timer
		timer += 1
		if timer%10000 == 0:
			print ".",
		
		# Create nt_hash for this guess using MD4 hashing algorithm.
		guess = guess.strip()					# Remove newline ('\n')
		uGuess = guess.encode('utf-16-le')		# Convert to utf-16le
		nt_hash = MD4.new(uGuess).hexdigest()
		
		# Split nt_hash into three DES keys.
		# Add the parity bits to the DES keys to make them 8-bytes each.
		des_key_1 = HexToByte(addParity(nt_hash[0:14]))
		des_key_2 = HexToByte(addParity(nt_hash[14:28]))
		des_key_3 = HexToByte(addParity(nt_hash[28:] + "0000000000"))

		# Create DES encryption objects with keys.
		des_1 = DES.new(des_key_1, DES.MODE_ECB)
		des_2 = DES.new(des_key_2, DES.MODE_ECB)
		des_3 = DES.new(des_key_3, DES.MODE_ECB)
		
		# Calculate 24-byte Client Challenge Response for this guess 
		# with the DES objects and the 16-byte Client Challenge Hash.
		ccr24_part1 = des_1.encrypt(CCH16)
		ccr24_part2 = des_2.encrypt(CCH16)
		ccr24_part3 = des_3.encrypt(CCH16)
		ccr24_guess = ByteToHex(ccr24_part1 + ccr24_part2 + ccr24_part3)
		#print "   ccr24 --> ", ccr24_guess  #DEBUG
		#print "CCR24 -----> ", CCR24, "\n"  #DEBUG
		
		# Compare the guess (ccr24_guess) with the original (CCR24).
		if ccr24_guess == CCR24:
			return guess
	
	# If no password found, return None
	return "FAILED - dictionary exhausted..."
开发者ID:lutzra,项目名称:MSCHAPv2_Cracker,代码行数:49,代码来源:MSCHAPv2_cracker.py

示例14: nt

 def nt(self):
     try:
         try:
             import smbpasswd
             hash =  smbpasswd.nthash(self.password)
         except:
             from Crypto.Hash import MD4
             hash = MD4.new(self.password.encode("utf-16-le")).hexdigest().upper()
         self.out['nt'] = {
             'header': '{nt}',
             'salt': None,
             'hash': hash }
         return hash
     except:
         return None
开发者ID:renard,项目名称:python-cw-hashes,代码行数:15,代码来源:__init__.py

示例15: decrypt_file

	def decrypt_file(self, filename, bdata=True):
		'''
		Decrypt a file from the Briefcase and return all the original data, if needed.
		'''
		if not self._user_id:
			print('Cannot decrypt file! Must sign-in first!')
			return False

		fd = self._get_file_info(filename)

		encr  = fd['encr']
		fname = fd['fname']
		salt   = fd['salt']
		labels = json.loads( self._decrypt(fd['labels'], salt) )
		date   = fd['ctime']
		fhash  = fd['hash']
		bprev  = fd['preview']

		bprev = self._decrypt(bprev, salt)

		# Maybe the data should not be decrypted? It's faster this way!
		if bdata:

			if not fd['included']:
				path = os.path.split(self._filename)[0] + os.sep + encr
				bdata = open(path, 'rb').read()
			else:
				bdata = fd['data']

			bdata = self._decrypt(bdata, salt)

			if fd['compressed']:
				bdata = zlib.decompress(bdata)

			if fhash != MD4.new(bdata).digest():
				print("Invalid decrypt! The hash doesn't match!")
				return False

		return {
			'labels' : labels,
			'ctime'  : date,
			'salt'   : salt,
			'compressed': fd['compressed'],
			'included': fd['included'],
			'hash'    : fhash,
			'preview' : bprev,
			'data'    : bdata
		}
开发者ID:croqaz,项目名称:priv-briefcase,代码行数:48,代码来源:priv_briefcase.py


注:本文中的Crypto.Hash.MD4类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。