md5加密

1:给字符串加密

#--encoding='utf-8'--
import hashlib
h=hashlib.md5()
h.update("lorem")
print h.hexdigest()

 2:给文件加密

from hashlib import md5
 
def md5_file(name):
    m = md5()
    a_file = open(name, 'rb')    #需要使用二进制格式读取文件内容
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()
 
if __main__ == '__init__':
    print md5_file('d:/test.txt')

 

3:大文件时这 样作

[python] view plaincopyprint?
#!/usr/bin/python  
#encoding=utf-8  
import io  
import sys  
import hashlib  
import string  
  
def printUsage():  
    print ('''''Usage: [python] pymd5sum.py <filename>''')  
      
def main():  
    if(sys.argv.__len__()==2):  
        #print(sys.argv[1])  
  
        m = hashlib.md5()  
        file = io.FileIO(sys.argv[1],'r')  
        bytes = file.read(1024)  
        while(bytes != b''):  
            m.update(bytes)  
            bytes = file.read(1024)   
        file.close()  
          
        #md5value = ""  
        md5value = m.hexdigest()  
        print(md5value+"\t"+sys.argv[1])  
          
        #dest = io.FileIO(sys.argv[1]+".CHECKSUM.md5",'w')  
        #dest.write(md5value)  
        #dest.close()  
      
    else:  
        printUsage()   
main()

 

你可能感兴趣的:(MD5加密)