常見加密算法的Python實現(xiàn)
回復(fù)“書籍”即可獲贈Python從入門到進階共10本電子書
Base64位加密
最簡單的加密方式,無密鑰,只要拿到密文,就可以直接解密,一般情況下不單獨使用,可以和其他加密方式混合使用,作為一層外部包裝。
import?base64
#?要加密的字符串
str_encrypt?=?'hello!'
#?加密方法
#?轉(zhuǎn)化為byte類型
base64_encrypt?=?base64.b64encode(str_encrypt.encode())
#?將字節(jié)串轉(zhuǎn)為字符串
base64_encrypt_str?=?base64_encrypt.decode()
print("BASE64加密串:",?base64_encrypt_str,?type(base64_encrypt_str))
#解密方法
#?字符串轉(zhuǎn)為字節(jié)串
base64_decrypt?=?base64_encrypt_str.encode()
#?得到加密的字符串
str_decrypt?=?base64.b64decode(base64_decrypt).decode()
print("BASE64解密串:",?str_decrypt,?type(str_decrypt))
BASE64加密串: aGVsbG/vvIE=
BASE64解密串: hello!
MD5加密
import?hashlib
str_encrypt?=?"hello!"
#?對要加密的字符串進行加密
hash?=?hashlib.md5(str_encrypt.encode())
hash.update(str_encrypt.encode("utf8"))
value?=?hash.digest()
#?二進制
print("二進制的字符串",?repr(value))
#?十六進制
print("十六進制的字符串",?hash.hexdigest())
二進制的字符串:b'%\xe2\n\x04\x86\xa7\xf4\xc5Y@\xfa\xc7\xd6\xdc\t_'
十六進制的字符串:25e20a0486a7f4c55940fac7d6dc095f
SHA1加密
import?hashlib
str_encrypt?=?"hello!"
#?對要加密的字符串進行加密
hash?=?hashlib.sha1(str_encrypt.encode())
hash.update(str_encrypt.encode("utf8"))
value?=?hash.hexdigest()
#?十六進制
print("十六進制的字符串",value)
十六進制的字符串 b8b92f40e0c5df69dcf5cdc1e327e1f87188aeb9
HMAC加密
import?hmac
import?hashlib
str_encrypt?=?"hello!"
key="abc"
#?第一個參數(shù)是密鑰key,第二個參數(shù)是待加密的字符串,第三個參數(shù)是hash函數(shù)
mac?=?hmac.new(key.encode(encoding="utf-8"),str_encrypt.encode("utf8"),hashlib.md5)
value=mac.hexdigest()??#?加密后字符串的十六進制格式
#?十六進制
print("十六進制的字符串",value)
十六進制的字符串 221479c27474cdf1ee245ffef26cfeee
DES加密
import?binascii
from?pyDes?import?des,?CBC,?PAD_PKCS5
#?需要安裝?pip?install?pyDes
#加密過程
def?des_encrypt(secret_key,s):
????iv?=?secret_key
????k?=?des(secret_key,?CBC,?iv,?pad=None,?padmode=PAD_PKCS5)
????en?=?k.encrypt(s,?padmode=PAD_PKCS5)
????return?binascii.b2a_hex(en)
#解密過程
def?des_decrypt(secret_key,?s):
????iv?=?secret_key
????k?=?des(secret_key,?CBC,?iv,?pad=None,?padmode=PAD_PKCS5)
????de?=?k.decrypt(binascii.a2b_hex(s),?padmode=PAD_PKCS5)
????return?de
secret_str?=?des_encrypt('12345678',?'hello!')
print(secret_str)
clear_str?=?des_decrypt('12345678',?secret_str)
print(clear_str)
b'7c48af7e37ecd280'?
b'hello!'
AES加密
分組密碼加密中的四種模式有ECB、CBC、CFB、OFB。其中最常見的有ECB和CBC。
1、ECB模式
對明文分組,每組明文通過加密算法和密鑰位運算得到密文,之后按照順序?qū)⒂嬎闼玫拿芪倪B在一起即可,各段數(shù)據(jù)之間互不影響。
2、CBC模式(使用最多的模式)
CBC模式需要一個初始化向量iv(和密鑰長度相等的字符串),一般通過密鑰生成器獲取。
加密步驟如下:
1)首先將數(shù)據(jù)分組得到D1D2…Dn
2)第一組數(shù)據(jù)D1與初始化向量iv位運算的結(jié)果進行加密得到第一組密文C1
3)第二組數(shù)據(jù)D2與第一組的加密結(jié)果C1位運算以后的結(jié)果進行加密,得到第二組密文C2
4)之后的數(shù)據(jù)以此類推,得到Cn
5)按順序連為C1C2C3…Cn即為加密結(jié)果。
特點:
1.不容易主動攻擊,安全性好于ECB,適合傳輸長度長的報文,是SSL、IPSec的標(biāo)準(zhǔn)。每個密文塊依賴于所有的信息塊,明文消息中一個改變會影響所有密文塊
2.發(fā)送方和接收方都需要知道初始化向量
3.加密過程是串行的,無法被并行化(在解密時,從兩個鄰接的密文塊中即可得到一個平文塊。因此,解密過程可以被并行化。)
4.解密時初始化向量必須相同
import?base64
from?Crypto.Cipher?import?AES
#ECB加密模式
import?base64
from?Crypto.Cipher?import?AES
#使用補0方法
#?#?需要補位,補足為16的倍數(shù)
def?add_to_16(s):
????while?len(s)?%?16?!=?0:
????????s?+=?'\0'
????return?str.encode(s)??#?返回bytes
#?密鑰長度必須為16、24或32位,分別對應(yīng)AES-128、AES-192和AES-256
key?=?'abc4567890abc458'
#?待加密文本
text?=?'hello'
#?初始化加密器
aes?=?AES.new(add_to_16(key),?AES.MODE_ECB)
#?加密
encrypted_text?=?str(base64.encodebytes(aes.encrypt(add_to_16(text))),?encoding='utf8').replace('\n',?'')
#?解密
decrypted_text?=?str(
????aes.decrypt(base64.decodebytes(bytes(encrypted_text,?encoding='utf8'))).rstrip(b'\0').decode("utf8"))
print('加密值:',?encrypted_text)
print('解密值:',?decrypted_text)
加密值:p3i7p25Ypel2X2yrFG4rCQ==解密值:hello
CBC加密模式(一)
#CBC加密模式
import?base64
from?Crypto.Cipher?import?AES
from?urllib?import?parse
AES_SECRET_KEY?=?'helloBrook2abcde'??#?此處16|24|32個字符
IV?=?'helloBrook2abcde'?
#?padding算法
BS?=?len(AES_SECRET_KEY)
#?填充方案
pad?=?lambda?s:?s?+?(BS?-?len(s)?%?BS)?*?chr(BS?-?len(s)?%?BS)
#?解密時刪除填充的值
unpad?=?lambda?s:?s[0:-ord(s[-1:])]
def?cryptoEn(string,?key,?iv):
#?param?string:?原始數(shù)據(jù)
#?param?key:?密鑰
#?param?iv:?向
????mode?=?AES.MODE_CBC
????cipher?=?AES.new(key.encode("utf8"),mode,iv.encode("utf8"))
????encrypted?=?cipher.encrypt(bytes(pad(string),?encoding="utf8"))
????return?base64.b64encode(encrypted).decode("utf-8")
#CBC模式的解密代碼
def?cryptoDe(destring,?key,?iv):
#?param?destring:?需要解密的數(shù)據(jù)
#?param?key:?密鑰
#?param?iv:?向量
????mode?=?AES.MODE_CBC
????
????decode?=?base64.b64decode(destring)
????cipher?=?AES.new(key.encode("utf8"),mode,iv.encode("utf8"))
????decrypted?=?cipher.decrypt(decode)
????return?unpad(decrypted).decode("utf-8")
secret_str?=?cryptoEn('hello',?AES_SECRET_KEY,IV)
print(secret_str)
clear_str?=?cryptoDe(secret_str.encode("utf8"),?AES_SECRET_KEY,IV)
print(clear_str)sqlpZ0AdaRAOQRabchzltQ==hello
CBC加密模式(二)
import?base64
from?Crypto.Cipher?import?AES
from?urllib?import?parse
AES_SECRET_KEY?=?'helloBrook2abcde'??#?此處16|24|32個字符
IV?=?'helloBrook2abcde'?
#?padding算法
BS?=?len(AES_SECRET_KEY)
pad?=?lambda?s:?s?+?(BS?-?len(s)?%?BS)?*?chr(BS?-?len(s)?%?BS)
unpad?=?lambda?s:?s[0:-ord(s[-1:])]
class?AES_ENCRYPT(object):
????def?__init__(self):
????????self.key?=?AES_SECRET_KEY
????????self.mode?=?AES.MODE_CBC
????#?加密函數(shù)
????def?encrypt(self,?text):
????????cryptor?=?AES.new(self.key.encode("utf8"),?self.mode,?IV.encode("utf8"))
????????self.ciphertext?=?cryptor.encrypt(bytes(pad(text),?encoding="utf8"))
????????#?AES加密時候得到的字符串不一定是ascii字符集的,輸出到終端或者保存時候可能存在問題,使用base64編碼
????????return?base64.b64encode(self.ciphertext).decode("utf-8")
????#?解密函數(shù)
????def?decrypt(self,?text):
????????decode?=?base64.b64decode(text)
????????cryptor?=?AES.new(self.key.encode("utf8"),?self.mode,?IV.encode("utf8"))
????????plain_text?=?cryptor.decrypt(decode)
????????return?unpad(plain_text).decode("utf-8")
if?__name__?==?'__main__':
????aes_encrypt?=?AES_ENCRYPT()
????text?=?"Python"
????e?=?aes_encrypt.encrypt(text)
????d?=?aes_encrypt.decrypt(e)
????print(text)
????print(e)
????print(d)待加密字符串:Python
加密值:X09JC6IqnsDFp9b9C57cUA==
解密值:Python如果字符串包含中文,先對文本轉(zhuǎn)ascii碼,將支持中文加密
text?=?base64.b64encode(text.encode('utf-8')).decode('ascii')
RSA加密
https://www.jianshu.com/p/7a4645691c68小伙伴們,快快用實踐一下吧!如果在學(xué)習(xí)過程中,有遇到任何問題,歡迎加我好友,我拉你進Python學(xué)習(xí)交流群共同探討學(xué)習(xí)。
-------------------?End?-------------------
往期精彩文章推薦:

歡迎大家點贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
想加入Python學(xué)習(xí)群請在后臺回復(fù)【入群】
萬水千山總是情,點個【在看】行不行
/今日留言主題/
隨便說一兩句吧~~
