常见的取盐校验加密方式有:md2、md4、md5、md5(hmac)也称带密码的md5、
python实现各种加密:
def md5_encode():
text = "123456"
hl = hashlib.md5()
hl.update(text.encode(encoding='utf8'))
md5 = hl.hexdigest()
print("加密结果:" + str(md5))
def sha1_encode(s: str):
sha = hashlib.sha1(s.encode('utf-8'))
encrypts = sha.hexdigest()
print("sha1加密结果:" + str(encrypts))
def sha256_encode(s: str):
hash = hashlib.sha256()
hash.update(bytes(s, encoding='utf-8'))
encrypts = hash.hexdigest()
print("sha256加密结果:" + str(encrypts))
def sha512_encode(s: str):
hash = hashlib.sha512()
hash.update(bytes(s, encoding='utf-8'))
encrypts = hash.hexdigest()
print("sha512加密结果:" + str(encrypts))
效果图:
采用MD5或者SHA1等散列算法,对明文进行加密。严格来说,MD5不算一种加密算法,而是一种摘要算法。无论多长的输入,MD5都会输出一个128位(16字节)的散列值。而SHA1也是流行的消息摘要算法,它可以生成一个被称为消息摘要的160位(20字节)散列值。MD5相对SHA1来说,安全性较低,但是速度快;SHA1和MD5相比安全性高,但是速度慢。
一些朋友喜欢用123456作为密码来使用,如果威胁行为者拿到了数据库的密码,那么可能很容易被解密。网上有很多号称可以解密MD5的网站https://md5.cn/,我们打开这个网站进行一些简单的测试,看看能否解密MD5。登录账号,输入MD5密文:
e10adc3949ba59abbe56e057f20f883e,点击解密,一下子就得到了解密结果:123456。由此可见,MD5似乎并不是很安全。
密钥散列优缺点:密钥散列具有防篡改的优点,同时它不具备安全性,可认证性。
密钥散列适用场景:普通文件下载
采用单钥密码系统的加密方法,同一个密钥可以同时用作信息的加密和解密,这种加密方法称为对称加密。对称加密算法中常用的算法有:AES、DES、3DES、TDEA、Blowfish、RC2、RC4、RC5、IDEA、SKIPJACK等。
def get_key():
"""
获取随机字符串,充当秘钥
"""
return ''.join([str(random.randint(1, 9)) for _ in range(32)])
class AesTool:
"""
AES加密
key:16个字节
iv:16个字节
注意APP中可能会使用32个字节
"""
def __init__(self, key: bytes):
self.key = key
self.length = AES.block_size
# 截断函数,去除填充的字符
self.un_pad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
en_text = text + (chr(add) * add)
return en_text
def get_aes(self):
return AES.new(self.key, AES.MODE_ECB)
def encrypt(self, text):
_bytes = self.get_aes().encrypt(self.pad(text).encode())
return base64.b64encode(_bytes).decode()
def decrypt(self, text):
_bytes = base64.b64decode(text.encode())
return self.un_pad(self.get_aes().decrypt(_bytes).decode())
aes加密:123456 秘钥:87491434942729926528369989683679 加密结果:CgTEggyvexk4iOstEoiizA==
aes解密:87491434942729926528369989683679 加密后的秘文:CgTEggyvexk4iOstEoiizA== 解密后的明文:123456
效果图如下:
import pyDes
import binascii # 二进制和 ASCII 码互转
class DESTool:
def __init__(self):
"""
# 八位密钥
"""
self.KEY = 'ABCDEFGH'
def des_encrypt(self, text):
"""
# 加密
:param text:
:return:
"""
iv = secret_key = self.KEY
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
data = k.encrypt(text, padmode=pyDes.PAD_PKCS5)
# data.进制返回文本字符串.解码字符串
return binascii.b2a_hex(data).decode()
def des_decrypt(self, text):
"""
# 解密
:param text:
:return:
"""
iv = secret_key = self.KEY
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
data = k.decrypt(binascii.a2b_hex(text), padmode=pyDes.PAD_PKCS5)
return data.decode()
des加密:123456 秘钥:ABCDEFGH 加密结果:942cc4cb17857723
des解密:942cc4cb17857723 秘钥:ABCDEFGH 解密后的明文:123456
des加解密效果图如下:
from Crypto.Cipher import DES3
class Des3Tool():
def __init__(self, key):
self.key = key # 初始化密钥
self.iv = b'01234567' # 偏移量
self.length = DES3.block_size # 初始化数据块大小
self.des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv) # 初始化AES,CBC模式的实例
# 截断函数,去除填充的字符
self.unpad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
def des3_decrypt(self, decrData):
"""
解密
:param encrData:
:return:
"""
res = base64.decodebytes(decrData.encode("utf8"))
# res = bytes.fromhex(decrData)
msg = self.des3.decrypt(res).decode("utf8")
return self.unpad(msg)
def des3_encrypt(self, encrData):
"""
加密
:param encrData:
:return:
"""
res = self.des3.encrypt(self.pad(encrData).encode("utf8"))
msg = str(base64.b64encode(res), encoding="utf8")
# msg = res.hex()
return msg
3des加解密效果图:
对称加密的优缺点:优点是算法公开、计算量小、加密速度快、加密效率高,安全、可认证;缺点是BS网络传输关系,密钥过多难维护,除非对密钥进行加密传输。
对称加密适用场景:收发方数量固定,密钥使用对象少
非对称加密算法是一种密钥的保密方法,它需要两个密钥来进行加密和解密,这两个密钥是公开密钥和私有密钥。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。
非对称加密算法有:RSA、Elgamal、背包算法、Rabin、D-H、ECC(椭圆曲线加密算法)。
其中,RSA有公钥和私钥,即同一个明文可以生成不同密文
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
class RsaTool:
def __init__(self):
pass
def create_rsa_pair(self,is_save=False):
'''
创建rsa公钥私钥对
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私钥
public_key = f.publickey().exportKey() # 生成公钥
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(self,file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(self,file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def encryption(self,text: str, public_key: bytes):
"""
rsa加密
:param public_key:
:return:
"""
# 字符串指定编码(转为bytes)
text = text.encode('utf-8')
# 构建公钥对象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64编码,并转为字符串
text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
return text_encrypted_base64
def decryption(self,text_encrypted_base64: str, private_key: bytes):
"""
rsa解密
:param private_key:
:return:
"""
# 字符串指定编码(转为bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解码
text_encrypted = base64.b64decode(text_encrypted_base64)
# 构建私钥对象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
# 解码为字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
ras_obj = RsaTool()
public_key, private_key = ras_obj.create_rsa_pair(is_save=False)
# 加密
text = '123456'
text_encrypted_base64 = ras_obj.encryption(text, public_key)
print('密文:', text_encrypted_base64)
# 解密
text_decrypted = ras_obj.decryption(text_encrypted_base64, private_key)
print('明文:', text_decrypted)
rsa加解密效果图:
非对称加密的优缺点:优点是安全性更高,公钥是公开的,秘钥是自己保存的,不需要将私钥给别人。缺点是加密和解密花费时间长、速度慢,只适合对少量数据进行加密。
非对称加密适用场景:需要密钥交换的场景,如互联网应用,无法事先约定密钥。
数字签名(又称公钥数字签名)是只有信息的发送者才能产生的别人无法伪造的一段数字串,这段数字串同时也是对信息的发送者发送信息真实性的一个有效证明。它是一种类似写在纸上的普通的物理签名,但是在使用了公钥加密领域的技术来实现的,用于鉴别数字信息的方法。
数字签名的优缺点:优点是运作方式简便、成本低廉,防伪造、防篡改、防抵赖;缺点是不具备足够的保密性。
数字签名适用场景:登录认证
关于常见的加密方式如上所述,不管是哪种加密方式都有自身独特的优点。大家可以根据实际需要,结合各个加密方式的特点,选择适合的加密方式,保护好数据安全,防止数据泄露。
我们可以将明文,翻译成一般人看不懂的其他语言,例如古希腊语、阿拉伯语、梵语等等,即使别人破解了相关秘钥,也很难知道这些语言,如百度翻译中下图所示
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:liangguangchao
# datetime:2022/10/9 19:01
# Email:[email protected]
import base64
import hashlib
import random
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.Cipher import DES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
def md2_encode():
pass
def md4_encode():
pass
def md5_encode(s: str):
hl = hashlib.md5()
hl.update(s.encode(encoding='utf8'))
md5 = hl.hexdigest()
print("md5加密结果:" + str(md5))
def sha1_encode(s: str):
sha = hashlib.sha1(s.encode('utf-8'))
encrypts = sha.hexdigest()
print("sha1加密结果:" + str(encrypts))
def sha256_encode(s: str):
hash = hashlib.sha256()
hash.update(bytes(s, encoding='utf-8'))
encrypts = hash.hexdigest()
print("sha256加密结果:" + str(encrypts))
def sha512_encode(s: str):
hash = hashlib.sha512()
hash.update(bytes(s, encoding='utf-8'))
encrypts = hash.hexdigest()
print("sha512加密结果:" + str(encrypts))
def get_key():
"""
获取随机字符串,充当秘钥
"""
return ''.join([str(random.randint(1, 9)) for _ in range(32)])
class AesTool:
"""
AES加密
key:16个字节
iv:16个字节
注意APP中可能会使用32个字节
"""
def __init__(self, key: bytes):
self.key = key
self.length = AES.block_size
# 截断函数,去除填充的字符
self.un_pad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
en_text = text + (chr(add) * add)
return en_text
def get_aes(self):
return AES.new(self.key, AES.MODE_ECB)
def encrypt(self, text):
_bytes = self.get_aes().encrypt(self.pad(text).encode())
return base64.b64encode(_bytes).decode()
def decrypt(self, text):
_bytes = base64.b64decode(text.encode())
return self.un_pad(self.get_aes().decrypt(_bytes).decode())
import pyDes
import binascii # 二进制和 ASCII 码互转
class DESTool:
def __init__(self):
"""
# 八位密钥
"""
self.KEY = 'ABCDEFGH'
def des_encrypt(self, text):
"""
# 加密
:param text:
:return:
"""
iv = secret_key = self.KEY
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
data = k.encrypt(text, padmode=pyDes.PAD_PKCS5)
# data.进制返回文本字符串.解码字符串
return binascii.b2a_hex(data).decode()
def des_decrypt(self, text):
"""
# 解密
:param text:
:return:
"""
iv = secret_key = self.KEY
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
data = k.decrypt(binascii.a2b_hex(text), padmode=pyDes.PAD_PKCS5)
return data.decode()
from Crypto.Cipher import DES3
class Des3Tool():
def __init__(self, key):
self.key = key # 初始化密钥
self.iv = b'01234567' # 偏移量
self.length = DES3.block_size # 初始化数据块大小
self.des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv) # 初始化AES,CBC模式的实例
# 截断函数,去除填充的字符
self.unpad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
"""
#填充函数,使被加密数据的字节码长度是block_size的整数倍
"""
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
def des3_decrypt(self, decrData):
"""
解密
:param encrData:
:return:
"""
res = base64.decodebytes(decrData.encode("utf8"))
# res = bytes.fromhex(decrData)
msg = self.des3.decrypt(res).decode("utf8")
return self.unpad(msg)
def des3_encrypt(self, encrData):
"""
加密
:param encrData:
:return:
"""
res = self.des3.encrypt(self.pad(encrData).encode("utf8"))
msg = str(base64.b64encode(res), encoding="utf8")
# msg = res.hex()
return msg
class RsaTool:
def __init__(self):
pass
def create_rsa_pair(self,is_save=False):
'''
创建rsa公钥私钥对
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私钥
public_key = f.publickey().exportKey() # 生成公钥
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(self,file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(self,file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def encryption(self,text: str, public_key: bytes):
"""
rsa加密
:param public_key:
:return:
"""
# 字符串指定编码(转为bytes)
text = text.encode('utf-8')
# 构建公钥对象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64编码,并转为字符串
text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
return text_encrypted_base64
def decryption(self,text_encrypted_base64: str, private_key: bytes):
"""
rsa解密
:param private_key:
:return:
"""
# 字符串指定编码(转为bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解码
text_encrypted = base64.b64decode(text_encrypted_base64)
# 构建私钥对象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
# 解码为字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
print("#################### 取盐校验(不可逆)####################")
text = "123456"
md5_encode(text)
sha1_encode(text)
sha256_encode(text)
sha512_encode(text)
#############aes加密################
print("#################### 对称加密 ####################")
key = get_key()
ase_tool = AesTool(key.encode())
cipher = ase_tool.encrypt('123456')
print("ase加密结果:" + str(cipher))
#############aes解密################
# key = '87491434942729926528369989683679'
# send_time_res = ase_tool.decrypt('CgTEggyvexk4iOstEoiizA==')
ase_tool = AesTool(key.encode())
send_time_res = ase_tool.decrypt(cipher)
print("ase解密结果:" + str(send_time_res))
#############des加解密有问题################
DS = DESTool()
encode_str = DS.des_encrypt(text.encode())
print('des加密:', encode_str)
decode_str = DS.des_decrypt(encode_str)
print('des解密:', decode_str)
#############3des加解密################
des3 = Des3Tool("abcdefghijklmnopqrstuvwx") # 这里密钥的长度必须是16的倍数
res = des3.des3_encrypt(text)
print('3des加密:', res)
des3 = Des3Tool("abcdefghijklmnopqrstuvwx")# 这里不能少,否则报错
res = des3.des3_decrypt(res)
print('3des解密:', res)
print("#################### 非对称加密 ####################")
#############rsa加密################
ras_obj = RsaTool()
public_key, private_key = ras_obj.create_rsa_pair(is_save=False)
text_encrypted_base64 = ras_obj.encryption(text, public_key)
print('rsa加密:', text_encrypted_base64)
#############rsa解密################
text_decrypted = ras_obj.decryption(text_encrypted_base64, private_key)
print('rsa解密:', text_decrypted)