1.md5
import hashlib
m = hashlib.md5()
s1 = "hello"
m.update(s1.encode(encoding='utf_8'))
print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592
#再次加密
s2 = "shitou"
m.update(s2.encode(encoding='utf_8'))
print(m.hexdigest()) #0893c52f33f9b8ec0f8cf809c880b3d0
#两次加密相当于一次转换,拼接字符串进行加密
m2 = hashlib.md5()
s = "helloshitou"
m2.update(s.encode(encoding='utf_8'))
print(m2.hexdigest()) #0893c52f33f9b8ec0f8cf809c880b3d0
2.sha
越来越安全,但是计算时间越长
import hashlib
h1 = hashlib.sha1()
h1.update("hello".encode("utf8"))
print(h1.hexdigest()) #aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
h2 = hashlib.sha224()
h2.update("hello".encode("utf8"))
print(h2.hexdigest()) #ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193
3.base64
import base64
s = "123数据"
#加密
s1 = base64.b64encode(s.encode(encoding='utf_8'))
print(s1) #b'MTIz5pWw5o2u'
#解密
s2 = str(base64.b64decode(s1),"utf_8")
print(s2) #123数据
4. pyCryptodome
pip install pyCryptodome
4.1DES加密
from Crypto.Cipher import DES
import binascii #binascii模块包含很多在二进制和ASCII编码的二进制表示转换的方法
#密钥长64位
key = b'abcddesw'
def pad(text):
#加密函数,如果text长度不是8的倍数,补足
while(len(text) % 8 != 0):
text+=' '
return text
#创建DES实例
des = DES.new(key, DES.MODE_ECB)
text = "I'm china!"
padded_text = pad(text)
#加密
encryted_text = des.encrypt(padded_text.encode(encoding='utf_8'))
print(encryted_text) #b'\x04mp5.\xac\xd5\xa76M\xc6>s\x95F\xa4'
#解密
t = str(des.decrypt(encryted_text.strip()), "utf_8")
print(t) #I'm china!
# b'\x04mp5.\xac\xd5\xa76M\xc6>s\x95F\xa4'
# I'm china!
5.js加密和pytho加密代码转换
var encrypt = function (t, e) {
t = CryptoJS..SHA256(t).toString(CryptoJS..enc.HEX).substr(0, 16);
var n = CryptoJS..enc.Utf8.parse(t),
i = CryptoJS..enc.Utf8.parse(e);
return CryptoJS..AES.encrypt(i, n, {
mode: CryptoJS..mode.ECB,
padding: CryptoJS..pad.Pkcs7
}).toString()
}
转为python
- t = CryptoJS…SHA256(t).toString(CryptoJS…enc.HEX).substr(0, 16);
def encrypt_authToken(t):
encrypt_str = hashlib.sha256()
encrypt_str.update(token.encode())
encrypt_token = encrypt_str.hexdigest()
return encrypt_token[0:16]
- 构建pad
def make_pad(e):
BLOCK_SIZE = 16
pad = e+ (BLOCK_SIZE - len(e) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(e) % BLOCK_SIZE)
return pad
- 组合
def encrypt(t, e):
mode = AES.MODE_ECB
key = encrypt_authToken(t).encode("utf8")
cryptos = AES.new(key, mode)
cipher_text = cryptos.encrypt(make_pad(e).encode("utf8"))
cipher_text = base64.b64encode(cipher_text).decode("utf8")
encrypt_desc = cipher_text.replace('\n', '');
return encrypt_desc