1. 程式人生 > >python 中的一些加密解密方法

python 中的一些加密解密方法

因為遇到了加密解密的問題,翻看了一些關於此的博文,所以想在粗略的學習後記錄下來,回顧以前並且加深印象。在以後的學習中再精細的雕琢。

基礎的MD5加密

MD5 是一種單向加密技術(不可解密)。MD5加密演算法簡單高效且
算出的值長度都是固定的, MD5值具有強抗碰撞,對原檔案哪怕只修改一個字元,所計算出的MD5值也會發生很大變化。
基於這些特性,MD5在資料校驗上發揮有很大作用。

PYTHON 中 MD5 有兩種生成方式

import md5

text = 'hello everyone !'
m = md5.new() 
m.update(text)
res = m.hexdigest()
print
res # 31b0c70dac41ed7ce0d185213275ae64

在python3中已經廢除了MD5模組,推薦使用下面這種

import hashlib

text = 'hello everyone !'
m = hashlib.md5()
m.update(text)
print m.hexdigest()
# 31b0c70dac41ed7ce0d185213275ae64

SHA-1加密

與MD5類似,都屬於hash演算法,sha1加密相對於MD5加密要更安全些,但是效率相對於MD5會低一些。

import hashlib
text = "hello world !"
sha = hashlib.sha1(text) print sha.hexdigest() # 05966204d726546ea43af951e0c417d75dd5ac3c

HAMC 加密

hamc 同樣是基於hash演算法,與上面兩個加密不同的是,hamc加密是以一個金鑰和一個訊息作為輸入,生成一個訊息摘要輸出。
主要用於身份驗證。

import hmac,hashlib
h = hmac.new(key='key',msg='hello')
h.update('world!')
ret = h.hexdigest()
print ret
# 774bd7473ce15ec74c015338cbf2d421

base64加密

base64編碼方法簡單,但是卻並不保險,別人很容易就能獲取原始資料,通常是用來對檔案進行一種格式化的操作。它是一種雙向加密

import base64
s = base64.b64encode("hello world !")
print s
# aGVsbG8gd29yZCAh
s1 = base64.b64decode(s)
print s1
# hello world !

AES 雙向對稱加密解密

AES 只是個基本演算法,實現AES有若干模式,而安全性較好的是CBC模式。cbc使用密碼和salt按固定演算法(md5)產生key和iv加密和解密。

from Crypto.Cipher import AES
import base64

class prpcrypt(object):
    def __init__(self,key=')[email protected]$k$w'):
        self.key = key
        self.mode = AES.MODE_CBC

    # cryptographic functions
    def encrypt(self,text):
        cryptor = AES.new(self.key,self.mode,self.key)
        length = 16
        count = len(text)
        add = length - (count % length)
        text = text + ('\0'*add)
        self.ciphertext = cryptor.encrypt(text)
        return base64.b64encode(self.ciphertext)


    def decrypt(self,text):
        cryptor = AES.new(self.key, self.mode, self.key)
        plain_text = cryptor.decrypt(base64.b64decode(text))
        print plain_text
        print plain_text.rstrip('\0')
        return 'ok'

a = prpcrypt()
text = a.encrypt("hello world!")
print text
a.decrypt(text)