python常见加密算法实现

base64加密

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。

import base64
#base64加密
def encode_base64(val):
    ret = base64.b64encode(val)
    return ret

#base64解密
def decode_base64(val):
    ret = base64.b64decode(val)
    return ret
常见哈希加密算法

哈希算法又叫散列算法,是将任意长度的二进制值映射为较短的固定长度的二进制值,这个小的二进制值称为哈希值。它的原理其实很简单,就是把一段交易信息转换成一个固定长度的字符串,MD5和SHA256可以说是应用最广泛的Hash算,而且哈希算法都是不可逆的。
hashlib有七种哈希算法库可以自己尝试。

import hashlib
#MD5算法实现
def Md5(val):
    md5 = hashlib.md5()
    md5.update(val.encode("UTF-8"))
    ret = md5.hexdigest()
    return ret


# sha256算法实现
def Sha256(val):
    sha256 = hashlib.sha256()
    sha256.update(val.encode("UTF-8"))
    ret = sha256.hexdigest()
    return ret

经典非对称加密RSA

RSA是最常见的非堆成加密, RSA算法属于分组加密方案,也就是说明文以分组为单位加密,分组的大小取决于所选的模n的值,明文块每个分组的长度可以相同也可以不同,但是,各分组大小必须小于或等于log2(n)的值。已知明文的某块分组报文M,公钥(e,n),私钥(d,n),则加密过程如下:对M的e次方幂指数运算结果再做模n运算,所得结果即为密文C。

import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA


# ------------------------生成密钥对------------------------
def create_rsa_pair(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(file_path="crypto_public_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b


def read_private_key(file_path="crypto_private_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b


# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
    # 字符串指定编码(转为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(text_encrypted_base64: str, private_key: bytes):
    # 字符串指定编码(转为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__':
    # 生成密钥对
    
    public_key, private_key = create_rsa_pair(is_save=False)

    # 加密
    text = '123456'
    text_encrypted_base64 = encryption(text, public_key)
    print('密文:', text_encrypted_base64)

    # 解密
    text_decrypted = decryption(text_encrypted_base64, private_key)
    print('明文:', text_decrypted)

常见对称加密算法AES

设 AES 加密函数为 E,则 C = E(K, P),其中 P 为明文,K 为密钥,C 为密文。也就是说,把明文 P 和密钥 K 作为加密函数的参数输入,则加密函数 E 会输出密文 C。

from Crypto.Cipher  import AES
import base64

# 密钥(key), 密斯偏移量(iv) CBC模式加密
BLOCK_SIZE = 16  # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]

vi = '0102030405060708'

def AES_Encrypt(key, data):
    data = pad(data)
    # 字符串补位
    cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
    encryptedbytes = cipher.encrypt(data.encode('utf8'))
    # 加密后得到的是bytes类型的数据,使用Base64进行编码,返回byte字符串
    encodestrs = base64.b64encode(encryptedbytes)
    # 对byte字符串按utf-8进行解码
    enctext = encodestrs.decode('utf8')
    return enctext


def AES_Decrypt(key, data):
    data = data.encode('utf8')
    encodebytes = base64.decodebytes(data)
    # 将加密数据转换位bytes类型数据
    cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
    text_decrypted = cipher.decrypt(encodebytes)
    # 去补位
    text_decrypted = unpad(text_decrypted)
    text_decrypted = text_decrypted.decode('utf8')
    print(text_decrypted)
    return text_decrypted

if __name__ == '__main__':
    key = 'ILoveyou_5201314'
    data = 'I Love you'
    enctext = AES_Encrypt(key, data)
    print(enctext)
    AES_Decrypt(key, enctext)

上述的pad就是填充模式可以使用函数代替。

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex


mykey='ILoveyou_5201314'

# 如果text不足16位的倍数就用空格补足为16位
def add_to_16(text):
    if len(text.encode('utf-8')) % 16:
        add = 16 - (len(text.encode('utf-8')) % 16)
    else:
        add = 0
    text = text + ('\0' * add)
    return text.encode('utf-8')


# 加密函数
def encrypt(text):
    key = add_to_16(mykey).decode('utf-8')
    mode = AES.MODE_CBC
    iv = add_to_16('12345678').decode("utf-8")
    text = add_to_16(text)
    cryptos = AES.new(key, mode, iv)
    cipher_text = cryptos.encrypt(text)
    # 因为AES加密问题,所以这里转为16进制字符串
    return b2a_hex(cipher_text)


# 解密后,去掉补足的空格用strip() 去掉
def decrypt(text):

    key = add_to_16(mykey).decode('utf-8')
    iv = add_to_16('12345678').decode("utf-8")
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    plain_text = cryptos.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')

mystr="hello world!"


if __name__ == '__main__':
    #e = encrypt("hello world")  # 加密
    e = encrypt(mystr)  # 加密
    d = decrypt(e)  # 解密
    print("加密:", e)
    print("解密:", d)
国产哈希算法sm系列

安装国产哈希算法库

pip install snowland-smx 

有时候会安装补上,那就需要去gitee找到源码运行如下命令安装

 python setup.py install 

代码:

from pysmx.SM3 import SM3
def Sm3(val):
	sm3 = SM3()
	sm3.update(val)
	ret = sm3.hexdigest()
	return ret

你可能感兴趣的:(爬虫,加密算法,python,python,安全,哈希算法,网络爬虫)