Python implementation of common encryption algorithms

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only, and do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it by yourself

Python free learning materials, codes and exchange answers click to join


Living in the era of highly developed informatization, people's awareness of information security and confidentiality is also constantly increasing. In the process of network data transmission, it is often necessary to encrypt sensitive data to ensure data security.

This article mainly introduces Base64, MD5, SHA-1, HMAC, DES/AES, RSA these encryption algorithms and python implementation code examples. The commonly used encryption methods basically have corresponding Python libraries, and you only need to call the specific method to use.

Base64 encryption

The simplest encryption method, no key, as long as you get the ciphertext, you can directly decrypt it. Generally, it is not used alone, and it can be mixed with other encryption methods as a layer of external packaging.

Python免费学习资料、代码以及交流解答:1136201545



import base64

# 要加密的字符串
str_encrypt = 'hello!'
# 加密方法
# 转化为byte类型
base64_encrypt = base64.b64encode(str_encrypt.encode())
# 将字节串转为字符串
base64_encrypt_str = base64_encrypt.decode()

print("BASE64加密串:", base64_encrypt_str, type(base64_encrypt_str))

#解密方法
# 字符串转为字节串
base64_decrypt = base64_encrypt_str.encode()
# 得到加密的字符串
str_decrypt = base64.b64decode(base64_decrypt).decode()
print("BASE64解密串:", str_decrypt, type(str_decrypt))

BASE64 encrypted string: aGVsbG/vvIE= <class'str'>
BASE64 decrypted string: hello! <class'str'>

MD5 encryption

MD5 Message-Digest Algorithm (MD5 Message-Digest Algorithm), with high security, can produce a 128-bit (16-byte) hash value (hash value), which corresponds to any string can be encrypted into a segment The unique fixed-length code is used to ensure complete and consistent information transmission. The current MD5 encryption algorithm is irreversible. Of course, the ciphertext encrypted in this way does not need to be decrypted, just send the original ciphertext directly when needed.

Python code:

import hashlib

str_encrypt = "hello!"
# 对要加密的字符串进行加密
hash = hashlib.md5(str_encrypt.encode())
hash.update(str_encrypt.encode("utf8"))
value = hash.digest()
# 二进制
print("二进制的字符串", repr(value))

# 十六进制
print("十六进制的字符串", hash.hexdigest())

Binary string: b'%\xe2\n\x04\x86\xa7\xf4\xc5Y@\xfa\xc7\xd6\xdc\t_'
Hexadecimal string: 25e20a0486a7f4c55940fac7d6dc095f

SHA1 encryption

The Secure Hash Algorithm is mainly applicable to the Digital Signature Algorithm DSA defined in the Digital Signature Standard DSS. SHA1 is based on MD5, and SHA1 is more secure than MD5. For messages less than 2^64 bits in length, SHA1 will generate a 160-bit message digest.

Digital signature can be realized through hash algorithm. The principle of digital signature is to convert the plaintext to be transmitted into a message digest through a function operation (Hash). The message digest is encrypted and sent to the recipient together with the plaintext, and the recipient will accept it. The new message digest generated by the plaintext is decrypted and compared with the sender's message digest. If it is inconsistent, the plaintext has been tampered with.

Python code:

import hashlib

str_encrypt = "hello!"

# 对要加密的字符串进行加密
hash = hashlib.sha1(str_encrypt.encode())
hash.update(str_encrypt.encode("utf8"))
value = hash.hexdigest()

# 十六进制
print("十六进制的字符串",value)

Hexadecimal string b8b92f40e0c5df69dcf5cdc1e327e1f87188aeb9

HMAC encryption

Hash Message Authentication Code (Hash Message Authentication Code), HMAC encryption algorithm is a secure message authentication protocol based on encrypted hash function and shared key.

The realization principle is to use the public function and the key to generate a fixed-length value as the authentication identifier, and use this identifier to authenticate the integrity of the message.

Python code:

import hmac
import hashlib

str_encrypt = "hello!"
key="abc"
# 第一个参数是密钥key,第二个参数是待加密的字符串,第三个参数是hash函数

mac = hmac.new(key.encode(encoding="utf-8"),str_encrypt.encode("utf8"),hashlib.md5)

value=mac.hexdigest()  # 加密后字符串的十六进制格式

# 十六进制
print("十六进制的字符串",value)

Hexadecimal string 221479c27474cdf1ee245ffef26cfeee

DES encryption

Data Encryption Standard (Data Encryption Standard) is a symmetric encryption algorithm. It is a block algorithm that uses a key to encrypt. There are three interface parameters: Key, Data, Mode, Key is the working key; Data is 8 bytes and 64 bits, which is the data to be encrypted or decrypted; Mode working mode: encryption or decryption.

Python code:

import binascii
from pyDes import des, CBC, PAD_PKCS5
# 需要安装 pip install pyDes

#加密过程
def des_encrypt(secret_key,s):
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(s, padmode=PAD_PKCS5)
    return binascii.b2a_hex(en)

#解密过程
def des_decrypt(secret_key, s):
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
    return de

secret_str = des_encrypt('12345678', 'hello!')
print(secret_str)

clear_str = des_decrypt('12345678', secret_str)
print(clear_str)

b'7c48af7e37ecd280'

b'hello!'

AES encryption

Advanced Encryption Standard (Advanced Encryption Standard), also known as Rijndael encryption method, is a block encryption standard adopted by the US Federal Government. There are certain requirements for the encryption speed and the number of bytes of the key. The minimum support for the AES key length is 128, 192, 256, and the encryption block packet length is 128 bits. You need to know the key to decrypt it.
Use the command pip3 install pycryptodome to install pycryptodome

The four modes of block cipher encryption are ECB, CBC, CFB, OFB. The most common ones are ECB and CBC.
1. ECB mode
Group the plaintext, each group of plaintext obtains the ciphertext through the encryption algorithm and the key bit operation, and then connect the calculated ciphertext together in order, and each piece of data does not affect each other.
2. CBC mode (the most used mode)
CBC mode requires an initialization vector iv (a string equal to the key length), which is generally obtained through a key generator.
The encryption steps are as follows:
1) First group the data to get D1D2...Dn
2) The first group of data D1 and the initialization vector iv bit operation result are encrypted to obtain the first group of ciphertext C1
3) The second group of data D2 and the first group of The result of the encryption result C1 bit operation is encrypted to obtain the second set of ciphertext C2
4) and the data after 4)
is deduced by analogy to obtain Cn 5) Connected in order to C1C2C3...Cn is the encryption result.
Features:
1. It is not easy to attack actively, its security is better than ECB, and it is suitable for transmitting long-length messages. It is the standard of SSL and IPSec. Each ciphertext block depends on all information blocks, a change in the plaintext message will affect all ciphertext blocks
2. The sender and receiver need to know the initialization vector
3. The encryption process is serial and cannot be parallelized (in When decrypting, one plaintext block can be obtained from two adjacent ciphertext blocks. Therefore, the decryption process can be parallelized.)
4. The initialization vector must be the same during decryption

Python code:

ECB encryption mode

import base64
from Crypto.Cipher import AES

#ECB加密模式

import base64
from Crypto.Cipher import AES


#使用补0方法

# # 需要补位,补足为16的倍数
def add_to_16(s):
    while len(s) % 16 != 0:
        s += '\0'
    return str.encode(s)  # 返回bytes

# 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
key = 'abc4567890abc458'
# 待加密文本
text = 'hello'
# 初始化加密器
aes = AES.new(add_to_16(key), AES.MODE_ECB)
# 加密
encrypted_text = str(base64.encodebytes(aes.encrypt(add_to_16(text))), encoding='utf8').replace('\n', '')
# 解密
decrypted_text = str(
    aes.decrypt(base64.decodebytes(bytes(encrypted_text, encoding='utf8'))).rstrip(b'\0').decode("utf8"))

print('加密值:', encrypted_text)
print('解密值:', decrypted_text)

Encrypted value: p3i7p25Ypel2X2yrFG4rCQ==
Decrypted value: hello

CBC encryption mode (1)

#CBC加密模式
import base64
from Crypto.Cipher import AES
from urllib import parse

AES_SECRET_KEY = 'helloBrook2abcde'  # 此处16|24|32个字符
IV = 'helloBrook2abcde' 


# padding算法

BS = len(AES_SECRET_KEY)

# 填充方案
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

# 解密时删除填充的值

unpad = lambda s: s[0:-ord(s[-1:])]

def cryptoEn(string, key, iv):

# param string: 原始数据
# param key: 密钥
# param iv: 向

    mode = AES.MODE_CBC

    cipher = AES.new(key.encode("utf8"),mode,iv.encode("utf8"))

    encrypted = cipher.encrypt(bytes(pad(string), encoding="utf8"))

    return base64.b64encode(encrypted).decode("utf-8")


#CBC模式的解密代码

def cryptoDe(destring, key, iv):

# param destring: 需要解密的数据
# param key: 密钥
# param iv: 向量

    mode = AES.MODE_CBC
    
    decode = base64.b64decode(destring)

    cipher = AES.new(key.encode("utf8"),mode,iv.encode("utf8"))

    decrypted = cipher.decrypt(decode)

    return unpad(decrypted).decode("utf-8")


secret_str = cryptoEn('hello', AES_SECRET_KEY,IV)
print(secret_str)

clear_str = cryptoDe(secret_str.encode("utf8"), AES_SECRET_KEY,IV)
print(clear_str)

sqlpZ0AdaRAOQRabchzltQ==
hello

CBC encryption mode (two)

import base64
from Crypto.Cipher import AES
from urllib import parse

AES_SECRET_KEY = 'helloBrook2abcde'  # 此处16|24|32个字符
IV = 'helloBrook2abcde' 

# padding算法
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1:])]


class AES_ENCRYPT(object):
    def __init__(self):
        self.key = AES_SECRET_KEY
        self.mode = AES.MODE_CBC

    # 加密函数
    def encrypt(self, text):
        cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
        self.ciphertext = cryptor.encrypt(bytes(pad(text), encoding="utf8"))
        # AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码
        return base64.b64encode(self.ciphertext).decode("utf-8")

    # 解密函数
    def decrypt(self, text):
        decode = base64.b64decode(text)
        cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
        plain_text = cryptor.decrypt(decode)
        return unpad(plain_text).decode("utf-8")


if __name__ == '__main__':
    aes_encrypt = AES_ENCRYPT()
    text = "Python"
    e = aes_encrypt.encrypt(text)
    d = aes_encrypt.decrypt(e)
    print(text)
    print(e)
    print(d)

String to be encrypted: Python
encrypted value: X09JC6IqnsDFp9b9C57cUA==
decrypted value: Python

If the string contains Chinese, first convert the text to ascii code, it will support Chinese encryption

text = base64.b64encode(text.encode('utf-8')).decode('ascii')

RSA encryption

Rivest-Shamir-Adleman, RSA encryption algorithm is an asymmetric encryption algorithm. Public key encryption, private key decryption, RSA is widely used in public key encryption and electronic commerce. The most important encryption algorithm at the moment!

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/114668524