1. 程式人生 > >利用 Python 計算MD5值

利用 Python 計算MD5值

  • 文章架構
    article_struct

目的

  • 日常開發中,經常涉及到針對某些值進行加密的情況(隱私資訊,例如密碼等資訊)。
  • 利用 Python 某些模組將 DataFrame(pandas)某列進行MD5加密處理很方便。
  • 利用Python 3 與 Python 2中不同模組處理之間的差異(例如,Python2 MD5模組與Python 3 hashlib模組)。

加密方式

hashlib 模組(Py3 docs
  • Python 2 / Python 3 中均可完成該模組的安裝.
import platform
pv = platform.python_version()
print
(pv) import hashlib deomo_val = 'kngines' md5_val = hashlib.md5(deomo_val.encode('utf8')).hexdigest() print ('src_val : %s \nmd5_val : %s' % (deomo_val,md5_val))
  • Py 2 執行結果
    Py 2

  • Py 3 執行結果
    Py3

  • Help on module hashlib
help('hashlib')  # 檢視該模組詳情
Help on module hashlib:

NAME
    hashlib - hashlib module - A common interface to many hash functions.

MODULE REFERENCE
    https://docs.python.org/3.6
/library/hashlib The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION new(name, data=b''
, **kwargs) - returns a new hash object implementing the given hash function; initializing the hash using the given binary data. Named constructor functions are also available, these are faster than using new(name): md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(), sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256. More algorithms may be available on your platform but the above are guaranteed to exist. See the algorithms_guaranteed and algorithms_available attributes to find out what algorithm names can be passed to new(). NOTE: If you want the adler32 or crc32 hash functions they are available in the zlib module. Choose your hash function wisely. Some have known collision weaknesses. sha384 and sha512 will be slow on 32 bit platforms. Hash objects have these methods: - update(arg): Update the hash object with the bytes in arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments. - digest(): Return the digest of the bytes passed to the update() method so far. - hexdigest(): Like digest() except the digest is returned as a unicode object of double length, containing only hexadecimal digits. - copy(): Return a copy (clone) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. For example, to obtain the digest of the string 'Nobody inspects the spammish repetition': >>> import hashlib >>> m = hashlib.md5() >>> m.update(b"Nobody inspects") >>> m.update(b" the spammish repetition") >>> m.digest() b'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' More condensed: >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' CLASSES builtins.object _blake2.blake2b _blake2.blake2s _sha3.sha3_224 _sha3.sha3_256 _sha3.sha3_384 _sha3.sha3_512 _sha3.shake_128 _sha3.shake_256 FUNCTIONS md5 = openssl_md5(...) Returns a md5 hash object; optionally initialized with a string new = __hash_new(name, data=b'', **kwargs) new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be bytes). pbkdf2_hmac(...) pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function. sha1 = openssl_sha1(...) Returns a sha1 hash object; optionally initialized with a string sha224 = openssl_sha224(...) Returns a sha224 hash object; optionally initialized with a string sha256 = openssl_sha256(...) Returns a sha256 hash object; optionally initialized with a string sha384 = openssl_sha384(...) Returns a sha384 hash object; optionally initialized with a string sha512 = openssl_sha512(...) Returns a sha512 hash object; optionally initialized with a string DATA __all__ = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'bla... algorithms_available = {'DSA', 'DSA-SHA', 'MD4', 'MD5', 'MDC2', 'RIPEM... algorithms_guaranteed = {'blake2b', 'blake2s', 'md5', 'sha1', 'sha224'... FILE /root/anaconda3/lib/python3.6/hashlib.py
MD5 模組加密 (Python 2 自帶模組)
  • 注意警告資訊(不推薦使用該方式加密,已廢棄
import md5

src_val = 'kngines'  
mnew = md5.new()  #  Returns a md5 hash object; optionally initialized with a string
mnew.update(src_val)   #  Update this hash object's state with the provided string.
print (mnew.hexdigest())  #  Return the digest value as a string of hexadecimal digits.
  • 執行結果
    deprecation

加密/校驗文字

  • Linux命令 md5sum
[root@localhost xxxx]# md5sum test.log 
9e05895ce1f42385c407f71e5bb84105  test.log
[[email protected] synway]# md5sum --h
Usage: md5sum [OPTION]... [FILE]...
Print or check MD5 (128-bit) checksums.
With no FILE, or when FILE is -, read standard input.

  -b, --binary         read in binary mode
  -c, --check          read MD5 sums from the FILEs and check them
      --tag            create a BSD-style checksum
  -t, --text           read in text mode (default)
  Note: There is no difference between binary and text mode option on GNU system.

The following four options are useful only when verifying checksums:
      --quiet          don't print OK for each successfully verified file
      --status         don't output anything, status code shows success
      --strict         exit non-zero for improperly formatted checksum lines
  -w, --warn           warn about improperly formatted checksum lines

      --help     display this help and exit
      --version  output version information and exit

The sums are computed as described in RFC 1321.  When checking, the input
should be a former output of this program.  The default mode is to print
a line with checksum, a character indicating input mode ('*' for binary,
space for text), and name for each FILE.

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'md5sum invocation'
  • Python 加密文字
import hashlib

f = open('./test.log', 'r')
f_md5 = hashlib.md5()
f_md5.update(f.read().encode('utf8'))

# f = open('./test.log', 'rb')
# f_md5 = hashlib.md5()
# f_md5.update(f.read())

print (f_md5.hexdigest())
  • 執行結果
    MD5加密

References

相關推薦

利用 Python 計算MD5

文章架構 目的 日常開發中,經常涉及到針對某些值進行加密的情況(隱私資訊,例如密碼等資訊)。 利用 Python 某些模組將 DataFrame(pandas)某列進行MD5加密處理很方便。 利用Python 3 與 Python 2中不同模組

java計算MD5

int con ger for 計算 utf-8 string md5值 get package com.linusiyu.common; import java.io.File; import java.io.FileInputStream; import java.

Python計算KS並繪制KS曲線

python KS 大數據 更多風控建模、大數據分析等內容請關註公眾號《大數據風控的一點一滴》 python實現KS曲線,相關使用方法請參考上篇博客-R語言實現KS曲線 代碼如下: ####################### PlotKS ##########################

python計算IV及使用

python 大數據 IV 更多風控建模、大數據分析等內容請關註公眾號《大數據風控的一點一滴》 在對變量分箱後,需要計算變量的重要性,IV是評估變量區分度或重要性的統計量之一,python計算IV值的代碼如下: def CalcIV(Xvar, Yvar): N_0 = np.sum(Y

不要對md5file.read()計算md5

最近遇到的一個問題,我使用以下程式碼對備份檔案計算MD5值: # md5file=open("%s" % outputpath+"/local/oplog.rs.bson", 'rb') # md5=hashlib.md5(md5file.read()).hexdigest() # md5file.c

利用Python計算資料的Pearson相關係數

步驟一:讀取資料 # _*_ coding: utf-8 _*_ import pandas as pd import numpy as np df = pd.read_csv("D:data1.csv",index_col='user_id') 步驟二:異常資料處理(如

利用Python 生成hash

一、介紹 如果在Python中需要對使用者輸入的密碼或者其他內容進行加密,首選的方法是生成hash值。 在Python中可以利用二個模組來進行: - crypt - hashlib 二、crypt (一)crypt的主要方法和常量

python計算md5,sha1,crc32

為了確保從網上下載的檔案或程式完整並且沒有被篡改,一般官網上都會給出檔案的md5或sha1。我們拿到一個軟體,第一步應當是校驗這個值與官網給的是否一致,如果不一致的話就趕緊刪掉吧。 在Mac上

Python計算IV

更多風控建模、大資料分析等內容請關注公眾號《大資料風控的一點一滴》在對變數分箱後,需要計算變數的重要性,IV是評估變數區分度或重要性的統計量之一,python計算IV值的程式碼如下:def CalcIV(Xvar, Yvar): N_0 = np.sum(Yvar=

測試python計算MD5和CRC的速度

大量資料想均勻分佈到不同的資料庫儲存,當前方法將key進行MD5或CRC計算,取最後一位分別對應到相應的儲存位置。測文字17721088行。 兩個指令碼如下: MD5部分 import hashlib import time file_list = open('d

利用Python計算某一年的某一天是星期幾

#計算某特定天使星期幾 #蔡勒公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1import math dict = {1: "星期一", 2: "星期二", 3: "星期三", 4: "星期四", 5: "星期五", 6: "星期六", 0:

Python計算一個目錄下的所有文件的md5,在Linux系統下面

linux md5 python walk hashlib 實現代碼如下:#!/usr/bin/python #*-*coding:utf8*-* import os import sys import hashlib def md5sum(data): with open(d

python選取資料夾,然後計算該資料夾下所有檔案的md5,並列出md5相同的檔案到log中

因為在處理手機相簿的時候,發現有些照片儲存了好多次,為了保證一張圖片不被多次儲存,所以想到通過計算圖片md5值的方式來進行篩選。 圖片的md5值計算,使用python非常方便。 執行該py之後,會有一個對話方塊,通過選擇目錄,即可遍歷該目錄及子目錄下所有檔案,計算出md5值,並將md5值重複

python計算檔案的md5

在Python中內建了md5的實現,就是md5模組,因此可以很簡單的處理比較兩個檔案是否一致的問題。如以下程式碼片斷: import os,sys,md5 f1 = open(’f:/1.txt’,’r’) f2 = open(’f:/1.txt’,’r’) print 

用隨機投擲飛鏢法計算Pi(Randomness Throwing dart Pi Python

targe .html def 技術分享 公開課 9.png pan turn div 畫一個邊長為r的正方形和半徑為r的四分之一的圓(如下圖所示),向上面隨機投擲飛鏢,通過計算落在星星區域和整體區域的飛鏢比例,即可求出π值。 公式推導如下: 假設正方形的邊長r

利用Python進行數據分析_Pandas_匯總和計算描述統計

描述 行數 OS 進行 weight pytho col font gpo 申明:本系列文章是自己在學習《利用Python進行數據分析》這本書的過程中,為了方便後期自己鞏固知識而整理。利用Python進行數據分析_Pandas_匯總和計算描述統計

利用Python叠代器查找最小和最大

urn 最大值 我們 lse dmi tuple 利用 spa 如同 叠代器的用法為for...in.... 叠代器如同for循環,可以遍歷所有的值,但我們熟悉的的語言,都是通過下標完成的,python的循環程度要高於C語言的循環,因為python的叠代不止可以用在Lis

利用Python+ADB打造一款自動點贊和抽獎機制!這款項目多少錢?

adb 漢語 pen stat sdcard -i enc 路徑和 備忘錄 為什麽要做這個呢? 鑒於之前已經有同學實現了自動挖掘抖音美女的案例,所以這個想法終於有了一絲付諸實踐的曙光,潘老師和這位同學一樣使用了Python+ADB的方式來實現。 Python

資料基礎---《利用Python進行資料分析·第2版》第4章 NumPy基礎:陣列和向量計算

之前自己對於numpy和pandas是要用的時候東學一點西一點,直到看到《利用Python進行資料分析·第2版》,覺得只看這一篇就夠了。非常感謝原博主的翻譯和分享。 NumPy(Numerical Python的簡稱)是Python數值計算最重要的基礎包。大多數提供科學計算的包都是用Nu

利用python完成簡單計算

實驗名稱 利用python完成簡單計算 專  業 軟體工程 姓    名      學  號