加解密实战
一.base64
base64总共有64个字符+填充字符=
原理
1.把字符通过ascii码表转成十进制
2.把十进制转成二进制
3.每6位二进制为一组
4.每6位一组的二进制前面全部填充0
5.每8位一组二进制转成10进制
6.根据base64码表转成对应的字符
import base64
# 字符串--->base64字符
sou1 = 'Nfdghyuy'
des1 = base64.b64encode(sou1.encode('utf-8'))
print(des1.decode('utf-8'))
# base64字符--->字符串
des2 = 'TmZkZ2h5dXk='
sou2 = base64.b64decode(des2.encode('utf-8'))
print(sou2.decode('utf-8'))
二.摘要算法
摘要算法也称为哈希算法或散列算法,是一种将任意长度的数据转化为固定长度输出的算法。输出长度固定。无论输入数据的长度如何,输出的摘要(哈希值或散列值)总是固定长度的。例如,MD5和SHA-1算法分别生成128位和160位的哈希值。
- 不可逆性。摘要算法是单向的,意味着无法从摘要中反向推导出原始数据。
- 敏感性。对于输入数据的微小变化,输出的摘要也会显著不同。
- 碰撞抵抗性。理想的摘要算法应难以找到具有相同摘要的不同输入,或者改变输入以产生特定的摘要。
摘要算法的应用包括但不限于数据完整性验证、密码存储、数字签名等。例如,在数字签名中,发送方使用私钥对数据的摘要进行加密,接收方使用公钥解密摘要并验证其与原始数据的摘要是否匹配,以确认数据的完整性和来源。常见的摘要算法包括MD5、SHA-1(已存在漏洞)、SHA-2和SHA-3等。
# 使用md5加密 32位十六进制数 128位二进制
s = 'woniu123'
d = hashlib.md5(s.encode('utf-8')).hexdigest()
print(d)
# 使用sha-1加密
s = 'woniu123'
d = hashlib.sha1(s.encode('utf-8')).hexdigest()
print(d)
三.对称加密
1.古典密码学实现对称加密
案例:字符串’helloWorld’,对该字符串进行大写转成小写,小写转成大写
# 案例:字符串'helloWorld',对该字符串进行大写转成小写,小写转成大写
# 原文:'helloWorld'
# 对称密钥:大写转小写,小写转大写
# 判断哪些字符是大写哪些是小写(ascii表,正则表达式)
def encrypt_1(source):
result = ''
for s in source:
num = ord(s)
# ascii判断大小写字母
if num >= 65 and num <= 90:
num += 32
result += chr(num)
elif num >= 97 and num <= 122:
num -= 32
result += chr(num)
return result
"""
import re
for s in source:
# 正则判断大小写字母
if re.findall('[a-z]', s):
print('小写字母')
elif re.findall('[A-Z]', s):
print('大写字母')
"""
if __name__ == '__main__':
# source = 'helloWorld'
# print(encrypt_1(source))
source1 = 'HELLOwORLD'
print(encrypt_1(source1))
2.现代密码学AES对称加密
# crypto与pycrypto已经没有维护了,所以直接都用 pycryptodome 就行了,安装命令如下
# pip install pycryptodome
# 安装完毕后需要把包名首字母改成大写,如上图
from Crypto.Cipher import AES
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
# AES加密
def encrypt_2(source):
# 1.设置相关的参数
# 模式
mode = AES.MODE_CBC
# 偏移量(16个字节)
vi = b'0123456789abcdef'
# 密钥
key = b'abcdef0123456780'
# 2.要求加密字符串必须是16个字节的倍数,如果不是,需要补足成16的倍数
if len(source.encode('utf-8')) % 16 == 0:
# 需要补位的个数
add_count = 0
else:
# 加密字符串不是16倍数需要补足的位数
add_count = 16 - len(source.encode('utf-8')) % 16
# '\0' 空字节
source = source + '\0' * add_count
# 3.创建加密对象
encrypt_obj = AES.new(key, mode, vi)
# 4.开始加密
encrypt_data = encrypt_obj.encrypt(source.encode('utf-8'))
return b2a_hex(encrypt_data).decode('utf-8')
# AES解密
def decrypt_2(source):
source = a2b_hex(source)
# 1.设置相关的参数
# 模式
mode = AES.MODE_CBC
# 偏移量(16个字节)
vi = b'0123456789abcdef'
# 密钥
key = b'abcdef0123456780'
# 3.创建加密对象
decrypt_obj = AES.new(key, mode, vi)
# 4.开始加密
encrypt_data = decrypt_obj.decrypt(source)
return encrypt_data.decode('utf-8').replace('\0', '')
if __name__ == '__main__':
source = 'helloWorld'
print(encrypt_2(source))
source = 'a1941f40f57c1e869ce4571bdf993844'
print(decrypt_2(source))
四.非对称加密
1.古典密码学实现非对称加密
案例:张三采用凯撒加密算法字母右移动5位,李四采用加密大小写互换,自己只知道自己的加解密算法,不知道对方的加解密算法,张三加密数据发送给李四,李四继续加密数据发送给张三,张三解密,发送给李四,李四解密得到张三发送的原文
# 张三加密
def encrypt_1(source, count):
d = ''
for i in source:
num = ord(i)
num += count
s = chr(num)
d += s
return d
# 李四
def encrypt_2(source):
d = ''
for i in source:
if ord(i) >= 65 and ord(i) <= 90:
num = ord(i)
num += 32
s = chr(num)
d += s
elif ord(i) >= 97 and ord(i) <= 122:
num = ord(i)
num -= 32
s = chr(num)
d += s
else:
d += i
return d
# 张三解密
def encrypt_3(source, count):
d = ''
for i in source:
num = ord(i)
num -= count
s = chr(num)
d += s
return d
if __name__ == '__main__':
source = 'ni hao!'
count = 5
# 张三加密
encrypt_data1 = encrypt_1(source, count)
# 李四加密
encrypt_data2 = encrypt_2(encrypt_data1)
# 张三解密
encrypt_data3 = encrypt_3(encrypt_data2, 5)
# 李四解密
encrypt_data4 = encrypt_2(encrypt_data3)
print(encrypt_data4)
判断一个数是质数
# 1.尝试判断一个数是不是质数
def is_prime(num):
for i in range(2, num):
if num % i == 0:
return False
else:
return True
查出质数分解因子
# 给出一个数,计算2个因子
def product(num): # 1024
count = 0
for i in range(1, num):
for j in range(1, num):
count += 1
# 判断i 和 j本身就需要是质数
if is_prime(i) and is_prime(j) and i * j == num:
print(i, j)
print(count)
# 优化:循环半数即可
def product1(num): # 512
count = 0
for i in range(1, num // 2 + 1):
for j in range(1, num // 2 + 1):
count += 1
# 判断i 和 j本身就需要是质数
if is_prime(i) and is_prime(j) and i * j == num:
print(i, j)
print(count)
# 优化:找到质数因子即可停止循环
def product2(num): # 512
count = 0
for i in range(1, num // 2 + 1):
for j in range(1, num // 2 + 1):
count += 1
print(count)
# 判断i 和 j本身就需要是质数
if is_prime(i) and is_prime(j) and i * j == num:
print(i, j)
print(count)
return
https://www.bilibili.com/video/BV1XP4y1A7Ui/?spm_id_from=333.337.search-card.all.click
2.现代密码学RSA实现非对称加密
RSA 需要额外下载 pip install rsa
import rsa
from binascii import unhexlify, hexlify
source = 'hello world'
# 1.创建出公钥与私钥
pub, priv = rsa.newkeys(512)
print(pub)
print(priv)
# 2.对原始数据进行加密(原文,公钥)
encrypt_data = rsa.encrypt(source.encode('utf-8'), pub)
# print(hexlify(encrypt_data).decode('utf-8'))
# 3.对密文进行解密(密文,私钥)
data = rsa.decrypt(encrypt_data, priv)
print(data.decode('utf-8'))
# 公钥加密,私钥解密 加密传输数据
# 私钥加密,公钥解密 防篡改(摘要算法)