加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

PYTHON 的MD5和CRC32计算方法

(2011-05-07 20:39:05)
标签:

it

分类: Python
#===================================
# CODE LIB

# COD STRTOMD5 字符串计算MD5
def cod_str2md5(instr):
    import hashlib
    umd5str=hashlib.md5(instr)
    return str(umd5str.hexdigest())

# COD FILETOMD5 计算文件的MD5
def cod_file2md5(filepathname):
    import hashlib
    try:
        umd5str=hashlib.md5()    
        #需要使用二进制格式读取文件内容
        ufile = open(unicode(filepathname,'utf8'), 'rb')
        umd5str.update(ufile.read())
        uoutstr=str(umd5str.hexdigest())
        ufile.close()
        return uoutstr
    except:
        return ''

def cod_str2crc32(instr):
    m_pdwCrc32Table = [0 for x in range(0,256)]
    dwPolynomial = 0xEDB88320;
    dwCrc = 0
    for i in range(0,255):
        dwCrc = i
        for j in [8,7,6,5,4,3,2,1]:
            if dwCrc & 1:
                dwCrc = (dwCrc >> 1) ^ dwPolynomial
            else:
                dwCrc >>= 1
        m_pdwCrc32Table[i] = dwCrc
    dwCrc32 = 0xFFFFFFFFL
    for i in instr:
        b = ord(i)
        dwCrc32 = ((dwCrc32) >> 8) ^ m_pdwCrc32Table[(b) ^ ((dwCrc32) & 0x000000FF)]
    dwCrc32 = dwCrc32 ^ 0xFFFFFFFFL
    return dwCrc32

def cod_str2crc32x(instr):
    import binascii
    return binascii.crc32(instr)

def cod_file2crc32(filepathname): 
    import binascii
    try: 
        uf = open(unicode(filepathname,'utf8'),"rb") 
        ucrc = binascii.crc32(uf.read()) 
        uf.close()
        if ucrc>0:
            uoutint=ucrc
        else :
            uoutint= ~ ucrc ^ 0xffffffff
        return '%x' % (uoutint)
    except: 
        return ''
#===================================
Stream.Wang 原创

0

阅读 收藏 喜欢 打印举报/Report
前一篇:WIN7 打开 PAE
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有