python——加密

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

  1. 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]
  1. 构建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
  1. 组合
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值