# Common encryption methods and python implementation

Time：2021-5-3

Due to the illegal duplication of computer software, the leakage of communication and data security are threatened, so encryption is often used in the development process. It has been applied in some important scenarios, such as login, payment and OAuth. Different scenarios require different signature encryption algorithms to achieve business goals.

### 1. Types of encryption algorithms

Encryption algorithm is distributed column algorithm, symmetric encryption and asymmetric encryption.

(1) Hash algorithm: it is often necessary to verify the integrity of messages. Hash function provides this service. It generates fixed length output for different length input messages. The common algorithms are MD5, Sha, HMAC and so on.

(2) Symmetric encryption: this encryption method is used by both sides to encrypt and decrypt with the same key. The key is the instruction that controls the encryption and decryption process. An algorithm is a set of rules that specify how to encrypt and decrypt. The common symmetry algorithms are AES, DES, 3DES and so on.

(3) Asymmetric encryption: unlike symmetric encryption algorithm, asymmetric encryption algorithm needs two keys: public key and private key. The public key and the private key are a pair. If the public key is used to encrypt the data, only the corresponding private key can be used to decrypt it; If the private key is used to encrypt the data, only the corresponding public key can be used to decrypt. Because encryption and decryption use two different keys, this algorithm is called asymmetric encryption algorithm. The common asymmetric algorithms are RSA, DSA, ECC and so on.

### 2. Implementation of Python

#### 2.1 hash algorithm HMAC, MD5

HMAC takes hmacsha1 as the column and needs HMAC_ The encrypted data is usually encoded in Base64 format.

import hmac
import hashlib
from hashlib import sha1
import base64

def hash_hmac(data, hmac_key):
"""
: param data: data to be encrypted
:param hmac_ Key: HMAC key
: Return: encrypted ciphertext
"""
#Base64 encoding for encrypted data
data = base64.b64encode(data.encode('utf-8')).decode("utf-8")
#Hmacsha1 is applied to the encoded data
hmac_code = hmac.new(hmac_key.encode(), data.encode(), sha1).hexdigest()
#The data after hmacsha1 were analyzed by MD5
sign = hashlib.md5(hmac_code.encode()).hexdigest()
return sign

if __name__ == '__main__':
hash_ HMAC ("text = smart content audit", "potential")

#### 2.2 symmetric encryption AES

(1) For symmetric encryption or asymmetric encryption, a third-party library needs to be installed. The password Library in Python is pycrypto, but it has stopped updating in 2012. Now pycryptodome is used to replace pycrypto.

pip install pycryptodome

(2) AES has five encryption modes, which are ECB, CBC, CTR, CFB and OFB. Take the ECB mode of AES as an example, AES also needs encryption key AES_ Key. It should be noted that if the encrypted data is less than 16 or 32 bits, it needs to be supplemented as a multiple of them. Take the multiple of 16 as an example:

import json
import base64
from Crypto.Cipher import AES

"""
STR is not a multiple of 16, so make it a multiple of 16
: param value: parameter to be encrypted
: Return: the parameter of the complement number
"""
while len(value) % 16 != 0:
value += b'
import json
import base64
from Crypto.Cipher import AES
"""
STR is not a multiple of 16, so make it a multiple of 16
: param value: parameter to be encrypted
: Return: the parameter of the complement number
"""
while len(value) % 16 != 0:
value += b'\0'
#Return bytes
return value
def encrypt_aes(data, aes_key):
"""
Encryption of AES in ECB mode
: param data: encrypted data
:param aes_ Key: the secret key of encryption
: Return: encrypted ciphertext
"""
#Secret key
key = aes_key.encode()
#Text to be encrypted
text = bytes(json.dumps(data).replace(" ", "").encode('utf-8'))
#Filling in encrypted data
#Initialize the encryptor and use ECB mode
aes = AES.new(key, AES.MODE_ECB)
#AES encryption first
aes_code = aes.encrypt(text)
#Convert to string form with Base64, execute encryption and transcoding to return bytes
encrypted_text = base64.encodebytes(aes_code)
return encrypted_text
if __name__ == '__main__':
Data = "Walkman AI focuses on the game field, has accumulated AI technology for many years, and provides one-stop audit of text, picture, audio / video content, game AI and data platform services."
aes_key = "1111111111111111"
encrypt_aes(data, aes_key)
' #Return bytes return value def encrypt_aes(data, aes_key): """ Encryption of AES in ECB mode : param data: encrypted data :param aes_ Key: the secret key of encryption : Return: encrypted ciphertext """ #Secret key key = aes_key.encode() #Text to be encrypted text = bytes(json.dumps(data).replace(" ", "").encode('utf-8')) #Filling in encrypted data text = add_to_16(text) #Initialize the encryptor and use ECB mode aes = AES.new(key, AES.MODE_ECB) #AES encryption first aes_code = aes.encrypt(text) #Convert to string form with Base64, execute encryption and transcoding to return bytes encrypted_text = base64.encodebytes(aes_code) return encrypted_text if __name__ == '__main__': Data = "Walkman AI focuses on the game field, has accumulated AI technology for many years, and provides one-stop audit of text, picture, audio / video content, game AI and data platform services." aes_key = "1111111111111111" encrypt_aes(data, aes_key)

#### 2.3 asymmetric encryption RSA

(1) You also need to install the pycryptodome library, which is the same as 3.2;

(2) RSA encryption needs public key to encrypt. It should be noted that sometimes when the amount of data to be encrypted is large, it needs to be encrypted by segments. The following is an example of segmented encryption. This method is also suitable for encryption with less data.

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

def cipher(data, rsa_key):
"""
Public key encryption
: param MSG: to encrypt content
: Return: encrypted ciphertext
"""
#Get public key
key = rsa_key
publickey = RSA.importKey(key)
#Segmented encryption
pk = PKCS1_v1_5.new(publickey)
encrypt_text = []
#Segment encryption of data
for i in range(0, len(data), 100):
cont = data[i:i + 100]
encrypt_text.append(pk.encrypt(cont.encode("utf-8")))
#Segmented encryption完进行拼接
cipher_text = b''.join(encrypt_text)
#Base64
result = base64.b64encode(cipher_text)
return result.decode()

if __name__ == '__main__':
Data = "Walkman AI focuses on the game field, has accumulated AI technology for many years, and provides one-stop audit of text, picture, audio / video content, game AI and data platform services."
#Read the file where the public key is stored to get the public key