Python MD5, ASE, RSA encryption and decryption implementation

1. MD5 encryption

The implementation of MD5 encryption in python is mainly done through hashlib, and the encrypted code is fixed. It is an irreversible operation. The result of encrypting different data is a fixed-length 32-bit and 16-bit character python code. The implementation is as follows:

import hashlib


def hasmd5(arg):
    # 将数据转换成UTF-8格式
    se = hashlib.md5(arg.encode('utf-8'))
    # 将hash中的数据转换成只包含十六进制的数字
    result = se.hexdigest()
    return result


if __name__ == '__main__':
    print(hasmd5('123abc'))

>> a906449d5769fa7361d7ecc6aa3f6d28

2. AES symmetric encryption

In digital encryption algorithms, encryption can be divided into symmetric encryption and asymmetric encryption.

In the symmetric encryption algorithm, encryption and decryption use the same key, that is: use the same key to encrypt and decrypt the same password

dense;

The encryption process is as follows:

Encryption: original text + key = cipher text

Decryption: ciphertext - key = original text

Online encryption tool: https://www.lddgo.net/encrypt/aes

pip install:

pip install pycryptodome

Code:

# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES


class EncryptDate:
    def __init__(self, key):
        self.key = key.encode('utf-8')  # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小,为16位
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的实例
        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 encrypt(self, encrData):
        res = self.aes.encrypt(self.pad(encrData).encode('utf-8'))
        # Base64是网络上最常见的用于传输8Bit字节码的编码方式之一
        msg = str(base64.b64encode(res), encoding='utf-8')
        return msg

    # 解密函数
    def decrypt(self, decrData):
        res = base64.decodebytes(decrData.encode('utf-8'))  # 转为二进制字节流
        msg = self.aes.decrypt(res).decode('utf-8')
        return self.unpad(msg)   # 把之前为了填充为16位多余的那部分截掉


if __name__ == '__main__':
    print("============加密==================")
    key = "1234567812345678"  # key 密码,服务器指定
    data = "tony"  # 数据
    eg = EncryptDate(key)  # 这里密钥的长度必须是16的倍数
    res1 = eg.encrypt(data)
    print(res1)
    print("============解密==================")
    res2 = eg.decrypt(res1)
    print(res2)

>> ============加密==================
>> XbXHJrNLwoTVcyfqM9eTgQ==
>> ============解密==================
>> tony

Three, rsa asymmetric encryption

Symmetric encryption uses the same key for encryption and decryption. Then, asymmetric encryption naturally uses different keys for encryption and decryption. Asymmetric encryption has two keys, a public key (Public Key) and a private key (Private Key). The public key and the private key exist in pairs. If the original text is encrypted with the public key, only the corresponding private key can be used to decrypt it; because the encryption and decryption do not use the same key, this algorithm is called non- Symmetric encryption algorithm. The key of an asymmetric encryption algorithm is a long string of random numbers obtained through a series of algorithms. Generally, the longer the length of the random number, the more secure the encrypted information. The public key can be derived from the private key through a series of algorithms, that is, the public key exists based on the private key. However, the private key cannot be reversed through the public key. This process is one-way.

Online encryption tool: http://rsa.bchrt.com/

Python code implementation:

# -*- coding: utf-8 -*-
import base64
import rsa

# 秘钥的位数, 可以自定义指定, 例如: 128、256、512、1024、2048等
(pubkey, privkey) = rsa.newkeys(512)
# 生成公钥
pub = pubkey.save_pkcs1()

# 将公钥保存到文件中
# with open('public.pem', 'wb') as f:
#     f.write(pub)

# 生成私钥
pri = privkey.save_pkcs1()

# 将私钥保存到文件中
# with open('private.pem', 'wb') as f:
#     f.write(pri)


class Rsa():
    def __init__(self):
        self.pub_key = rsa.PublicKey.load_pkcs1(pub)
        self.priv_key = rsa.PrivateKey.load_pkcs1(pri)

    def encrypt(self, text):
        # rsa加密 最后把加密字符串转为base64
        text = text.encode("utf-8")
        cryto_info = rsa.encrypt(text, self.pub_key)
        cipher_base64 = base64.b64encode(cryto_info)  # 输出的为byte类型的base64
        cipher_base64 = cipher_base64.decode()  # 转为str类型的base64
        return cipher_base64

    def decrypt(self, text):
        # rsa解密 返回解密结果
        cryto_info = base64.b64decode(text)  # 将base64转为二进制byte字节
        talk_real = rsa.decrypt(cryto_info, self.priv_key)
        res = talk_real.decode("utf-8")
        return res


if __name__ == "__main__":
    rsaer = Rsa()
    info = rsaer.encrypt('测试非对称加密')
    print('加密:', info)
    print('解密:', rsaer.decrypt(info))

>> 加密: N0sl/zKIM9b3e282XX/7wTDwqnjgTj9yrVwpCgndhw30Z5y7r2RcL1zsajzUt9opznEdb3p9aDe7UVrSGtmy7w==
>> 解密: 测试非对称加密
 

Guess you like

Origin blog.csdn.net/qq_38571773/article/details/128805077